[clang] [DRAFT][clang] Add experimental C++ profiles framework (P3589) and std::casting (PR #239372)

Michael Levine via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 5 12:59:58 PST 2026


https://github.com/levinem created https://github.com/llvm/llvm-project/pull/239372

Add experimental support for the C++ profiles framework proposed in P3589, behind the -cc1 option -fexperimental-cxx-profiles, together with a first profile, std::casting.

Framework:
- The [[profiles::enforce]], [[profiles::suppress]], [[profiles::require]] and [[profiles::exempt]] attributes, with the P3589 argument grammar. 'enforce' is accepted on an empty-declaration preceding every declaration of the translation unit and on a module declaration; 'require' on a module import declaration.
- -fcxx-profiles=<profile,...> enforces profiles for a whole translation unit; -fcxx-profiles-preview=<profile,...> reports their rules as warnings.
- Profiles enforced by a C++20 named module unit are serialized (SUBMODULE_CXX_PROFILE), inherited by implementation units, checked by 'require', and used to check instantiations of the module's templates.
- Rule checks record violations as Sema builds the relevant construct; they are reported when the outermost function (or the translation unit) is complete, so that suppressions on enclosing statements apply. Violations in templates are reported once. System headers and [[profiles::exempt]] headers are not checked.
- Each rule has its own -Wcxx-profile-<profile>-<rule> group; violations are errors by default and are only emitted when the profile is enforced.

std::casting (P3984R0 section 4; rules from P3081R2 section 4) rejects reinterpret_cast (other than to std::byte or to a pointer-sized integer), casts that cast away constness, static_cast downcasts, and static_cast from void *. C-style and functional-style casts are checked according to the conversion they perform, with a note offering the equivalent named cast.

To support this, C-style and functional-style casts in C++ now record how they were resolved ([expr.cast]p4) and whether they cast away constness. The information is serialized and shown in -ast-dump; it is also useful to tools such as clang-tidy, which currently re-derive it from the cast kind.

This change has not been built or tested yet.

Assisted-by: Claude Opus 5.5

>From 22bc670eae12a88468eb9951e266bfee1c5e6170 Mon Sep 17 00:00:00 2001
From: mlevine55 <mlevine55 at bloomberg.net>
Date: Tue, 27 Oct 2026 17:20:01 -0400
Subject: [PATCH] [clang] Add experimental C++ profiles framework (P3589) and
 std::casting

Add experimental support for the C++ profiles framework proposed in P3589,
behind the -cc1 option -fexperimental-cxx-profiles, together with a first
profile, std::casting.

Framework:
- The [[profiles::enforce]], [[profiles::suppress]], [[profiles::require]]
  and [[profiles::exempt]] attributes, with the P3589 argument grammar.
  'enforce' is accepted on an empty-declaration preceding every declaration
  of the translation unit and on a module declaration; 'require' on a module
  import declaration.
- -fcxx-profiles=<profile,...> enforces profiles for a whole translation
  unit; -fcxx-profiles-preview=<profile,...> reports their rules as warnings.
- Profiles enforced by a C++20 named module unit are serialized
  (SUBMODULE_CXX_PROFILE), inherited by implementation units, checked by
  'require', and used to check instantiations of the module's templates.
- Rule checks record violations as Sema builds the relevant construct; they
  are reported when the outermost function (or the translation unit) is
  complete, so that suppressions on enclosing statements apply. Violations in
  templates are reported once. System headers and [[profiles::exempt]]
  headers are not checked.
- Each rule has its own -Wcxx-profile-<profile>-<rule> group; violations are
  errors by default and are only emitted when the profile is enforced.

std::casting (P3984R0 section 4; rules from P3081R2 section 4) rejects
reinterpret_cast (other than to std::byte or to a pointer-sized integer),
casts that cast away constness, static_cast downcasts, and static_cast from
void *. C-style and functional-style casts are checked according to the
conversion they perform, with a note offering the equivalent named cast.

To support this, C-style and functional-style casts in C++ now record how
they were resolved ([expr.cast]p4) and whether they cast away constness. The
information is serialized and shown in -ast-dump; it is also useful to tools
such as clang-tidy, which currently re-derive it from the cast kind.

This change has not been built or tested yet.

Assisted-by: Claude Opus 5.5

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply at anthropic.com>
---
 clang/docs/CXXProfiles.md                     | 123 +++
 clang/docs/ReleaseNotes.md                    |  13 +
 clang/docs/index.md                           |   2 +
 clang/include/clang/AST/Expr.h                |  27 +
 clang/include/clang/AST/OperationKinds.h      |  12 +
 clang/include/clang/AST/Stmt.h                |  11 +
 clang/include/clang/Basic/Attr.td             |  52 +
 clang/include/clang/Basic/AttrDocs.td         |  96 ++
 .../include/clang/Basic/AttributeCommonInfo.h |  13 +-
 clang/include/clang/Basic/CXXProfiles.def     |  42 +
 clang/include/clang/Basic/CXXProfiles.h       |  58 ++
 clang/include/clang/Basic/DiagnosticGroups.td |  23 +
 .../clang/Basic/DiagnosticParseKinds.td       |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td        |  70 ++
 clang/include/clang/Basic/LangOptions.def     |   2 +
 clang/include/clang/Basic/LangOptions.h       |   8 +
 clang/include/clang/Basic/Module.h            |  11 +
 clang/include/clang/Options/Options.td        |  20 +
 clang/include/clang/Parse/Parser.h            |  43 +
 clang/include/clang/Sema/Sema.h               |   7 +
 clang/include/clang/Sema/SemaCXXProfiles.h    | 200 ++++
 .../include/clang/Serialization/ASTBitCodes.h |   4 +
 clang/lib/AST/JSONNodeDumper.cpp              |  25 +
 clang/lib/AST/TextNodeDumper.cpp              |  29 +
 clang/lib/Basic/Attributes.cpp                |   3 +-
 clang/lib/Basic/CMakeLists.txt                |   1 +
 clang/lib/Basic/CXXProfiles.cpp               |  63 ++
 clang/lib/Parse/ParseDeclCXX.cpp              | 155 +++
 clang/lib/Parse/Parser.cpp                    |  34 +-
 clang/lib/Sema/CMakeLists.txt                 |   1 +
 clang/lib/Sema/Sema.cpp                       |  13 +
 clang/lib/Sema/SemaCXXProfiles.cpp            | 908 ++++++++++++++++++
 clang/lib/Sema/SemaCast.cpp                   |  73 ++
 clang/lib/Sema/SemaDecl.cpp                   |   2 +-
 clang/lib/Sema/SemaDeclAttr.cpp               |  13 +
 clang/lib/Sema/SemaModule.cpp                 |   3 +
 clang/lib/Sema/SemaStmtAttr.cpp               |   3 +
 clang/lib/Serialization/ASTReader.cpp         |   9 +
 clang/lib/Serialization/ASTReaderStmt.cpp     |   4 +
 clang/lib/Serialization/ASTWriter.cpp         |  19 +
 clang/lib/Serialization/ASTWriterStmt.cpp     |   3 +
 .../ast-dump-cstyle-cast-interpretation.cpp   |  51 +
 .../test/AST/ast-dump-cxx-profiles-attrs.cpp  |  19 +
 clang/test/Modules/cxx-profiles.cppm          |  72 ++
 clang/test/Parser/cxx-profiles-attributes.cpp |  53 +
 .../Inputs/cxx-profiles-exempt-nested.h       |   1 +
 .../cxx-profiles/Inputs/cxx-profiles-exempt.h |   3 +
 .../Inputs/cxx-profiles-not-exempt.h          |   4 +
 .../Inputs/system/cxx-profiles-system.h       |   2 +
 .../SemaCXX/cxx-profiles/command-line.cpp     |  18 +
 clang/test/SemaCXX/cxx-profiles/enforce.cpp   |  26 +
 clang/test/SemaCXX/cxx-profiles/exempt.cpp    |  19 +
 clang/test/SemaCXX/cxx-profiles/preview.cpp   |   9 +
 .../test/SemaCXX/cxx-profiles/std-casting.cpp | 134 +++
 clang/test/SemaCXX/cxx-profiles/suppress.cpp  |  75 ++
 55 files changed, 2682 insertions(+), 8 deletions(-)
 create mode 100644 clang/docs/CXXProfiles.md
 create mode 100644 clang/include/clang/Basic/CXXProfiles.def
 create mode 100644 clang/include/clang/Basic/CXXProfiles.h
 create mode 100644 clang/include/clang/Sema/SemaCXXProfiles.h
 create mode 100644 clang/lib/Basic/CXXProfiles.cpp
 create mode 100644 clang/lib/Sema/SemaCXXProfiles.cpp
 create mode 100644 clang/test/AST/ast-dump-cstyle-cast-interpretation.cpp
 create mode 100644 clang/test/AST/ast-dump-cxx-profiles-attrs.cpp
 create mode 100644 clang/test/Modules/cxx-profiles.cppm
 create mode 100644 clang/test/Parser/cxx-profiles-attributes.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt-nested.h
 create mode 100644 clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt.h
 create mode 100644 clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-not-exempt.h
 create mode 100644 clang/test/SemaCXX/cxx-profiles/Inputs/system/cxx-profiles-system.h
 create mode 100644 clang/test/SemaCXX/cxx-profiles/command-line.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/enforce.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/exempt.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/preview.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/std-casting.cpp
 create mode 100644 clang/test/SemaCXX/cxx-profiles/suppress.cpp

diff --git a/clang/docs/CXXProfiles.md b/clang/docs/CXXProfiles.md
new file mode 100644
index 00000000000000..c60b3d0b03e226
--- /dev/null
+++ b/clang/docs/CXXProfiles.md
@@ -0,0 +1,123 @@
+# C++ Profiles
+
+```{contents}
+:local:
+```
+
+## Introduction
+
+**Experimental.** C++ profiles are being designed by WG21 (the framework is
+[P3589](https://wg21.link/P3589)) and are not part of any published C++
+standard. Clang's implementation is experimental, is enabled with the
+`-cc1` option `-fexperimental-cxx-profiles`, and may change incompatibly as
+the proposals evolve.
+
+A profile is a named set of rules that a translation unit or module can ask to
+have enforced. Code that violates an enforced rule is rejected. Profiles only
+restrict which programs are accepted: they never change the meaning of a
+program, overload resolution, template instantiation or SFINAE.
+
+Clang currently implements the profile framework and one profile,
+`std::casting`.
+
+## Enforcing a profile
+
+A profile is enforced by an attribute on an empty-declaration that precedes
+every other declaration of the translation unit (including declarations from
+included headers):
+
+```c++
+[[profiles::enforce(std::casting)]];
+#include <vector>
+```
+
+or on a module declaration:
+
+```c++
+export module Widgets [[profiles::enforce(std::casting)]];
+```
+
+A profile enforced on the module declaration of a primary module interface is
+also enforced in the implementation units of the module, and is advertised to
+importers, which can require it:
+
+```c++
+import Widgets [[profiles::require(std::casting)]];
+```
+
+`require` does not enforce the profile in the importing translation unit; the
+import is ill-formed if `Widgets` does not enforce `std::casting`.
+
+Profiles can also be enforced for a whole translation unit from the command
+line with `-fcxx-profiles=std::casting`. `-fcxx-profiles-preview=<profile>`
+checks the rules of a profile but reports violations as warnings, which is
+useful to evaluate a profile on existing code.
+
+Code is checked according to the profiles enforced where it is written. In
+particular, the instantiation of a template is checked according to the
+profiles enforced by the translation unit or module that defines the template,
+not by the one that instantiates it.
+
+Code in system headers is never checked. Other headers can be exempted with
+`[[profiles::exempt]]`, which exempts the named header and every header it
+includes:
+
+```c++
+[[profiles::enforce(std::casting)]];
+[[profiles::exempt(std::casting, quote_header: "legacy/ffi.h",
+                   justification: "C interface")]];
+#include "legacy/ffi.h"
+```
+
+The header is identified by matching the trailing components of its path.
+
+## Suppressing rules
+
+`[[profiles::suppress]]` turns off a profile, or one of its rules, for the
+tokens of a declaration or statement. An optional justification documents why:
+
+```c++
+unsigned bits(float f) {
+  [[profiles::suppress(std::casting, rule: reinterpret_cast,
+                       justification: "inspecting the representation")]]
+  return *reinterpret_cast<unsigned *>(&f);
+}
+```
+
+## Diagnostics
+
+Each rule of each profile is diagnosed in its own diagnostic group,
+`-Wcxx-profile-<profile>-<rule>`, contained in `-Wcxx-profile-<profile>` and
+`-Wcxx-profile`. Rule violations are errors by default. The diagnostics are only
+emitted when the profile is enforced; enabling the warning groups does not
+enforce a profile. Unknown profile and rule names are diagnosed with
+`-Wunknown-cxx-profiles`.
+
+## `std::casting`
+
+`std::casting` rejects casts that cannot be verified to use objects according to
+their types. It follows the casting rules of
+[P3081R2](https://wg21.link/P3081) section 4 (Type.1 to Type.4); P3984 lists
+"casting" as one of the profiles that make up type-and-resource safety. The rules
+apply to named casts and equally to C-style and functional-style casts that
+perform the same conversions; for those, a note offers to spell the cast as the
+named cast it performs.
+
+| Rule | Rejects |
+|---|---|
+| `reinterpret_cast` | `reinterpret_cast`, except to a pointer or reference to `std::byte`, from a pointer to an integer type that can hold any pointer, or a cast that only adds qualifiers |
+| `reinterpret_cast_char` | `reinterpret_cast` to a pointer or reference to `char` or `unsigned char` |
+| `const_cast` | casts that cast away constness (removing only `volatile` is permitted) |
+| `static_downcast` | `static_cast` from a base class to a derived class (use `dynamic_cast`) |
+| `static_cast_void` | `static_cast` from `void *` to a pointer to an object type other than `std::byte` |
+
+## Current limitations
+
+- Only `std::casting` is implemented.
+- Profiles enforced by a module are not recorded for the global module fragment
+  of that module, and a module partition implementation unit does not inherit
+  the profiles enforced on the primary module interface.
+- The compatibility of redeclarations across profiles (P3589
+  [decl.profile.enforce]p5) is not checked.
+- `[[profiles::exempt]]` matches headers by path suffix rather than by the
+  spelling of the `#include` directive.
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index db3c689bdd5001..37f2c5ec491e60 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -159,6 +159,12 @@ features cannot lower the translation-unit ABI level;
 
 ### AST Dumping Potentially Breaking Changes
 
+- The AST dump of a C-style or functional-style cast in C++ now shows how the
+  cast was resolved (`resolved_as_const_cast`, `resolved_as_reinterpret_cast`,
+  or `resolved_as_static_cast` when it also casts away constness) and whether it
+  casts away constness (`casts_away_const`). The JSON dump has the corresponding
+  `resolvedAs` and `castsAwayConst` attributes.
+
 ### Clang Frontend Potentially Breaking Changes
 
 - Templight support has been removed.
@@ -349,6 +355,13 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
 
 ### New Compiler Flags
 
+- Experimental support for C++ profiles (P3589) is available behind the
+  `-cc1` option `-fexperimental-cxx-profiles`. It implements the
+  `[[profiles::enforce]]`, `[[profiles::suppress]]`, `[[profiles::require]]`
+  and `[[profiles::exempt]]` attributes, the `-fcxx-profiles=` and
+  `-fcxx-profiles-preview=` options, and the `std::casting` profile. See
+  {doc}`CXXProfiles`.
+
 - New option `-fmodules-validate-directory-dependencies` makes an implicitly
   built module out of date when a header is added to a directory it enumerated,
   such as an umbrella directory or the directory of an umbrella header, after it
diff --git a/clang/docs/index.md b/clang/docs/index.md
index c67d07d317278c..c02dfca0809e00 100644
--- a/clang/docs/index.md
+++ b/clang/docs/index.md
@@ -23,6 +23,7 @@ ClangStaticAnalyzer
 ThreadSafetyAnalysis
 LifetimeSafety
 SafeBuffers
+CXXProfiles
 ScalableStaticAnalysis/index
 DataFlowAnalysisIntro
 FunctionEffectAnalysis
@@ -120,6 +121,7 @@ LLVMExceptionHandlingCodeGen
 * {doc}`ThreadSafetyAnalysis`
 * {doc}`LifetimeSafety`
 * {doc}`SafeBuffers`
+* {doc}`CXXProfiles`
 * {doc}`ScalableStaticAnalysis/index`
 * {doc}`DataFlowAnalysisIntro`
 * {doc}`FunctionEffectAnalysis`
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index b28b9a7a27019a..10db48c0e8d443 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3760,6 +3760,9 @@ class CastExpr : public Expr {
       : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
     CastExprBits.Kind = kind;
     CastExprBits.PartOfExplicitCast = false;
+    CastExprBits.CStyleInterpretation =
+        llvm::to_underlying(CStyleCastInterpretation::Unknown);
+    CastExprBits.CStyleCastsAwayConst = false;
     CastExprBits.BasePathSize = BasePathSize;
     assert((CastExprBits.BasePathSize == BasePathSize) &&
            "BasePathSize overflow!");
@@ -3772,6 +3775,9 @@ class CastExpr : public Expr {
            bool HasFPFeatures)
       : Expr(SC, Empty) {
     CastExprBits.PartOfExplicitCast = false;
+    CastExprBits.CStyleInterpretation =
+        llvm::to_underlying(CStyleCastInterpretation::Unknown);
+    CastExprBits.CStyleCastsAwayConst = false;
     CastExprBits.BasePathSize = BasePathSize;
     CastExprBits.HasFPFeatures = HasFPFeatures;
     assert((CastExprBits.BasePathSize == BasePathSize) &&
@@ -4023,6 +4029,27 @@ class ExplicitCastExpr : public CastExpr {
   /// casting to, as written in the source code.
   QualType getTypeAsWritten() const { return TInfo->getType(); }
 
+  /// For a C++ C-style or functional cast, returns how the cast was resolved
+  /// according to [expr.cast]p4. Returns CStyleCastInterpretation::Unknown for
+  /// other casts and for casts that were not resolved (e.g. dependent casts).
+  CStyleCastInterpretation getCStyleCastInterpretation() const {
+    return static_cast<CStyleCastInterpretation>(
+        CastExprBits.CStyleInterpretation);
+  }
+
+  /// For a C++ C-style or functional cast, returns true if the cast casts
+  /// away constness, i.e. it is a const_cast or is a static_cast or
+  /// reinterpret_cast followed by a const_cast.
+  bool getCStyleCastCastsAwayConst() const {
+    return CastExprBits.CStyleCastsAwayConst;
+  }
+
+  void setCStyleCastInterpretation(CStyleCastInterpretation Interpretation,
+                                   bool CastsAwayConst) {
+    CastExprBits.CStyleInterpretation = llvm::to_underlying(Interpretation);
+    CastExprBits.CStyleCastsAwayConst = CastsAwayConst;
+  }
+
   static bool classof(const Stmt *T) {
      return T->getStmtClass() >= firstExplicitCastExprConstant &&
             T->getStmtClass() <= lastExplicitCastExprConstant;
diff --git a/clang/include/clang/AST/OperationKinds.h b/clang/include/clang/AST/OperationKinds.h
index 679e0fdd4056d8..c40394206c83e1 100644
--- a/clang/include/clang/AST/OperationKinds.h
+++ b/clang/include/clang/AST/OperationKinds.h
@@ -45,6 +45,18 @@ enum ObjCBridgeCastKind {
   OBC_BridgeRetained
 };
 
+/// How a C-style or functional cast was resolved in C++ ([expr.cast]p4).
+enum class CStyleCastInterpretation {
+  /// Not a C++ C-style or functional cast, or not yet resolved.
+  Unknown,
+  /// Resolved as a const_cast.
+  Const,
+  /// Resolved as a static_cast (possibly followed by a const_cast).
+  Static,
+  /// Resolved as a reinterpret_cast (possibly followed by a const_cast).
+  Reinterpret
+};
+
 }  // end namespace clang
 
 #endif
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index f8e2192f189258..ae38648be00917 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -626,6 +626,7 @@ class alignas(void *) Stmt {
   class CastExprBitfields {
     friend class CastExpr;
     friend class ImplicitCastExpr;
+    friend class ExplicitCastExpr;
 
     LLVM_PREFERRED_TYPE(ExprBitfields)
     unsigned : NumExprBits;
@@ -639,6 +640,16 @@ class alignas(void *) Stmt {
     LLVM_PREFERRED_TYPE(bool)
     unsigned HasFPFeatures : 1;
 
+    /// For a C++ C-style or functional cast, how the cast was resolved.
+    /// Only set for CStyleCastExpr and CXXFunctionalCastExpr.
+    LLVM_PREFERRED_TYPE(CStyleCastInterpretation)
+    unsigned CStyleInterpretation : 2;
+
+    /// For a C++ C-style or functional cast, true if the cast casts away
+    /// constness. Only set for CStyleCastExpr and CXXFunctionalCastExpr.
+    LLVM_PREFERRED_TYPE(bool)
+    unsigned CStyleCastsAwayConst : 1;
+
     /// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
     /// here. ([implimits] Direct and indirect base classes [16384]).
     unsigned BasePathSize;
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 5de5059cc18c0e..92cc202d071ff4 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -443,6 +443,7 @@ def SYCLHost : LangOpt<"SYCLIsHost">;
 def SYCLDevice : LangOpt<"SYCLIsDevice">;
 def COnly : LangOpt<"", "!LangOpts.CPlusPlus">;
 def CPlusPlus : LangOpt<"CPlusPlus">;
+def CXXProfiles : LangOpt<"CXXProfiles">;
 def OpenCL : LangOpt<"OpenCL">;
 def ObjC : LangOpt<"ObjC">;
 def BlocksSupported : LangOpt<"Blocks">;
@@ -3607,6 +3608,57 @@ def Suppress : DeclOrStmtAttr {
   let Documentation = [SuppressDocs];
 }
 
+// C++ Profiles (P3589). The arguments of these attributes follow the
+// profile-designator grammar of P3589 and are parsed by
+// Parser::ParseCXXProfilesAttributeArgs.
+def ProfilesEnforce : Attr {
+  let Spellings = [CXX11<"profiles", "enforce">];
+  let Args = [VariadicStringArgument<"Designators">];
+  let Subjects = SubjectList<[Empty], ErrorDiag, "empty declarations">;
+  let LangOpts = [CXXProfiles];
+  let HasCustomParsing = 1;
+  let PragmaAttributeSupport = 0;
+  let Documentation = [ProfilesEnforceDocs];
+}
+
+def ProfilesSuppress : DeclOrStmtAttr {
+  let Spellings = [CXX11<"profiles", "suppress">];
+  let Args = [StringArgument<"ProfileName">, StringArgument<"Rule", /*opt=*/1>,
+              StringArgument<"Justification", /*opt=*/1>];
+  let Subjects = SubjectList<[
+    Stmt, Var, Field, ObjCProperty, Function, ObjCMethod, Record, ObjCInterface,
+    ObjCImplementation, Namespace
+  ], ErrorDiag, "variables, functions, classes, namespaces, and statements">;
+  let LangOpts = [CXXProfiles];
+  let HasCustomParsing = 1;
+  let PragmaAttributeSupport = 0;
+  let Documentation = [ProfilesSuppressDocs];
+}
+
+def ProfilesRequire : Attr {
+  let Spellings = [CXX11<"profiles", "require">];
+  let Args = [VariadicStringArgument<"Designators">];
+  let LangOpts = [CXXProfiles];
+  let HasCustomParsing = 1;
+  let PragmaAttributeSupport = 0;
+  // Only valid on a module-import-declaration, where it is checked by the
+  // parser; it is never attached to the AST.
+  let ASTNode = 0;
+  let Documentation = [ProfilesRequireDocs];
+}
+
+def ProfilesExempt : Attr {
+  let Spellings = [CXX11<"profiles", "exempt">];
+  let Args = [StringArgument<"ProfileName">, StringArgument<"Header">,
+              BoolArgument<"Angled">,
+              StringArgument<"Justification", /*opt=*/1>];
+  let Subjects = SubjectList<[Empty], ErrorDiag, "empty declarations">;
+  let LangOpts = [CXXProfiles];
+  let HasCustomParsing = 1;
+  let PragmaAttributeSupport = 0;
+  let Documentation = [ProfilesExemptDocs];
+}
+
 def SysVABI : DeclOrTypeAttr {
   let Spellings = [GCC<"sysv_abi">];
 //  let Subjects = [Function, ObjCMethod];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 687e022c7bd61f..e2fde42f4cff8d 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6786,6 +6786,102 @@ the `int` parameter is the one that represents the error.
 }];
 }
 
+def ProfilesEnforceDocs : Documentation {
+  let Category = DocCatDecl;
+  let Heading = "profiles::enforce";
+  let Content = [{
+**Experimental.** Requires `-fexperimental-cxx-profiles`.
+
+`[[profiles::enforce(profile)]]` requests that the rules of the named C++
+profile (P3589) are enforced. It may appear on an empty-declaration that
+precedes every other declaration of the translation unit, in which case the
+profile is enforced for the whole translation unit, or on a module
+declaration, in which case the profile is enforced from the module declaration
+onwards, in every implementation unit of the module, and is advertised to
+importers (see `profiles::require`).
+
+```c++
+[[profiles::enforce(std::casting)]];
+#include <vector>
+
+float f(int *p) {
+  return *reinterpret_cast<float *>(p); // error: std::casting forbids
+                                        // reinterpret_cast
+}
+```
+
+Violations of an enforced profile are diagnosed as errors in the
+`-Wcxx-profile-<profile>-<rule>` diagnostic groups. Code in system headers is
+not checked. Unknown profile names are diagnosed with `-Wunknown-cxx-profiles`
+and enforce nothing. Profiles can also be enforced with
+`-fcxx-profiles=<profile>,...`.
+  }];
+}
+
+def ProfilesSuppressDocs : Documentation {
+  let Category = DocCatStmt;
+  let Heading = "profiles::suppress";
+  let Content = [{
+**Experimental.** Requires `-fexperimental-cxx-profiles`.
+
+`[[profiles::suppress(profile [, rule: name] [, justification: "text"])]]`
+appertains to a declaration or a statement and suppresses the rules of the
+named profile (or only the named rule) within the tokens of that declaration or
+statement.
+
+```c++
+[[profiles::enforce(std::casting)]];
+
+unsigned bits(float f) {
+  [[profiles::suppress(std::casting, rule: reinterpret_cast,
+                       justification: "inspecting the representation")]]
+  return *reinterpret_cast<unsigned *>(&f);
+}
+```
+
+  }];
+}
+
+def ProfilesRequireDocs : Documentation {
+  let Category = DocCatDecl;
+  let Heading = "profiles::require";
+  let Content = [{
+**Experimental.** Requires `-fexperimental-cxx-profiles`.
+
+`[[profiles::require(profile)]]` may only appear on a module import
+declaration. The import is ill-formed unless the imported module enforces the
+profile on its module declaration. It does not enforce the profile in the
+importing translation unit.
+
+```c++
+import Utilities [[profiles::require(std::casting)]];
+```
+
+  }];
+}
+
+def ProfilesExemptDocs : Documentation {
+  let Category = DocCatDecl;
+  let Heading = "profiles::exempt";
+  let Content = [{
+**Experimental.** Requires `-fexperimental-cxx-profiles`.
+
+`[[profiles::exempt(profile, angle_header: "name")]]` or
+`[[profiles::exempt(profile, quote_header: "name")]]` exempts code in the
+named header, and in every header it includes, from the rules of the profile.
+The header is identified by matching the trailing components of its path
+against `name`. An optional `justification: "text"` argument documents the
+reason.
+
+```c++
+[[profiles::enforce(std::casting)]];
+[[profiles::exempt(std::casting, quote_header: "legacy/ffi.h")]];
+#include "legacy/ffi.h"
+```
+
+  }];
+}
+
 def SuppressDocs : Documentation {
   let Category = DocCatStmt;
   let Content = [{
diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h b/clang/include/clang/Basic/AttributeCommonInfo.h
index 77b5eb8a1a7cc6..bc34c246d97a6e 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -72,7 +72,18 @@ class AttributeCommonInfo {
     IgnoredAttribute,
     UnknownAttribute,
   };
-  enum class Scope { NONE, CLANG, GNU, MSVC, OMP, HLSL, VK, GSL, RISCV };
+  enum class Scope {
+    NONE,
+    CLANG,
+    GNU,
+    MSVC,
+    OMP,
+    HLSL,
+    VK,
+    GSL,
+    RISCV,
+    PROFILES
+  };
   enum class AttrArgsInfo {
     None,
     Optional,
diff --git a/clang/include/clang/Basic/CXXProfiles.def b/clang/include/clang/Basic/CXXProfiles.def
new file mode 100644
index 00000000000000..5ed8e91e4324a5
--- /dev/null
+++ b/clang/include/clang/Basic/CXXProfiles.def
@@ -0,0 +1,42 @@
+//===--- CXXProfiles.def - C++ profiles registry ----------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the C++ profiles (P3589) known to Clang and their rules.
+// Users of this file define CXX_PROFILE and/or CXX_PROFILE_RULE before
+// including it.
+//
+//===----------------------------------------------------------------------===//
+
+// CXX_PROFILE(ID, NAME)
+//   ID   - the enumerator name in clang::CXXProfileID.
+//   NAME - the profile name as written in a profile designator.
+#ifndef CXX_PROFILE
+#define CXX_PROFILE(ID, NAME)
+#endif
+
+// CXX_PROFILE_RULE(PROFILE, ID, NAME)
+//   PROFILE - the ID of the profile the rule belongs to.
+//   ID      - the enumerator name in clang::CXXProfileRuleID.
+//   NAME    - the rule name as written in a 'rule:' argument of
+//             [[profiles::suppress]].
+#ifndef CXX_PROFILE_RULE
+#define CXX_PROFILE_RULE(PROFILE, ID, NAME)
+#endif
+
+// std::casting: no unverifiable casts (P3984R0 section 4; the rules follow
+// P3081R2 section 4, Type.1-Type.4).
+CXX_PROFILE(StdCasting, "std::casting")
+CXX_PROFILE_RULE(StdCasting, StdCastingReinterpretCast, "reinterpret_cast")
+CXX_PROFILE_RULE(StdCasting, StdCastingReinterpretCastChar,
+                 "reinterpret_cast_char")
+CXX_PROFILE_RULE(StdCasting, StdCastingConstCast, "const_cast")
+CXX_PROFILE_RULE(StdCasting, StdCastingStaticDowncast, "static_downcast")
+CXX_PROFILE_RULE(StdCasting, StdCastingStaticCastVoid, "static_cast_void")
+
+#undef CXX_PROFILE
+#undef CXX_PROFILE_RULE
diff --git a/clang/include/clang/Basic/CXXProfiles.h b/clang/include/clang/Basic/CXXProfiles.h
new file mode 100644
index 00000000000000..4097969e27363f
--- /dev/null
+++ b/clang/include/clang/Basic/CXXProfiles.h
@@ -0,0 +1,58 @@
+//===--- CXXProfiles.h - C++ profiles registry ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Defines the registry of C++ profiles (P3589) known to Clang.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_CXXPROFILES_H
+#define LLVM_CLANG_BASIC_CXXPROFILES_H
+
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/StringRef.h"
+#include <optional>
+
+namespace clang {
+
+/// A C++ profile known to Clang.
+enum class CXXProfileID {
+#define CXX_PROFILE(ID, NAME) ID,
+#include "clang/Basic/CXXProfiles.def"
+};
+
+/// A rule of a C++ profile known to Clang.
+enum class CXXProfileRuleID {
+#define CXX_PROFILE_RULE(PROFILE, ID, NAME) ID,
+#include "clang/Basic/CXXProfiles.def"
+};
+
+/// Returns the name of \p Profile as written in a profile designator.
+StringRef getCXXProfileName(CXXProfileID Profile);
+
+/// Returns the name of \p Rule as written in a 'rule:' argument.
+StringRef getCXXProfileRuleName(CXXProfileRuleID Rule);
+
+/// Returns the profile that \p Rule belongs to.
+CXXProfileID getCXXProfileOfRule(CXXProfileRuleID Rule);
+
+/// Looks up a profile by name, e.g. "std::casting".
+std::optional<CXXProfileID> lookupCXXProfile(StringRef Name);
+
+/// Looks up a rule of \p Profile by name, e.g. "reinterpret_cast".
+std::optional<CXXProfileRuleID> lookupCXXProfileRule(CXXProfileID Profile,
+                                                     StringRef Name);
+
+/// Returns the profile name of a profile designator, i.e. the designator
+/// without its argument list. For example, returns "acme::hardened" for
+/// "acme::hardened(level: 3)".
+StringRef getCXXProfileDesignatorName(StringRef Designator);
+
+} // namespace clang
+
+#endif // LLVM_CLANG_BASIC_CXXPROFILES_H
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index b3bb2fb1b53fdc..41d9ee472fe11b 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -2022,6 +2022,29 @@ def UnsafeBufferUsageInStringView : DiagGroup<"unsafe-buffer-usage-in-string-vie
 def UnsafeBufferUsageMainArgv : DiagGroup<"unsafe-buffer-usage-main-argv">;
 def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", [UnsafeBufferUsageInContainer, UnsafeBufferUsageInLibcCall, UnsafeBufferUsageInUniquePtrArrayAccess, UnsafeBufferUsageInStaticSizedArray, UnsafeBufferUsageInFormatAttrCall, UnsafeBufferUsageInStringView, UnsafeBufferUsageMainArgv]>;
 
+// C++ profiles (P3589). Each rule of each profile has its own group, so that
+// rules can be suppressed individually; the rule diagnostics are only emitted
+// when the profile is enforced.
+def CXXProfileStdCastingReinterpretCast
+    : DiagGroup<"cxx-profile-std-casting-reinterpret-cast">;
+def CXXProfileStdCastingReinterpretCastChar
+    : DiagGroup<"cxx-profile-std-casting-reinterpret-cast-char">;
+def CXXProfileStdCastingConstCast
+    : DiagGroup<"cxx-profile-std-casting-const-cast">;
+def CXXProfileStdCastingStaticDowncast
+    : DiagGroup<"cxx-profile-std-casting-static-downcast">;
+def CXXProfileStdCastingStaticCastVoid
+    : DiagGroup<"cxx-profile-std-casting-static-cast-void">;
+def CXXProfileStdCasting
+    : DiagGroup<"cxx-profile-std-casting",
+                [CXXProfileStdCastingReinterpretCast,
+                 CXXProfileStdCastingReinterpretCastChar,
+                 CXXProfileStdCastingConstCast,
+                 CXXProfileStdCastingStaticDowncast,
+                 CXXProfileStdCastingStaticCastVoid]>;
+def CXXProfile : DiagGroup<"cxx-profile", [CXXProfileStdCasting]>;
+def UnknownCXXProfiles : DiagGroup<"unknown-cxx-profiles">;
+
 // Warnings and notes InstallAPI verification.
 def InstallAPIViolation : DiagGroup<"installapi-violation">;
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 33eeb3762cd34e..77c64d28288412 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1661,6 +1661,12 @@ def err_attribute_not_module_attr : Error<
   "%0 attribute cannot be applied to a module">;
 def err_keyword_not_module_attr : Error<
   "%0 cannot be applied to a module">;
+def err_cxx_profiles_expected_profile_name : Error<
+  "expected a profile name">;
+def err_cxx_profiles_expected_named_argument : Error<
+  "expected 'name: value' argument in %0 attribute">;
+def err_cxx_profiles_invalid_argument_token : Error<
+  "invalid token in profile argument">;
 def err_attribute_not_import_attr : Error<
   "%0 attribute cannot be applied to a module import">;
 def err_keyword_not_import_attr : Error<
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3eba313f0b0e6e..8c01e7eb92106d 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12928,6 +12928,76 @@ def err_invalid_type_for_program_scope_var : Error<
   "the %0 type cannot be used to declare a program scope variable">;
 }
 
+let CategoryName = "C++ Profiles Issue" in {
+// Framework diagnostics.
+def err_cxx_profiles_attr_requires_profile : Error<
+  "%0 attribute requires %select{at least one profile designator|"
+  "a profile name}1">;
+def err_cxx_profiles_enforce_not_at_tu_scope : Error<
+  "%0 attribute must appear at translation unit scope">;
+def err_cxx_profiles_enforce_after_decl : Error<
+  "%0 attribute must precede every declaration in the translation unit">;
+def note_cxx_profiles_first_decl : Note<"first declaration is here">;
+def err_cxx_profiles_enforce_mismatch : Error<
+  "profile '%0' is already enforced with designator '%1'">;
+def note_cxx_profiles_previous_enforce : Note<
+  "profile '%0' was enforced here">;
+def note_cxx_profiles_enforced_on_command_line : Note<
+  "profile '%0' was enforced on the command line">;
+def warn_cxx_profiles_unknown_profile : Warning<
+  "unknown profile '%0'%select{; it will not be enforced|}1">,
+  InGroup<UnknownCXXProfiles>;
+def warn_cxx_profiles_unknown_rule : Warning<
+  "unknown rule '%0' of profile '%1'; the suppression has no effect">,
+  InGroup<UnknownCXXProfiles>;
+def warn_cxx_profiles_unknown_argument : Warning<
+  "unknown argument '%0' in %1 attribute ignored">,
+  InGroup<IgnoredAttributes>;
+def err_cxx_profiles_require_not_on_import : Error<
+  "%0 attribute may only appear on a module import declaration">;
+def err_cxx_profiles_require_not_enforced : Error<
+  "module '%0' does not enforce profile '%1'">;
+def err_cxx_profiles_require_not_named_module : Error<
+  "%0 attribute requires a C++20 named module or header unit">;
+def err_cxx_profiles_exempt_requires_header : Error<
+  "%0 attribute requires an 'angle_header' or 'quote_header' argument">;
+def err_cxx_profiles_argument_requires_string : Error<
+  "argument '%0' of %1 attribute must be a string literal">;
+def err_cxx_profiles_not_enabled : Error<
+  "'-fcxx-profiles%select{|-preview}0=' requires "
+  "'-fexperimental-cxx-profiles'">;
+
+// std::casting
+def warn_cxx_profile_casting_reinterpret_cast : Warning<
+  "%0 forbids %select{reinterpret_cast|a C-style cast that performs a "
+  "reinterpret_cast|a functional-style cast that performs a reinterpret_cast}1 "
+  "from %2 to %3">,
+  InGroup<CXXProfileStdCastingReinterpretCast>, DefaultError;
+def warn_cxx_profile_casting_reinterpret_cast_char : Warning<
+  "%0 forbids %select{reinterpret_cast|a C-style cast that performs a "
+  "reinterpret_cast|a functional-style cast that performs a reinterpret_cast}1 "
+  "from %2 to %3">,
+  InGroup<CXXProfileStdCastingReinterpretCastChar>, DefaultError;
+def warn_cxx_profile_casting_const_cast : Warning<
+  "%0 forbids %select{const_cast|a C-style cast|a functional-style cast}1 that "
+  "casts away constness from %2 to %3">,
+  InGroup<CXXProfileStdCastingConstCast>, DefaultError;
+def warn_cxx_profile_casting_static_downcast : Warning<
+  "%0 forbids %select{static_cast|a C-style cast|a functional-style cast}1 "
+  "from base class %2 to derived class %3">,
+  InGroup<CXXProfileStdCastingStaticDowncast>, DefaultError;
+def warn_cxx_profile_casting_static_cast_void : Warning<
+  "%0 forbids %select{static_cast|a C-style cast|a functional-style cast}1 "
+  "from %2 to %3">,
+  InGroup<CXXProfileStdCastingStaticCastVoid>, DefaultError;
+def note_cxx_profile_casting_use_dynamic_cast : Note<
+  "use 'dynamic_cast' to perform a checked conversion">;
+def note_cxx_profile_casting_use_bit_cast : Note<
+  "use 'std::bit_cast' to reinterpret the object representation">;
+def note_cxx_profile_casting_named_cast : Note<
+  "use '%0' to make the conversion explicit">;
+} // end of C++ Profiles category
+
 let CategoryName = "Modules Issue" in {
 def err_module_decl_in_module_map_module : Error<
   "'module' declaration found while building module from module map">;
diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def
index b4a57a9c0944b1..1903e1b8db12d5 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -524,6 +524,8 @@ LANGOPT(CheckConstexprFunctionBodies, 1, 1, Benign,
 
 LANGOPT(BoundsSafety, 1, 0, NotCompatible, "Bounds safety extension for C")
 
+LANGOPT(CXXProfiles, 1, 0, Benign, "experimental C++ profiles (P3589)")
+
 LANGOPT(DebugRunLifetimeSafety, 1, 0, Benign, "Run lifetime safety analysis for C++. Does not enable warnings.")
 
 LANGOPT(EnableLifetimeSafetyInC, 1, 1, Benign, "Lifetime safety analysis for C")
diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h
index 8607fbae8d8fce..01e3f502902f39 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -590,6 +590,14 @@ class LangOptions : public LangOptionsBase {
 
   std::vector<std::string> OverflowPatternExclusionValues;
 
+  /// The C++ profiles (P3589) enforced for the whole translation unit by
+  /// -fcxx-profiles=.
+  std::vector<std::string> CXXProfilesEnforced;
+
+  /// The C++ profiles (P3589) whose rules are checked, but diagnosed as
+  /// warnings rather than errors, by -fcxx-profiles-preview=.
+  std::vector<std::string> CXXProfilesPreview;
+
   /// The seed used by the randomize structure layout feature.
   std::string RandstructSeed;
 
diff --git a/clang/include/clang/Basic/Module.h b/clang/include/clang/Basic/Module.h
index 4d304b8f006b60..e1e934b39f79b0 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -730,6 +730,17 @@ class alignas(8) Module {
   /// (intentionally) change how this module is built.
   std::vector<std::string> ConfigMacros;
 
+  /// The C++ profile designators (P3589) enforced for the whole module unit,
+  /// by an enforce attribute that precedes every declaration or by
+  /// -fcxx-profiles=. Only meaningful for C++20 named modules.
+  std::vector<std::string> CXXProfilesUnitEnforced;
+
+  /// The C++ profile designators (P3589) enforced on the module declaration.
+  /// They are enforced in the module purview and in the implementation units
+  /// of the module, and are advertised to importers. Only meaningful for C++20
+  /// named modules.
+  std::vector<std::string> CXXProfilesModuleEnforced;
+
   /// An unresolved conflict with another module.
   struct UnresolvedConflict {
     /// The (unresolved) module id.
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 4419e3cf6f98c5..d6a6ded3fd248c 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -2125,6 +2125,26 @@ defm bounds_safety : BoolFOption<
   BothFlags<[], [CC1Option],
           " experimental bounds safety extension for C">>;
 
+defm experimental_cxx_profiles : BoolFOption<
+  "experimental-cxx-profiles",
+  LangOpts<"CXXProfiles">, DefaultFalse,
+  PosFlag<SetTrue, [], [CC1Option], "Enable">,
+  NegFlag<SetFalse, [], [CC1Option], "Disable">,
+  BothFlags<[], [CC1Option],
+          " experimental support for C++ profiles (P3589)">>,
+  ShouldParseIf<cplusplus.KeyPath>;
+def fcxx_profiles_EQ : CommaJoined<["-"], "fcxx-profiles=">,
+  Visibility<[CC1Option]>, MetaVarName<"<profile>,...">,
+  HelpText<"Enforce the given C++ profiles for the whole translation unit "
+           "(requires -fexperimental-cxx-profiles)">,
+  MarshallingInfoStringVector<LangOpts<"CXXProfilesEnforced">>;
+def fcxx_profiles_preview_EQ : CommaJoined<["-"], "fcxx-profiles-preview=">,
+  Visibility<[CC1Option]>, MetaVarName<"<profile>,...">,
+  HelpText<"Check the rules of the given C++ profiles for the whole "
+           "translation unit, diagnosing violations as warnings (requires "
+           "-fexperimental-cxx-profiles)">,
+  MarshallingInfoStringVector<LangOpts<"CXXProfilesPreview">>;
+
 defm debug_run_lifetime_safety : BoolFOption<
   "debug-run-lifetime-safety",
   LangOpts<"DebugRunLifetimeSafety">, DefaultFalse,
diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
index 5237d767affdd0..be80f3c21e2b68 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -3054,6 +3054,49 @@ class Parser : public CodeCompletionHandler {
   void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
                                 CachedTokens &OpenMPTokens);
 
+  /// Parse the arguments of a C++ profiles attribute (P3589), i.e. an
+  /// attribute in the 'profiles' attribute namespace.
+  ///
+  /// \verbatim
+  ///   profiles-attribute-argument-clause:
+  ///     '(' profile-designator-list ')'          [enforce, require]
+  ///     '(' profile-name named-argument-list ')' [suppress, exempt]
+  ///
+  ///   profile-designator:
+  ///     profile-name
+  ///     profile-name '(' profile-argument-list ')'
+  ///
+  ///   profile-name:
+  ///     identifier
+  ///     profile-name '::' identifier
+  ///
+  ///   named-argument-list:
+  ///     <empty>
+  ///     named-argument-list ',' identifier ':' non-comma-balanced-token
+  /// \endverbatim
+  ///
+  /// Profile designators and token values are recorded as identifier
+  /// arguments holding their spelling; string literal values are recorded as
+  /// expression arguments.
+  void ParseCXXProfilesAttributeArgs(IdentifierInfo *AttrName,
+                                     SourceLocation AttrNameLoc,
+                                     ParsedAttributes &Attrs,
+                                     SourceLocation *EndLoc,
+                                     IdentifierInfo *ScopeName,
+                                     SourceLocation ScopeLoc,
+                                     ParsedAttr::Form Form);
+
+  /// Parse a profile designator (or, if \p AllowArguments is false, a
+  /// profile name) and append its canonical spelling to \p Spelling.
+  /// \returns true on error.
+  bool ParseCXXProfileDesignator(std::string &Spelling, SourceLocation &Loc,
+                                 bool AllowArguments);
+
+  /// Parse a balanced token (a single token other than a comma or closing
+  /// bracket, or a bracketed token sequence) and append its spelling to
+  /// \p Spelling. \returns true on error.
+  bool ParseCXXProfileBalancedToken(std::string &Spelling);
+
   /// Parse a C++11 or C23 attribute-specifier.
   ///
   /// \verbatim
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 0d207679d1f4d8..5acc19e90610c5 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -164,6 +164,7 @@ class SemaAVR;
 class SemaBPF;
 class SemaCodeCompletion;
 class SemaCUDA;
+class SemaCXXProfiles;
 class SemaDirectX;
 class SemaHLSL;
 class SemaHexagon;
@@ -1500,6 +1501,11 @@ class Sema final : public SemaBase {
     return *CUDAPtr;
   }
 
+  SemaCXXProfiles &CXXProfiles() {
+    assert(CXXProfilesPtr);
+    return *CXXProfilesPtr;
+  }
+
   SemaDirectX &DirectX() {
     assert(DirectXPtr);
     return *DirectXPtr;
@@ -1643,6 +1649,7 @@ class Sema final : public SemaBase {
   std::unique_ptr<SemaBPF> BPFPtr;
   std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
   std::unique_ptr<SemaCUDA> CUDAPtr;
+  std::unique_ptr<SemaCXXProfiles> CXXProfilesPtr;
   std::unique_ptr<SemaDirectX> DirectXPtr;
   std::unique_ptr<SemaHLSL> HLSLPtr;
   std::unique_ptr<SemaHexagon> HexagonPtr;
diff --git a/clang/include/clang/Sema/SemaCXXProfiles.h b/clang/include/clang/Sema/SemaCXXProfiles.h
new file mode 100644
index 00000000000000..a0dff44a6ca16c
--- /dev/null
+++ b/clang/include/clang/Sema/SemaCXXProfiles.h
@@ -0,0 +1,200 @@
+//===----- SemaCXXProfiles.h ---- C++ profiles (P3589) ---------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+/// \file
+/// This file declares semantic analysis for C++ profiles (P3589): the
+/// profiles::enforce, profiles::suppress, profiles::require and
+/// profiles::exempt attributes, and the checking of profile rules.
+///
+/// Rule checks run where Sema builds the relevant construct, but violations
+/// are only recorded there. They are reported once the outermost enclosing
+/// function (or the translation unit) is complete, so that
+/// [[profiles::suppress]] attributes on enclosing statements, which are
+/// attached after the statement has been analyzed, can be taken into account.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_SEMA_SEMACXXPROFILES_H
+#define LLVM_CLANG_SEMA_SEMACXXPROFILES_H
+
+#include "clang/AST/ASTFwd.h"
+#include "clang/AST/Type.h"
+#include "clang/Basic/CXXProfiles.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Sema/SemaBase.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/SmallVector.h"
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace clang {
+class Attr;
+class ExplicitCastExpr;
+class ImportDecl;
+class Module;
+class ParsedAttr;
+class ProfilesSuppressAttr;
+
+class SemaCXXProfiles : public SemaBase {
+public:
+  SemaCXXProfiles(Sema &S);
+
+  /// Process the profiles enforced on the command line.
+  void ActOnStartOfTranslationUnit();
+
+  /// Report the remaining profile violations and record the profiles
+  /// enforced by the current module unit, if any.
+  void ActOnEndOfTranslationUnit();
+
+  /// Report the profile violations recorded so far. Called when the
+  /// outermost function scope is popped and at the end of the translation
+  /// unit.
+  void flushPendingViolations();
+
+  /// \name Attributes
+  /// @{
+  void handleEnforceAttr(Decl *D, const ParsedAttr &AL);
+  void handleSuppressAttr(Decl *D, const ParsedAttr &AL);
+  Attr *handleSuppressStmtAttr(Stmt *St, const ParsedAttr &AL);
+  void handleExemptAttr(Decl *D, const ParsedAttr &AL);
+  /// Diagnose a [[profiles::require]] attribute that does not appertain to a
+  /// module import declaration.
+  void handleMisplacedRequireAttr(const ParsedAttr &AL);
+  /// @}
+
+  /// \name Modules
+  /// @{
+
+  /// Called when a module declaration has been processed. \p Interface is the
+  /// primary module interface implicitly imported by a module implementation
+  /// unit, if any.
+  void ActOnModuleDecl(Module *Mod, Module *Interface,
+                       SourceLocation ModuleLoc);
+
+  /// Process a [[profiles::enforce]] attribute on the module declaration.
+  void ActOnModuleDeclEnforceAttr(const ParsedAttr &AL);
+
+  /// Check a [[profiles::require]] attribute on a module import declaration.
+  void ActOnModuleImportRequireAttr(ImportDecl *Import, const ParsedAttr &AL);
+  /// @}
+
+  /// \name Rule checks
+  /// @{
+
+  /// Check an explicit cast against the rules of std::casting.
+  /// \p CastAwayQualifiers holds the qualifiers the cast casts away
+  /// ([expr.const.cast]), if it casts away constness.
+  void checkExplicitCast(const ExplicitCastExpr *E,
+                         std::optional<Qualifiers> CastAwayQualifiers);
+  /// @}
+
+private:
+  struct EnforcedProfile {
+    /// The profile, if it is known to Clang.
+    std::optional<CXXProfileID> ID;
+    /// The profile designator as written (canonical spelling).
+    std::string Designator;
+    /// The location of the designator; invalid if the profile is enforced on
+    /// the command line or inherited from the primary module interface.
+    SourceLocation Loc;
+  };
+
+  struct SuppressionSite {
+    CXXProfileID Profile;
+    /// The suppressed rule, or std::nullopt if every rule of the profile is
+    /// suppressed.
+    std::optional<CXXProfileRuleID> Rule;
+    /// The declaration or statement the suppression appertains to.
+    llvm::PointerUnion<const Decl *, const Stmt *> Node;
+  };
+
+  struct ExemptHeader {
+    CXXProfileID Profile;
+    std::string Header;
+  };
+
+  struct PendingViolation {
+    CXXProfileRuleID Rule;
+    /// The declaration context in which the violation was found; used to find
+    /// the enforcing unit and suppressions of templates from other modules.
+    const Decl *Owner;
+    PartialDiagnosticAt Diag;
+    SmallVector<PartialDiagnosticAt, 1> Notes;
+  };
+
+  /// Record the profile named by \p Designator as enforced in \p List.
+  /// Returns false if it was already enforced (or conflicts with an existing
+  /// enforcement, which is diagnosed if \p Diagnose is true).
+  bool addEnforcedProfile(StringRef Designator, SourceLocation Loc,
+                          SmallVectorImpl<EnforcedProfile> &List,
+                          bool Diagnose = true);
+
+  /// Returns the first non-empty declaration in the translation unit that
+  /// precedes \p D, if any.
+  const Decl *findPrecedingNonEmptyDecl(const Decl *D) const;
+
+  bool isEnforcedInCurrentUnit(CXXProfileID Profile, SourceLocation Loc) const;
+
+  /// Returns true if the rules of \p Profile apply to code at \p Loc within
+  /// the declaration context \p Owner.
+  bool isEnforced(CXXProfileID Profile, SourceLocation Loc,
+                  const Decl *Owner) const;
+
+  /// Returns true if code at \p Loc is exempt from \p Profile: it is in a
+  /// system header or in a header named by a [[profiles::exempt]] attribute.
+  bool isExempt(CXXProfileID Profile, SourceLocation Loc) const;
+
+  /// Returns true if the rules of \p Profile should be checked for code at
+  /// \p Loc in the current context.
+  bool shouldCheck(CXXProfileID Profile, SourceLocation Loc) const;
+
+  bool isSuppressed(CXXProfileRuleID Rule, SourceLocation Loc,
+                    const Decl *Owner);
+
+  std::optional<SuppressionSite> makeSuppressionSite(
+      const ProfilesSuppressAttr *A,
+      llvm::PointerUnion<const Decl *, const Stmt *> Node) const;
+
+  /// Returns the suppressions that appertain to a template from an AST file
+  /// whose instantiation is being checked in this translation unit.
+  ArrayRef<SuppressionSite> getImportedSuppressionSites(const Decl *Pattern);
+
+  void addViolation(CXXProfileRuleID Rule, PartialDiagnosticAt Diag,
+                    SmallVector<PartialDiagnosticAt, 1> Notes = {});
+
+  /// Record the profiles enforced by the current module unit on its Module so
+  /// that they are serialized.
+  void updateModuleRecord();
+
+  bool Initialized = false;
+  SmallVector<EnforcedProfile, 2> UnitProfiles;
+  SmallVector<EnforcedProfile, 2> ModuleProfiles;
+  SmallVector<CXXProfileID, 1> PreviewProfiles;
+  SourceLocation ModuleDeclLoc;
+  Module *UnitModule = nullptr;
+  Module *PrimaryInterface = nullptr;
+
+  SmallVector<SuppressionSite, 4> SuppressionSites;
+  llvm::DenseMap<const Decl *, SmallVector<SuppressionSite, 2>>
+      ImportedSuppressionSites;
+  SmallVector<ExemptHeader, 1> ExemptHeaders;
+
+  SmallVector<PendingViolation, 4> PendingViolations;
+  /// The (rule, location) pairs already reported, so that a violation in a
+  /// template is reported once rather than once per instantiation.
+  llvm::DenseSet<std::pair<unsigned, SourceLocation::UIntTy>>
+      ReportedViolations;
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_SEMA_SEMACXXPROFILES_H
diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h
index ae3a2fad6ebe7f..f282ae52c613b3 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -891,6 +891,10 @@ enum SubmoduleRecordTypes {
   /// Specifies a direct submodule by name and ID, enabling on-demand
   /// deserialization of children without loading the entire submodule block.
   SUBMODULE_CHILD = 19,
+
+  /// Specifies a C++ profile designator enforced by a C++20 named module
+  /// unit, either for the whole unit or on its module declaration.
+  SUBMODULE_CXX_PROFILE = 20,
 };
 
 /// Record types used within a comments block.
diff --git a/clang/lib/AST/JSONNodeDumper.cpp b/clang/lib/AST/JSONNodeDumper.cpp
index 4cea437db41507..4dba788b10a4d9 100644
--- a/clang/lib/AST/JSONNodeDumper.cpp
+++ b/clang/lib/AST/JSONNodeDumper.cpp
@@ -1511,6 +1511,31 @@ void JSONNodeDumper::VisitCastExpr(const CastExpr *CE) {
   // from the inner[] array.
   if (const NamedDecl *ND = CE->getConversionFunction())
     JOS.attribute("conversionFunc", createBareDeclRef(ND));
+  if (isa<CStyleCastExpr, CXXFunctionalCastExpr>(CE)) {
+    const auto *ECE = cast<ExplicitCastExpr>(CE);
+    CStyleCastInterpretation Interpretation =
+        ECE->getCStyleCastInterpretation();
+    bool CastsAwayConst = ECE->getCStyleCastCastsAwayConst();
+    // Only print the interpretation when the cast is not a plain static_cast.
+    if (Interpretation != CStyleCastInterpretation::Unknown &&
+        (Interpretation != CStyleCastInterpretation::Static ||
+         CastsAwayConst)) {
+      switch (Interpretation) {
+      case CStyleCastInterpretation::Unknown:
+        llvm_unreachable("handled above");
+      case CStyleCastInterpretation::Const:
+        JOS.attribute("resolvedAs", "const_cast");
+        break;
+      case CStyleCastInterpretation::Static:
+        JOS.attribute("resolvedAs", "static_cast");
+        break;
+      case CStyleCastInterpretation::Reinterpret:
+        JOS.attribute("resolvedAs", "reinterpret_cast");
+        break;
+      }
+      attributeOnlyIfTrue("castsAwayConst", CastsAwayConst);
+    }
+  }
 }
 
 void JSONNodeDumper::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index d7476eacbd27a0..076f1f636b8072 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1651,6 +1651,32 @@ void TextNodeDumper::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Node) {
   VisitCallExpr(Node);
 }
 
+/// Print how a C++ C-style or functional cast was resolved, unless it is a
+/// plain static_cast (the common case).
+static void dumpCStyleCastInterpretation(raw_ostream &OS,
+                                         const ExplicitCastExpr *Node) {
+  CStyleCastInterpretation Interpretation = Node->getCStyleCastInterpretation();
+  bool CastsAwayConst = Node->getCStyleCastCastsAwayConst();
+  if (Interpretation == CStyleCastInterpretation::Unknown ||
+      (Interpretation == CStyleCastInterpretation::Static && !CastsAwayConst))
+    return;
+  switch (Interpretation) {
+  case CStyleCastInterpretation::Unknown:
+    llvm_unreachable("handled above");
+  case CStyleCastInterpretation::Const:
+    OS << " resolved_as_const_cast";
+    break;
+  case CStyleCastInterpretation::Static:
+    OS << " resolved_as_static_cast";
+    break;
+  case CStyleCastInterpretation::Reinterpret:
+    OS << " resolved_as_reinterpret_cast";
+    break;
+  }
+  if (CastsAwayConst)
+    OS << " casts_away_const";
+}
+
 void TextNodeDumper::VisitCastExpr(const CastExpr *Node) {
   OS << " <";
   {
@@ -1659,6 +1685,8 @@ void TextNodeDumper::VisitCastExpr(const CastExpr *Node) {
   }
   dumpBasePath(OS, Node);
   OS << ">";
+  if (const auto *CStyle = dyn_cast<CStyleCastExpr>(Node))
+    dumpCStyleCastInterpretation(OS, CStyle);
   if (Node->hasStoredFPFeatures())
     printFPOptions(Node->getFPFeatures());
 }
@@ -1864,6 +1892,7 @@ void TextNodeDumper::VisitCXXFunctionalCastExpr(
     const CXXFunctionalCastExpr *Node) {
   OS << " functional cast to " << Node->getTypeAsWritten().getAsString() << " <"
      << Node->getCastKindName() << ">";
+  dumpCStyleCastInterpretation(OS, Node);
   if (Node->hasStoredFPFeatures())
     printFPOptions(Node->getFPFeatures());
 }
diff --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 8ee45a338c57cf..6674d1fda0e57b 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -236,7 +236,8 @@ getScopeFromNormalizedScopeName(StringRef ScopeName) {
       .Case("vk", AttributeCommonInfo::Scope::VK)
       .Case("msvc", AttributeCommonInfo::Scope::MSVC)
       .Case("omp", AttributeCommonInfo::Scope::OMP)
-      .Case("riscv", AttributeCommonInfo::Scope::RISCV);
+      .Case("riscv", AttributeCommonInfo::Scope::RISCV)
+      .Case("profiles", AttributeCommonInfo::Scope::PROFILES);
 }
 
 unsigned AttributeCommonInfo::calculateAttributeSpellingListIndex() const {
diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index 6329c3fa8b34e2..6083a114ab164a 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -64,6 +64,7 @@ add_clang_library(clangBasic
   CharInfo.cpp
   CodeGenOptions.cpp
   Cuda.cpp
+  CXXProfiles.cpp
   DarwinSDKInfo.cpp
   Diagnostic.cpp
   DiagnosticIDs.cpp
diff --git a/clang/lib/Basic/CXXProfiles.cpp b/clang/lib/Basic/CXXProfiles.cpp
new file mode 100644
index 00000000000000..8a69c4f94f810e
--- /dev/null
+++ b/clang/lib/Basic/CXXProfiles.cpp
@@ -0,0 +1,63 @@
+//===--- CXXProfiles.cpp - C++ profiles registry --------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Basic/CXXProfiles.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/ErrorHandling.h"
+
+using namespace clang;
+
+StringRef clang::getCXXProfileName(CXXProfileID Profile) {
+  switch (Profile) {
+#define CXX_PROFILE(ID, NAME)                                                  \
+  case CXXProfileID::ID:                                                       \
+    return NAME;
+#include "clang/Basic/CXXProfiles.def"
+  }
+  llvm_unreachable("unknown profile");
+}
+
+StringRef clang::getCXXProfileRuleName(CXXProfileRuleID Rule) {
+  switch (Rule) {
+#define CXX_PROFILE_RULE(PROFILE, ID, NAME)                                    \
+  case CXXProfileRuleID::ID:                                                   \
+    return NAME;
+#include "clang/Basic/CXXProfiles.def"
+  }
+  llvm_unreachable("unknown profile rule");
+}
+
+CXXProfileID clang::getCXXProfileOfRule(CXXProfileRuleID Rule) {
+  switch (Rule) {
+#define CXX_PROFILE_RULE(PROFILE, ID, NAME)                                    \
+  case CXXProfileRuleID::ID:                                                   \
+    return CXXProfileID::PROFILE;
+#include "clang/Basic/CXXProfiles.def"
+  }
+  llvm_unreachable("unknown profile rule");
+}
+
+std::optional<CXXProfileID> clang::lookupCXXProfile(StringRef Name) {
+  return llvm::StringSwitch<std::optional<CXXProfileID>>(Name)
+#define CXX_PROFILE(ID, NAME) .Case(NAME, CXXProfileID::ID)
+#include "clang/Basic/CXXProfiles.def"
+      .Default(std::nullopt);
+}
+
+std::optional<CXXProfileRuleID>
+clang::lookupCXXProfileRule(CXXProfileID Profile, StringRef Name) {
+#define CXX_PROFILE_RULE(PROFILE, ID, NAME)                                    \
+  if (Profile == CXXProfileID::PROFILE && Name == NAME)                        \
+    return CXXProfileRuleID::ID;
+#include "clang/Basic/CXXProfiles.def"
+  return std::nullopt;
+}
+
+StringRef clang::getCXXProfileDesignatorName(StringRef Designator) {
+  return Designator.take_until([](char C) { return C == '('; }).rtrim();
+}
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 4cf445d68bdbe4..ed55054010297c 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -4503,6 +4503,154 @@ bool Parser::ParseCXXAssumeAttributeArg(
   return false;
 }
 
+/// Append the spelling of \p Tok to \p Spelling, separating tokens with a
+/// single space except after an opening bracket and before a bracket, a comma
+/// or a colon.
+static void appendCXXProfileTokenSpelling(std::string &Spelling,
+                                          const Token &Tok,
+                                          const Preprocessor &PP) {
+  if (!Spelling.empty() &&
+      !Tok.isOneOf(tok::l_paren, tok::l_square, tok::r_paren, tok::r_square,
+                   tok::r_brace, tok::comma, tok::colon)) {
+    char Last = Spelling.back();
+    if (Last != '(' && Last != '[' && Last != '{')
+      Spelling += ' ';
+  }
+  Spelling += PP.getSpelling(Tok);
+}
+
+bool Parser::ParseCXXProfileBalancedToken(std::string &Spelling) {
+  if (Tok.isOneOf(tok::l_paren, tok::l_square, tok::l_brace)) {
+    tok::TokenKind Open = Tok.getKind();
+    tok::TokenKind Close = Open == tok::l_paren    ? tok::r_paren
+                           : Open == tok::l_square ? tok::r_square
+                                                   : tok::r_brace;
+    appendCXXProfileTokenSpelling(Spelling, Tok, PP);
+    ConsumeAnyToken();
+    while (Tok.isNot(Close)) {
+      if (Tok.is(tok::comma)) {
+        appendCXXProfileTokenSpelling(Spelling, Tok, PP);
+        ConsumeToken();
+        continue;
+      }
+      if (ParseCXXProfileBalancedToken(Spelling))
+        return true;
+    }
+    appendCXXProfileTokenSpelling(Spelling, Tok, PP);
+    ConsumeAnyToken();
+    return false;
+  }
+
+  if (Tok.isOneOf(tok::eof, tok::comma, tok::r_paren, tok::r_square,
+                  tok::r_brace) ||
+      Tok.isAnnotation()) {
+    Diag(Tok, diag::err_cxx_profiles_invalid_argument_token);
+    return true;
+  }
+  appendCXXProfileTokenSpelling(Spelling, Tok, PP);
+  ConsumeAnyToken();
+  return false;
+}
+
+bool Parser::ParseCXXProfileDesignator(std::string &Spelling,
+                                       SourceLocation &Loc,
+                                       bool AllowArguments) {
+  if (Tok.isNot(tok::identifier)) {
+    Diag(Tok, diag::err_cxx_profiles_expected_profile_name);
+    return true;
+  }
+  Loc = Tok.getLocation();
+  Spelling += Tok.getIdentifierInfo()->getName();
+  ConsumeToken();
+  while (Tok.is(tok::coloncolon)) {
+    ConsumeToken();
+    if (Tok.isNot(tok::identifier)) {
+      Diag(Tok, diag::err_cxx_profiles_expected_profile_name);
+      return true;
+    }
+    Spelling += "::";
+    Spelling += Tok.getIdentifierInfo()->getName();
+    ConsumeToken();
+  }
+
+  if (!AllowArguments || Tok.isNot(tok::l_paren))
+    return false;
+
+  // profile-argument-list. The arguments are not interpreted here; two
+  // designators are the same if their token sequences are the same, so record
+  // a canonical spelling of the tokens.
+  return ParseCXXProfileBalancedToken(Spelling);
+}
+
+void Parser::ParseCXXProfilesAttributeArgs(
+    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
+    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
+    SourceLocation ScopeLoc, ParsedAttr::Form Form) {
+  assert(Tok.is(tok::l_paren) && "expected the attribute argument clause");
+  BalancedDelimiterTracker Parens(*this, tok::l_paren);
+  Parens.consumeOpen();
+
+  auto MakeIdentifierArg = [&](SourceLocation Loc, StringRef Spelling) {
+    return new (Actions.Context)
+        IdentifierLoc(Loc, PP.getIdentifierInfo(Spelling));
+  };
+  auto Fail = [&] {
+    Parens.skipToEnd();
+    if (EndLoc)
+      *EndLoc = Parens.getCloseLocation();
+  };
+
+  ArgsVector Args;
+  if (AttrName->isStr("enforce") || AttrName->isStr("require")) {
+    do {
+      std::string Designator;
+      SourceLocation Loc;
+      if (ParseCXXProfileDesignator(Designator, Loc, /*AllowArguments=*/true))
+        return Fail();
+      Args.push_back(MakeIdentifierArg(Loc, Designator));
+    } while (TryConsumeToken(tok::comma));
+  } else {
+    std::string Name;
+    SourceLocation Loc;
+    if (ParseCXXProfileDesignator(Name, Loc, /*AllowArguments=*/false))
+      return Fail();
+    Args.push_back(MakeIdentifierArg(Loc, Name));
+
+    while (TryConsumeToken(tok::comma)) {
+      if (Tok.isNot(tok::identifier) || !NextToken().is(tok::colon)) {
+        Diag(Tok, diag::err_cxx_profiles_expected_named_argument) << AttrName;
+        return Fail();
+      }
+      Args.push_back(ParseIdentifierLoc());
+      ConsumeToken(); // ':'
+
+      if (isTokenStringLiteral()) {
+        ExprResult Value = ParseUnevaluatedStringLiteralExpression();
+        if (Value.isInvalid())
+          return Fail();
+        Args.push_back(Value.get());
+        continue;
+      }
+
+      SourceLocation ValueLoc = Tok.getLocation();
+      std::string Value;
+      if (ParseCXXProfileBalancedToken(Value))
+        return Fail();
+      Args.push_back(MakeIdentifierArg(ValueLoc, Value));
+    }
+  }
+
+  if (Parens.consumeClose())
+    return;
+  if (EndLoc)
+    *EndLoc = Parens.getCloseLocation();
+
+  SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
+  Attrs.addNew(AttrName, SourceRange(AttrLoc, Parens.getCloseLocation()),
+               AttributeScopeInfo(ScopeName, ScopeLoc), Args.data(),
+               Args.size(), Form);
+}
+
 bool Parser::ParseCXX11AttributeArgs(
     IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
     ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
@@ -4575,6 +4723,13 @@ bool Parser::ParseCXX11AttributeArgs(
     return true;
   }
 
+  // C++ profiles attributes (P3589) have their own argument grammar.
+  if (ScopeName && ScopeName->isStr("profiles")) {
+    ParseCXXProfilesAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
+                                  ScopeName, ScopeLoc, Form);
+    return true;
+  }
+
   unsigned NumArgs;
   // Some Clang-scoped attributes have some special parsing behavior.
   if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index f0f4c7195381e5..ee19b6d51d0231 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -25,6 +25,7 @@
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include "clang/Sema/SemaCodeCompletion.h"
 #include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/Support/Path.h"
@@ -2412,9 +2413,17 @@ Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
     SkipUntil(tok::semi, SkipUntilFlags::StopBeforeMatch);
   }
 
-  // We don't support any module attributes yet; just parse them and diagnose.
+  // The only attribute supported on a module declaration is
+  // [[profiles::enforce]]; parse the others and diagnose them.
   ParsedAttributes Attrs(AttrFactory);
   MaybeParseCXX11Attributes(Attrs);
+  SmallVector<ParsedAttr *, 1> ProfileAttrs;
+  if (getLangOpts().CXXProfiles)
+    for (ParsedAttr &AL : Attrs)
+      if (AL.getKind() == ParsedAttr::AT_ProfilesEnforce)
+        ProfileAttrs.push_back(&AL);
+  for (ParsedAttr *AL : ProfileAttrs)
+    Attrs.remove(AL);
   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
                           diag::err_keyword_not_module_attr,
                           /*DiagnoseEmptyAttrs=*/false,
@@ -2424,9 +2433,12 @@ Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
                            tok::getKeywordSpelling(tok::kw_module)))
     SkipUntil(tok::semi);
 
-  return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
-                                 ImportState,
-                                 Introducer.hasSeenNoTrivialPPDirective());
+  DeclGroupPtrTy Result = Actions.ActOnModuleDecl(
+      StartLoc, ModuleLoc, MDK, Path, Partition, ImportState,
+      Introducer.hasSeenNoTrivialPPDirective());
+  for (ParsedAttr *AL : ProfileAttrs)
+    Actions.CXXProfiles().ActOnModuleDeclEnforceAttr(*AL);
+  return Result;
 }
 
 Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
@@ -2472,7 +2484,15 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
 
   ParsedAttributes Attrs(AttrFactory);
   MaybeParseCXX11Attributes(Attrs);
-  // We don't support any module import attributes yet.
+  // The only attribute supported on a module import declaration is
+  // [[profiles::require]]; it is checked once the module has been imported.
+  SmallVector<ParsedAttr *, 1> ProfileAttrs;
+  if (getLangOpts().CXXProfiles)
+    for (ParsedAttr &AL : Attrs)
+      if (AL.getKind() == ParsedAttr::AT_ProfilesRequire)
+        ProfileAttrs.push_back(&AL);
+  for (ParsedAttr *AL : ProfileAttrs)
+    Attrs.remove(AL);
   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
                           diag::err_keyword_not_import_attr,
                           /*DiagnoseEmptyAttrs=*/false,
@@ -2567,6 +2587,10 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   if (Import.isInvalid())
     return nullptr;
 
+  if (auto *ImportD = dyn_cast_or_null<ImportDecl>(Import.get()))
+    for (ParsedAttr *AL : ProfileAttrs)
+      Actions.CXXProfiles().ActOnModuleImportRequireAttr(ImportD, *AL);
+
   // Using '@import' in framework headers requires modules to be enabled so that
   // the header is parseable. Emit a warning to make the user aware.
   if (IsObjCAtImport && AtLoc.isValid()) {
diff --git a/clang/lib/Sema/CMakeLists.txt b/clang/lib/Sema/CMakeLists.txt
index 68646838959732..7e9e9fbf3b6e7a 100644
--- a/clang/lib/Sema/CMakeLists.txt
+++ b/clang/lib/Sema/CMakeLists.txt
@@ -47,6 +47,7 @@ add_clang_library(clangSema
   SemaConsumer.cpp
   SemaCoroutine.cpp
   SemaCUDA.cpp
+  SemaCXXProfiles.cpp
   SemaDirectX.cpp
   SemaDecl.cpp
   SemaDeclAttr.cpp
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index b121f17b96a288..15b124a6b95f96 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -46,6 +46,7 @@
 #include "clang/Sema/SemaAVR.h"
 #include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include "clang/Sema/SemaCodeCompletion.h"
 #include "clang/Sema/SemaConsumer.h"
 #include "clang/Sema/SemaDirectX.h"
@@ -291,6 +292,7 @@ Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
       CodeCompletionPtr(
           std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),
       CUDAPtr(std::make_unique<SemaCUDA>(*this)),
+      CXXProfilesPtr(std::make_unique<SemaCXXProfiles>(*this)),
       DirectXPtr(std::make_unique<SemaDirectX>(*this)),
       HLSLPtr(std::make_unique<SemaHLSL>(*this)),
       HexagonPtr(std::make_unique<SemaHexagon>(*this)),
@@ -396,6 +398,8 @@ void Sema::Initialize() {
   // will not be able to merge any duplicate __va_list_tag decls correctly.
   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
 
+  CXXProfiles().ActOnStartOfTranslationUnit();
+
   if (!TUScope)
     return;
 
@@ -1357,6 +1361,8 @@ void Sema::ActOnEndOfTranslationUnit() {
                      }),
       UnusedFileScopedDecls.end());
 
+  CXXProfiles().ActOnEndOfTranslationUnit();
+
   if (TUKind == TU_Prefix) {
     // Translation unit prefixes don't need any of the checking below.
     if (!PP.isIncrementalProcessingEnabled())
@@ -2645,6 +2651,13 @@ Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, Decl *D,
     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
       Diag(PUD.Loc, PUD.PD);
 
+  // C++ profile violations are reported once the outermost function is
+  // complete, so that suppressions on enclosing statements are known. A
+  // lambda or block outside any function is part of an enclosing declaration
+  // (e.g. a variable initializer) that is not complete yet.
+  if (FunctionScopes.empty() && Scope->isPlainFunction())
+    CXXProfiles().flushPendingViolations();
+
   return Scope;
 }
 
diff --git a/clang/lib/Sema/SemaCXXProfiles.cpp b/clang/lib/Sema/SemaCXXProfiles.cpp
new file mode 100644
index 00000000000000..000685773b96cd
--- /dev/null
+++ b/clang/lib/Sema/SemaCXXProfiles.cpp
@@ -0,0 +1,908 @@
+//===------ SemaCXXProfiles.cpp --- C++ profiles (P3589) ------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+/// \file
+/// This file implements semantic analysis for C++ profiles (P3589).
+///
+//===----------------------------------------------------------------------===//
+
+#include "clang/Sema/SemaCXXProfiles.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DynamicRecursiveASTVisitor.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/DiagnosticSema.h"
+#include "clang/Basic/Module.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/Sema.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Twine.h"
+#include <algorithm>
+
+using namespace clang;
+
+SemaCXXProfiles::SemaCXXProfiles(Sema &S) : SemaBase(S) {}
+
+/// Returns the name of the diagnostic group that contains the rules of
+/// \p Profile, e.g. "cxx-profile-std-casting" for "std::casting".
+static std::string getProfileDiagGroupName(CXXProfileID Profile) {
+  std::string Group = "cxx-profile-";
+  StringRef Name = getCXXProfileName(Profile);
+  for (size_t I = 0, E = Name.size(); I != E; ++I) {
+    if (Name.substr(I).starts_with("::")) {
+      Group += '-';
+      ++I;
+    } else if (Name[I] == '_') {
+      Group += '-';
+    } else {
+      Group += Name[I];
+    }
+  }
+  return Group;
+}
+
+/// Returns the template (or class template member) that \p D was instantiated
+/// from, or \p D itself.
+static const Decl *getPatternDecl(const Decl *D) {
+  if (const auto *FD = dyn_cast<FunctionDecl>(D))
+    if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
+      return Pattern;
+  if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
+    if (const CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
+      return Pattern;
+  if (const auto *VD = dyn_cast<VarDecl>(D))
+    if (const VarDecl *Pattern = VD->getTemplateInstantiationPattern())
+      return Pattern;
+  return D;
+}
+
+/// Returns true if \p Range (a declaration or statement range, possibly
+/// spanning macro expansions) contains \p Loc. A range without an end is
+/// that of a declaration that is still being parsed (e.g. a namespace), and
+/// contains every location after its beginning.
+static bool rangeContains(const SourceManager &SM, SourceRange Range,
+                          SourceLocation Loc) {
+  if (Range.getBegin().isInvalid() || Loc.isInvalid())
+    return false;
+  SourceLocation Begin = SM.getExpansionLoc(Range.getBegin());
+  SourceLocation Point = SM.getExpansionLoc(Loc);
+  if (SM.isBeforeInTranslationUnit(Point, Begin))
+    return false;
+  if (Range.getEnd().isInvalid())
+    return true;
+  SourceLocation End = SM.getExpansionRange(Range.getEnd()).getEnd();
+  return !SM.isBeforeInTranslationUnit(End, Point);
+}
+
+/// Returns true if the file \p Path is the header named by \p Header, i.e.
+/// \p Header matches the trailing path components of \p Path.
+static bool pathMatchesHeader(StringRef Path, StringRef Header) {
+  std::string Normalized = Path.str();
+  std::replace(Normalized.begin(), Normalized.end(), '\\', '/');
+  StringRef P = Normalized;
+  if (Header.empty() || !P.ends_with(Header))
+    return false;
+  return P.size() == Header.size() || P[P.size() - Header.size() - 1] == '/';
+}
+
+/// Returns the spelling of argument \p I of a profiles attribute: the
+/// spelling of an identifier argument, or the contents of a string literal.
+static StringRef getArgSpelling(const ParsedAttr &AL, unsigned I) {
+  if (AL.isArgIdent(I))
+    return AL.getArgAsIdent(I)->getIdentifierInfo()->getName();
+  if (const auto *SL = dyn_cast<StringLiteral>(AL.getArgAsExpr(I)))
+    return SL->getString();
+  return StringRef();
+}
+
+static SourceLocation getArgLoc(const ParsedAttr &AL, unsigned I) {
+  if (AL.isArgIdent(I))
+    return AL.getArgAsIdent(I)->getLoc();
+  return AL.getArgAsExpr(I)->getBeginLoc();
+}
+
+namespace {
+/// The arguments of [[profiles::suppress]] and [[profiles::exempt]].
+struct NamedProfileArgs {
+  StringRef Profile;
+  SourceLocation ProfileLoc;
+  StringRef Rule;
+  SourceLocation RuleLoc;
+  StringRef Justification;
+  StringRef Header;
+  bool Angled = false;
+  bool HasHeader = false;
+};
+} // namespace
+
+/// Parse the arguments of [[profiles::suppress]] (if \p IsExempt is false) or
+/// [[profiles::exempt]]. Returns std::nullopt if the attribute is invalid.
+static std::optional<NamedProfileArgs>
+parseNamedProfileArgs(Sema &S, const ParsedAttr &AL, bool IsExempt) {
+  if (AL.getNumArgs() == 0 || !AL.isArgIdent(0)) {
+    S.Diag(AL.getLoc(), diag::err_cxx_profiles_attr_requires_profile)
+        << AL << /*a profile name*/ 1;
+    return std::nullopt;
+  }
+
+  NamedProfileArgs Args;
+  Args.Profile = getArgSpelling(AL, 0);
+  Args.ProfileLoc = getArgLoc(AL, 0);
+
+  // The remaining arguments are (name, value) pairs; see
+  // Parser::ParseCXXProfilesAttributeArgs.
+  for (unsigned I = 1; I + 1 < AL.getNumArgs(); I += 2) {
+    if (!AL.isArgIdent(I))
+      continue;
+    StringRef Key = getArgSpelling(AL, I);
+    SourceLocation KeyLoc = getArgLoc(AL, I);
+    StringRef Value = getArgSpelling(AL, I + 1);
+    bool IsString = AL.isArgExpr(I + 1);
+
+    if (Key == "justification") {
+      if (!IsString) {
+        S.Diag(KeyLoc, diag::err_cxx_profiles_argument_requires_string)
+            << Key << AL;
+        return std::nullopt;
+      }
+      Args.Justification = Value;
+    } else if (!IsExempt && Key == "rule") {
+      Args.Rule = Value;
+      Args.RuleLoc = KeyLoc;
+    } else if (IsExempt && (Key == "angle_header" || Key == "quote_header")) {
+      if (!IsString) {
+        S.Diag(KeyLoc, diag::err_cxx_profiles_argument_requires_string)
+            << Key << AL;
+        return std::nullopt;
+      }
+      Args.Header = Value;
+      Args.Angled = Key == "angle_header";
+      Args.HasHeader = true;
+    } else {
+      S.Diag(KeyLoc, diag::warn_cxx_profiles_unknown_argument) << Key << AL;
+    }
+  }
+  return Args;
+}
+
+void SemaCXXProfiles::ActOnStartOfTranslationUnit() {
+  if (Initialized)
+    return;
+  Initialized = true;
+
+  const LangOptions &LangOpts = getLangOpts();
+  if (!LangOpts.CXXProfiles) {
+    if (!LangOpts.CXXProfilesEnforced.empty())
+      Diag(SourceLocation(), diag::err_cxx_profiles_not_enabled) << 0;
+    if (!LangOpts.CXXProfilesPreview.empty())
+      Diag(SourceLocation(), diag::err_cxx_profiles_not_enabled) << 1;
+    return;
+  }
+
+  for (const std::string &Designator : LangOpts.CXXProfilesEnforced)
+    addEnforcedProfile(Designator, SourceLocation(), UnitProfiles);
+
+  for (const std::string &Designator : LangOpts.CXXProfilesPreview) {
+    StringRef Name = getCXXProfileDesignatorName(Designator);
+    std::optional<CXXProfileID> ID = lookupCXXProfile(Name);
+    if (!ID) {
+      Diag(SourceLocation(), diag::warn_cxx_profiles_unknown_profile)
+          << Name << /*will not be enforced*/ 0;
+      continue;
+    }
+    if (llvm::is_contained(PreviewProfiles, *ID))
+      continue;
+    PreviewProfiles.push_back(*ID);
+    // Preview the rules of a profile that is not enforced as warnings.
+    if (llvm::none_of(UnitProfiles,
+                      [&](const EnforcedProfile &E) { return E.ID == *ID; }))
+      getDiagnostics().setSeverityForGroup(diag::Flavor::WarningOrError,
+                                           getProfileDiagGroupName(*ID),
+                                           diag::Severity::Warning);
+  }
+}
+
+void SemaCXXProfiles::ActOnEndOfTranslationUnit() {
+  flushPendingViolations();
+
+  // A header unit has no module declaration; its module is the current
+  // module for the whole translation unit.
+  if (!UnitModule)
+    if (Module *M = SemaRef.getCurrentModule(); M && M->isHeaderUnit())
+      UnitModule = M;
+  updateModuleRecord();
+}
+
+void SemaCXXProfiles::updateModuleRecord() {
+  if (!UnitModule)
+    return;
+  UnitModule->CXXProfilesUnitEnforced.clear();
+  for (const EnforcedProfile &E : UnitProfiles)
+    UnitModule->CXXProfilesUnitEnforced.push_back(E.Designator);
+}
+
+bool SemaCXXProfiles::addEnforcedProfile(StringRef Designator,
+                                         SourceLocation Loc,
+                                         SmallVectorImpl<EnforcedProfile> &List,
+                                         bool Diagnose) {
+  StringRef Name = getCXXProfileDesignatorName(Designator);
+  std::optional<CXXProfileID> ID = lookupCXXProfile(Name);
+  if (!ID && Diagnose)
+    Diag(Loc, diag::warn_cxx_profiles_unknown_profile)
+        << Name << /*will not be enforced*/ 0;
+
+  // Enforcing the same designator again is a no-op; enforcing the same
+  // profile with a different designator is an error.
+  for (const SmallVectorImpl<EnforcedProfile> *Existing :
+       {&UnitProfiles, &ModuleProfiles}) {
+    for (const EnforcedProfile &E : *Existing) {
+      if (getCXXProfileDesignatorName(E.Designator) != Name)
+        continue;
+      if (E.Designator == Designator)
+        return false;
+      if (Diagnose) {
+        Diag(Loc, diag::err_cxx_profiles_enforce_mismatch)
+            << Name << E.Designator;
+        if (E.Loc.isValid())
+          Diag(E.Loc, diag::note_cxx_profiles_previous_enforce) << Name;
+        else
+          Diag(Loc, diag::note_cxx_profiles_enforced_on_command_line) << Name;
+      }
+      return false;
+    }
+  }
+
+  List.push_back({ID, Designator.str(), Loc});
+  return true;
+}
+
+const Decl *SemaCXXProfiles::findPrecedingNonEmptyDecl(const Decl *D) const {
+  for (const Decl *Other : getASTContext().getTranslationUnitDecl()->decls()) {
+    if (Other == D)
+      break;
+    if (isa<EmptyDecl>(Other) || Other->isImplicit())
+      continue;
+    // The implicit import of the primary module interface by a module
+    // implementation unit is not written in the source.
+    if (const auto *Import = dyn_cast<ImportDecl>(Other);
+        Import && PrimaryInterface &&
+        Import->getImportedModule() == PrimaryInterface)
+      continue;
+    return Other;
+  }
+  return nullptr;
+}
+
+void SemaCXXProfiles::handleEnforceAttr(Decl *D, const ParsedAttr &AL) {
+  if (AL.getNumArgs() == 0) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_attr_requires_profile)
+        << AL << /*at least one profile designator*/ 0;
+    return;
+  }
+  if (!D->getDeclContext()->isTranslationUnit()) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_enforce_not_at_tu_scope) << AL;
+    return;
+  }
+  if (const Decl *First = findPrecedingNonEmptyDecl(D)) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_enforce_after_decl) << AL;
+    Diag(First->getLocation(), diag::note_cxx_profiles_first_decl);
+    return;
+  }
+
+  SmallVector<StringRef, 2> Designators;
+  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
+    if (!AL.isArgIdent(I))
+      continue;
+    StringRef Designator = getArgSpelling(AL, I);
+    Designators.push_back(Designator);
+    addEnforcedProfile(Designator, getArgLoc(AL, I), UnitProfiles);
+  }
+  updateModuleRecord();
+
+  ASTContext &Ctx = getASTContext();
+  D->addAttr(::new (Ctx) ProfilesEnforceAttr(Ctx, AL, Designators.data(),
+                                             Designators.size()));
+}
+
+std::optional<SemaCXXProfiles::SuppressionSite>
+SemaCXXProfiles::makeSuppressionSite(
+    const ProfilesSuppressAttr *A,
+    llvm::PointerUnion<const Decl *, const Stmt *> Node) const {
+  std::optional<CXXProfileID> Profile = lookupCXXProfile(A->getProfileName());
+  if (!Profile)
+    return std::nullopt;
+  std::optional<CXXProfileRuleID> Rule;
+  if (!A->getRule().empty()) {
+    Rule = lookupCXXProfileRule(*Profile, A->getRule());
+    if (!Rule)
+      return std::nullopt;
+  }
+  return SuppressionSite{*Profile, Rule, Node};
+}
+
+/// Diagnose an unknown profile or rule named by a suppression.
+static void diagnoseSuppressionNames(Sema &S, const NamedProfileArgs &Args) {
+  std::optional<CXXProfileID> Profile = lookupCXXProfile(Args.Profile);
+  if (!Profile) {
+    S.Diag(Args.ProfileLoc, diag::warn_cxx_profiles_unknown_profile)
+        << Args.Profile << /*no suffix*/ 1;
+    return;
+  }
+  if (!Args.Rule.empty() && !lookupCXXProfileRule(*Profile, Args.Rule))
+    S.Diag(Args.RuleLoc, diag::warn_cxx_profiles_unknown_rule)
+        << Args.Rule << Args.Profile;
+}
+
+void SemaCXXProfiles::handleSuppressAttr(Decl *D, const ParsedAttr &AL) {
+  std::optional<NamedProfileArgs> Args =
+      parseNamedProfileArgs(SemaRef, AL, /*IsExempt=*/false);
+  if (!Args)
+    return;
+  diagnoseSuppressionNames(SemaRef, *Args);
+
+  ASTContext &Ctx = getASTContext();
+  auto *A = ::new (Ctx) ProfilesSuppressAttr(Ctx, AL, Args->Profile, Args->Rule,
+                                             Args->Justification);
+  D->addAttr(A);
+  if (std::optional<SuppressionSite> Site = makeSuppressionSite(A, D))
+    SuppressionSites.push_back(*Site);
+}
+
+Attr *SemaCXXProfiles::handleSuppressStmtAttr(Stmt *St, const ParsedAttr &AL) {
+  std::optional<NamedProfileArgs> Args =
+      parseNamedProfileArgs(SemaRef, AL, /*IsExempt=*/false);
+  if (!Args)
+    return nullptr;
+  diagnoseSuppressionNames(SemaRef, *Args);
+
+  ASTContext &Ctx = getASTContext();
+  auto *A = ::new (Ctx) ProfilesSuppressAttr(Ctx, AL, Args->Profile, Args->Rule,
+                                             Args->Justification);
+  if (std::optional<SuppressionSite> Site = makeSuppressionSite(A, St))
+    SuppressionSites.push_back(*Site);
+  return A;
+}
+
+void SemaCXXProfiles::handleExemptAttr(Decl *D, const ParsedAttr &AL) {
+  std::optional<NamedProfileArgs> Args =
+      parseNamedProfileArgs(SemaRef, AL, /*IsExempt=*/true);
+  if (!Args)
+    return;
+  if (!D->getDeclContext()->isTranslationUnit()) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_enforce_not_at_tu_scope) << AL;
+    return;
+  }
+  if (!Args->HasHeader) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_exempt_requires_header) << AL;
+    return;
+  }
+
+  std::optional<CXXProfileID> Profile = lookupCXXProfile(Args->Profile);
+  if (!Profile)
+    Diag(Args->ProfileLoc, diag::warn_cxx_profiles_unknown_profile)
+        << Args->Profile << /*no suffix*/ 1;
+  else
+    ExemptHeaders.push_back({*Profile, Args->Header.str()});
+
+  ASTContext &Ctx = getASTContext();
+  D->addAttr(::new (Ctx) ProfilesExemptAttr(
+      Ctx, AL, Args->Profile, Args->Header, Args->Angled, Args->Justification));
+}
+
+void SemaCXXProfiles::handleMisplacedRequireAttr(const ParsedAttr &AL) {
+  Diag(AL.getLoc(), diag::err_cxx_profiles_require_not_on_import) << AL;
+}
+
+void SemaCXXProfiles::ActOnModuleDecl(Module *Mod, Module *Interface,
+                                      SourceLocation ModuleLoc) {
+  UnitModule = Mod;
+  ModuleDeclLoc = ModuleLoc;
+  PrimaryInterface = Interface;
+
+  // [[profiles::enforce]] on the primary module interface's module
+  // declaration also applies to every implementation unit of the module.
+  if (Interface)
+    for (const std::string &Designator : Interface->CXXProfilesModuleEnforced)
+      addEnforcedProfile(Designator, SourceLocation(), ModuleProfiles,
+                         /*Diagnose=*/false);
+  updateModuleRecord();
+}
+
+void SemaCXXProfiles::ActOnModuleDeclEnforceAttr(const ParsedAttr &AL) {
+  if (AL.getNumArgs() == 0) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_attr_requires_profile)
+        << AL << /*at least one profile designator*/ 0;
+    return;
+  }
+  // Errors in the module declaration have already been diagnosed.
+  Module *Mod = SemaRef.getCurrentModule();
+  if (!Mod || !Mod->isNamedModule())
+    return;
+
+  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
+    if (!AL.isArgIdent(I))
+      continue;
+    StringRef Designator = getArgSpelling(AL, I);
+    if (addEnforcedProfile(Designator, getArgLoc(AL, I), ModuleProfiles))
+      Mod->CXXProfilesModuleEnforced.push_back(Designator.str());
+  }
+}
+
+void SemaCXXProfiles::ActOnModuleImportRequireAttr(ImportDecl *Import,
+                                                   const ParsedAttr &AL) {
+  if (AL.getNumArgs() == 0) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_attr_requires_profile)
+        << AL << /*at least one profile designator*/ 0;
+    return;
+  }
+  Module *M = Import->getImportedModule();
+  if (!M)
+    return;
+  if (!M->isNamedModule() && !M->isHeaderUnit()) {
+    Diag(AL.getLoc(), diag::err_cxx_profiles_require_not_named_module) << AL;
+    return;
+  }
+
+  // A named module advertises the profiles enforced on its module
+  // declaration; a header unit advertises the profiles it enforces.
+  Module *Top = M->getTopLevelModule();
+  const std::vector<std::string> &Advertised =
+      M->isHeaderUnit() ? Top->CXXProfilesUnitEnforced
+                        : Top->CXXProfilesModuleEnforced;
+  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
+    if (!AL.isArgIdent(I))
+      continue;
+    StringRef Designator = getArgSpelling(AL, I);
+    if (llvm::none_of(Advertised, [&](const std::string &Other) {
+          return Other == Designator;
+        }))
+      Diag(getArgLoc(AL, I), diag::err_cxx_profiles_require_not_enforced)
+          << M->getFullModuleName() << Designator;
+  }
+}
+
+bool SemaCXXProfiles::isEnforcedInCurrentUnit(CXXProfileID Profile,
+                                              SourceLocation Loc) const {
+  for (const EnforcedProfile &E : UnitProfiles)
+    if (E.ID == Profile)
+      return true;
+  if (llvm::is_contained(PreviewProfiles, Profile))
+    return true;
+  // A profile enforced on the module declaration applies from the module
+  // declaration onwards; it does not apply to the global module fragment.
+  for (const EnforcedProfile &E : ModuleProfiles)
+    if (E.ID == Profile)
+      return ModuleDeclLoc.isInvalid() || Loc.isInvalid() ||
+             !SemaRef.getSourceManager().isBeforeInTranslationUnit(
+                 Loc, ModuleDeclLoc);
+  return false;
+}
+
+bool SemaCXXProfiles::isEnforced(CXXProfileID Profile, SourceLocation Loc,
+                                 const Decl *Owner) const {
+  // Code is checked according to the profiles enforced where it is written:
+  // the instantiation of a template is checked according to the profiles
+  // enforced by the unit that defines the template.
+  const Decl *Pattern = Owner ? getPatternDecl(Owner) : nullptr;
+  if (!Pattern || !Pattern->isFromASTFile())
+    return isEnforcedInCurrentUnit(Profile, Loc);
+
+  Module *M = Pattern->getOwningModule();
+  // Declarations from a precompiled header are part of this translation
+  // unit.
+  if (!M)
+    return isEnforcedInCurrentUnit(Profile, Loc);
+  // Clang modules and the global module fragments of named modules do not
+  // record enforced profiles.
+  if (!M->isNamedModule() && !M->isHeaderUnit())
+    return false;
+
+  Module *Top = M->getTopLevelModule();
+  auto Enforces = [&](const std::vector<std::string> &Designators) {
+    return llvm::any_of(Designators, [&](const std::string &Designator) {
+      return lookupCXXProfile(getCXXProfileDesignatorName(Designator)) ==
+             Profile;
+    });
+  };
+  return Enforces(Top->CXXProfilesUnitEnforced) ||
+         (M->isNamedModule() && Enforces(Top->CXXProfilesModuleEnforced));
+}
+
+bool SemaCXXProfiles::isExempt(CXXProfileID Profile, SourceLocation Loc) const {
+  const SourceManager &SM = SemaRef.getSourceManager();
+  SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
+  if (SM.isInSystemHeader(ExpansionLoc))
+    return true;
+  if (ExemptHeaders.empty())
+    return false;
+
+  // A [[profiles::exempt]] header exempts its own code and the code of every
+  // header it includes.
+  FileID FID = SM.getFileID(ExpansionLoc);
+  while (FID.isValid()) {
+    if (OptionalFileEntryRef File = SM.getFileEntryRefForID(FID))
+      for (const ExemptHeader &Exempt : ExemptHeaders)
+        if (Exempt.Profile == Profile &&
+            pathMatchesHeader(File->getName(), Exempt.Header))
+          return true;
+    SourceLocation IncludeLoc = SM.getIncludeLoc(FID);
+    if (IncludeLoc.isInvalid())
+      break;
+    FID = SM.getFileID(IncludeLoc);
+  }
+  return false;
+}
+
+bool SemaCXXProfiles::shouldCheck(CXXProfileID Profile,
+                                  SourceLocation Loc) const {
+  if (!getLangOpts().CXXProfiles || Loc.isInvalid())
+    return false;
+  // Profiles restrict what is accepted; they never affect which overloads or
+  // specializations are viable, and code that is not evaluated has no runtime
+  // effect.
+  if (SemaRef.isUnevaluatedContext() || SemaRef.isConstantEvaluatedContext() ||
+      SemaRef.isSFINAEContext())
+    return false;
+  const Decl *Owner =
+      SemaRef.CurContext ? cast<Decl>(SemaRef.CurContext) : nullptr;
+  return isEnforced(Profile, Loc, Owner) && !isExempt(Profile, Loc);
+}
+
+void SemaCXXProfiles::addViolation(CXXProfileRuleID Rule,
+                                   PartialDiagnosticAt Diag,
+                                   SmallVector<PartialDiagnosticAt, 1> Notes) {
+  const Decl *Owner =
+      SemaRef.CurContext ? cast<Decl>(SemaRef.CurContext) : nullptr;
+  PendingViolations.push_back({Rule, Owner, std::move(Diag), std::move(Notes)});
+}
+
+namespace {
+/// Collects the [[profiles::suppress]] attributes within a declaration.
+class SuppressionCollector : public ConstDynamicRecursiveASTVisitor {
+public:
+  explicit SuppressionCollector(
+      llvm::function_ref<void(const ProfilesSuppressAttr *,
+                              llvm::PointerUnion<const Decl *, const Stmt *>)>
+          Callback)
+      : Callback(Callback) {
+    ShouldVisitTemplateInstantiations = false;
+    ShouldVisitImplicitCode = false;
+  }
+
+  bool VisitDecl(const Decl *D) override {
+    for (const auto *A : D->specific_attrs<ProfilesSuppressAttr>())
+      if (!A->isInherited())
+        Callback(A, D);
+    return true;
+  }
+
+  bool VisitAttributedStmt(const AttributedStmt *S) override {
+    for (const Attr *A : S->getAttrs())
+      if (const auto *Suppress = dyn_cast<ProfilesSuppressAttr>(A))
+        Callback(Suppress, S->getSubStmt());
+    return true;
+  }
+
+private:
+  llvm::function_ref<void(const ProfilesSuppressAttr *,
+                          llvm::PointerUnion<const Decl *, const Stmt *>)>
+      Callback;
+};
+} // namespace
+
+ArrayRef<SemaCXXProfiles::SuppressionSite>
+SemaCXXProfiles::getImportedSuppressionSites(const Decl *Pattern) {
+  auto It = ImportedSuppressionSites.find(Pattern);
+  if (It != ImportedSuppressionSites.end())
+    return It->second;
+
+  SmallVector<SuppressionSite, 2> &Sites = ImportedSuppressionSites[Pattern];
+  auto Add = [&](const ProfilesSuppressAttr *A,
+                 llvm::PointerUnion<const Decl *, const Stmt *> Node) {
+    if (std::optional<SuppressionSite> Site = makeSuppressionSite(A, Node))
+      Sites.push_back(*Site);
+  };
+
+  // Collect the suppressions in the outermost enclosing function (so that
+  // suppressions around a lambda are found) and on its enclosing
+  // declarations.
+  const Decl *Root = Pattern;
+  for (const DeclContext *DC = Pattern->getLexicalDeclContext(); DC;
+       DC = DC->getLexicalParent())
+    if (const auto *FD = dyn_cast<FunctionDecl>(DC))
+      Root = FD;
+  SuppressionCollector(Add).TraverseDecl(Root);
+  for (const DeclContext *DC = Root->getLexicalDeclContext();
+       DC && !isa<TranslationUnitDecl>(DC); DC = DC->getLexicalParent())
+    if (const auto *D = dyn_cast<Decl>(DC))
+      for (const auto *A : D->specific_attrs<ProfilesSuppressAttr>())
+        Add(A, D);
+  return Sites;
+}
+
+bool SemaCXXProfiles::isSuppressed(CXXProfileRuleID Rule, SourceLocation Loc,
+                                   const Decl *Owner) {
+  CXXProfileID Profile = getCXXProfileOfRule(Rule);
+  const SourceManager &SM = SemaRef.getSourceManager();
+  auto Matches = [&](const SuppressionSite &Site) {
+    if (Site.Profile != Profile || (Site.Rule && *Site.Rule != Rule))
+      return false;
+    SourceRange Range = isa<const Decl *>(Site.Node)
+                            ? cast<const Decl *>(Site.Node)->getSourceRange()
+                            : cast<const Stmt *>(Site.Node)->getSourceRange();
+    return rangeContains(SM, Range, Loc);
+  };
+
+  if (llvm::any_of(SuppressionSites, Matches))
+    return true;
+
+  // The suppressions of a template from another module are in the AST file.
+  const Decl *Pattern = Owner ? getPatternDecl(Owner) : nullptr;
+  if (Pattern && Pattern->isFromASTFile())
+    return llvm::any_of(getImportedSuppressionSites(Pattern), Matches);
+  return false;
+}
+
+void SemaCXXProfiles::flushPendingViolations() {
+  if (PendingViolations.empty())
+    return;
+
+  SmallVector<PendingViolation, 4> Violations;
+  std::swap(Violations, PendingViolations);
+  for (PendingViolation &V : Violations) {
+    SourceLocation Loc = V.Diag.first;
+    if (!ReportedViolations
+             .insert({static_cast<unsigned>(V.Rule), Loc.getRawEncoding()})
+             .second)
+      continue;
+    if (isSuppressed(V.Rule, Loc, V.Owner))
+      continue;
+    Diag(Loc, V.Diag.second);
+    for (const PartialDiagnosticAt &Note : V.Notes)
+      Diag(Note.first, Note.second);
+  }
+}
+
+//===----------------------------------------------------------------------===//
+// std::casting
+//===----------------------------------------------------------------------===//
+
+/// Returns the type of the operand of \p E as written, after the
+/// array-to-pointer and function-to-pointer conversions that apply to the
+/// operand of a cast to a non-reference type.
+static QualType getCastOperandType(ASTContext &Ctx, const ExplicitCastExpr *E) {
+  QualType T = E->getSubExprAsWritten()->getType();
+  if (E->getTypeAsWritten()->isReferenceType())
+    return T;
+  if (T->isArrayType())
+    return Ctx.getArrayDecayedType(T);
+  if (T->isFunctionType())
+    return Ctx.getPointerType(T);
+  return T;
+}
+
+/// Returns the type a pointer or reference type \p T refers to, or a null
+/// type.
+static QualType getReferencedType(QualType T) {
+  if (T->isPointerType() || T->isReferenceType())
+    return T->getPointeeType();
+  return QualType();
+}
+
+static bool isCharacterType(QualType T) {
+  const auto *BT = T.isNull() ? nullptr : T->getAs<BuiltinType>();
+  return BT && (BT->getKind() == BuiltinType::Char_S ||
+                BT->getKind() == BuiltinType::Char_U ||
+                BT->getKind() == BuiltinType::UChar);
+}
+
+/// Returns true if the reinterpret_cast \p E is permitted by std::casting:
+/// a cast to a pointer or reference to std::byte, a pointer to integer
+/// conversion to an integer type wide enough to hold any pointer, or a cast
+/// that does not change the type beyond adding qualifiers.
+static bool isPermittedReinterpretCast(ASTContext &Ctx,
+                                       const ExplicitCastExpr *E) {
+  if (E->getCastKind() == CK_NoOp)
+    return true;
+  QualType DestType = E->getTypeAsWritten();
+  if (E->getCastKind() == CK_PointerToIntegral)
+    return Ctx.getTypeSize(DestType) >= Ctx.getTypeSize(Ctx.VoidPtrTy);
+  QualType Referenced = getReferencedType(DestType);
+  return !Referenced.isNull() && Referenced->isStdByteType();
+}
+
+/// Returns a hint that replaces the C-style or functional cast \p E with the
+/// named cast \p CastName, or false if no hint can be built.
+static bool buildNamedCastFixIts(Sema &S, const ExplicitCastExpr *E,
+                                 StringRef CastName,
+                                 SmallVectorImpl<FixItHint> &Hints) {
+  const SourceManager &SM = S.getSourceManager();
+  const LangOptions &LangOpts = S.getLangOpts();
+
+  if (const auto *CE = dyn_cast<CStyleCastExpr>(E)) {
+    SourceLocation LParen = CE->getLParenLoc();
+    SourceLocation RParen = CE->getRParenLoc();
+    const Expr *Operand = CE->getSubExprAsWritten();
+    SourceLocation OperandEnd = Operand->getEndLoc();
+    if (LParen.isMacroID() || RParen.isMacroID() || OperandEnd.isMacroID())
+      return false;
+    StringRef TypeText =
+        Lexer::getSourceText(
+            CharSourceRange::getCharRange(LParen.getLocWithOffset(1), RParen),
+            SM, LangOpts)
+            .trim();
+    if (TypeText.empty())
+      return false;
+    bool NeedsParens = !isa<ParenExpr>(Operand);
+    std::string Replacement = (CastName + "<" + TypeText + ">").str();
+    if (NeedsParens)
+      Replacement += "(";
+    Hints.push_back(FixItHint::CreateReplacement(
+        CharSourceRange::getTokenRange(LParen, RParen), Replacement));
+    if (NeedsParens)
+      Hints.push_back(FixItHint::CreateInsertion(
+          Lexer::getLocForEndOfToken(OperandEnd, 0, SM, LangOpts), ")"));
+    return true;
+  }
+
+  const auto *FE = cast<CXXFunctionalCastExpr>(E);
+  if (FE->isListInitialization())
+    return false;
+  SourceLocation Begin = FE->getBeginLoc();
+  SourceLocation LParen = FE->getLParenLoc();
+  if (Begin.isMacroID() || LParen.isMacroID())
+    return false;
+  StringRef TypeText =
+      Lexer::getSourceText(CharSourceRange::getCharRange(Begin, LParen), SM,
+                           LangOpts)
+          .trim();
+  if (TypeText.empty())
+    return false;
+  Hints.push_back(
+      FixItHint::CreateReplacement(CharSourceRange::getCharRange(Begin, LParen),
+                                   (CastName + "<" + TypeText + ">").str()));
+  return true;
+}
+
+void SemaCXXProfiles::checkExplicitCast(
+    const ExplicitCastExpr *E, std::optional<Qualifiers> CastAwayQualifiers) {
+  if (E->getCastKind() == CK_Dependent || E->isTypeDependent())
+    return;
+  SourceLocation Loc = E->getBeginLoc();
+  if (!shouldCheck(CXXProfileID::StdCasting, Loc))
+    return;
+
+  // How the cast is spelled, for the diagnostics: 0 for a named cast, 1 for
+  // a C-style cast, 2 for a functional-style cast.
+  unsigned Spelling = isa<CStyleCastExpr>(E)          ? 1
+                      : isa<CXXFunctionalCastExpr>(E) ? 2
+                                                      : 0;
+  CStyleCastInterpretation Interpretation;
+  if (isa<CXXReinterpretCastExpr>(E))
+    Interpretation = CStyleCastInterpretation::Reinterpret;
+  else if (isa<CXXConstCastExpr>(E))
+    Interpretation = CStyleCastInterpretation::Const;
+  else if (isa<CXXStaticCastExpr>(E))
+    Interpretation = CStyleCastInterpretation::Static;
+  else if (Spelling != 0)
+    Interpretation = E->getCStyleCastInterpretation();
+  else
+    return;
+  if (Interpretation == CStyleCastInterpretation::Unknown)
+    return;
+
+  ASTContext &Ctx = getASTContext();
+  StringRef ProfileName = getCXXProfileName(CXXProfileID::StdCasting);
+  QualType SourceType = getCastOperandType(Ctx, E);
+  QualType DestType = E->getTypeAsWritten();
+  SourceRange Range = E->getSourceRange();
+
+  // For a C-style or functional cast, offer to spell the cast as the named
+  // cast it performs, which is meaningful unless it also casts away
+  // constness. The hint is attached to the first violation only.
+  bool OfferedNamedCast = Spelling == 0;
+  auto MakeNotes = [&] {
+    SmallVector<PartialDiagnosticAt, 1> Notes;
+    if (OfferedNamedCast)
+      return Notes;
+    OfferedNamedCast = true;
+    if (E->getCStyleCastCastsAwayConst() &&
+        Interpretation != CStyleCastInterpretation::Const)
+      return Notes;
+    StringRef CastName = Interpretation == CStyleCastInterpretation::Const
+                             ? "const_cast"
+                         : Interpretation == CStyleCastInterpretation::Static
+                             ? "static_cast"
+                             : "reinterpret_cast";
+    SmallVector<FixItHint, 2> Hints;
+    if (!buildNamedCastFixIts(SemaRef, E, CastName, Hints))
+      return Notes;
+    PartialDiagnostic Note = PDiag(diag::note_cxx_profile_casting_named_cast)
+                             << CastName;
+    for (const FixItHint &Hint : Hints)
+      Note << Hint;
+    Notes.push_back({Loc, Note});
+    return Notes;
+  };
+
+  if (Interpretation == CStyleCastInterpretation::Reinterpret &&
+      !isPermittedReinterpretCast(Ctx, E)) {
+    bool ToCharacter = isCharacterType(getReferencedType(DestType));
+    SmallVector<PartialDiagnosticAt, 1> Notes = MakeNotes();
+    QualType SourceReferenced = getReferencedType(SourceType);
+    QualType DestReferenced = getReferencedType(DestType);
+    if (!SourceReferenced.isNull() && !DestReferenced.isNull() &&
+        SourceReferenced->isObjectType() && DestReferenced->isObjectType() &&
+        !SourceReferenced->isIncompleteType() &&
+        !DestReferenced->isIncompleteType() &&
+        SourceReferenced.isTriviallyCopyableType(Ctx) &&
+        DestReferenced.isTriviallyCopyableType(Ctx) &&
+        Ctx.getTypeSizeInChars(SourceReferenced) ==
+            Ctx.getTypeSizeInChars(DestReferenced))
+      Notes.push_back(
+          {Loc, PDiag(diag::note_cxx_profile_casting_use_bit_cast)});
+    addViolation(
+        ToCharacter ? CXXProfileRuleID::StdCastingReinterpretCastChar
+                    : CXXProfileRuleID::StdCastingReinterpretCast,
+        {Loc, PDiag(ToCharacter
+                        ? diag::warn_cxx_profile_casting_reinterpret_cast_char
+                        : diag::warn_cxx_profile_casting_reinterpret_cast)
+                  << ProfileName << Spelling << SourceType << DestType
+                  << Range},
+        std::move(Notes));
+  }
+
+  // Removing 'volatile' (or 'restrict') alone is not casting away constness
+  // for the purposes of this rule; removing qualifiers at an inner level of
+  // a multi-level pointer is.
+  if (CastAwayQualifiers &&
+      (CastAwayQualifiers->hasConst() || (!CastAwayQualifiers->hasVolatile() &&
+                                          !CastAwayQualifiers->hasRestrict())))
+    addViolation(CXXProfileRuleID::StdCastingConstCast,
+                 {Loc, PDiag(diag::warn_cxx_profile_casting_const_cast)
+                           << ProfileName << Spelling << SourceType << DestType
+                           << Range},
+                 MakeNotes());
+
+  if (Interpretation != CStyleCastInterpretation::Static)
+    return;
+
+  if (E->getCastKind() == CK_BaseToDerived) {
+    SmallVector<PartialDiagnosticAt, 1> Notes = MakeNotes();
+    QualType SourceClass =
+        SourceType->isPointerType() ? SourceType->getPointeeType() : SourceType;
+    QualType DestClass =
+        DestType->isPointerType() || DestType->isReferenceType()
+            ? DestType->getPointeeType()
+            : DestType;
+    if (const auto *RD = SourceClass->getAsCXXRecordDecl();
+        RD && RD->hasDefinition() && RD->isPolymorphic())
+      Notes.push_back(
+          {Loc, PDiag(diag::note_cxx_profile_casting_use_dynamic_cast)});
+    addViolation(CXXProfileRuleID::StdCastingStaticDowncast,
+                 {Loc, PDiag(diag::warn_cxx_profile_casting_static_downcast)
+                           << ProfileName << Spelling << SourceClass
+                           << DestClass << Range},
+                 std::move(Notes));
+    return;
+  }
+
+  if (SourceType->isVoidPointerType() && DestType->isPointerType() &&
+      !DestType->isVoidPointerType() &&
+      !DestType->getPointeeType()->isStdByteType())
+    addViolation(CXXProfileRuleID::StdCastingStaticCastVoid,
+                 {Loc, PDiag(diag::warn_cxx_profile_casting_static_cast_void)
+                           << ProfileName << Spelling << SourceType << DestType
+                           << Range},
+                 MakeNotes());
+}
diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index cea9a593e58ada..07392782be1173 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -25,6 +25,7 @@
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/SemaAMDGPU.h"
 #include "clang/Sema/SemaCUDA.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaObjC.h"
 #include "clang/Sema/SemaRISCV.h"
@@ -132,6 +133,11 @@ namespace {
     OpRangeType OpRange;
     SourceRange DestRange;
 
+    /// For a C++ C-style or functional cast, how the cast was resolved
+    /// ([expr.cast]p4).
+    CStyleCastInterpretation CStyleInterpretation =
+        CStyleCastInterpretation::Unknown;
+
     // Top-level semantics-checking routines.
     void CheckConstCast();
     void CheckReinterpretCast();
@@ -151,9 +157,16 @@ namespace {
         ICE->setIsPartOfExplicitCast(true);
     }
 
+    /// Record how a C-style or functional cast was resolved on \p E, and
+    /// check \p E against the enforced C++ profiles.
+    void finishExplicitCast(ExplicitCastExpr *E);
+
     /// Complete an apparently-successful cast operation that yields
     /// the given expression.
     ExprResult complete(CastExpr *castExpr) {
+      if (auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(castExpr))
+        finishExplicitCast(ExplicitCast);
+
       // If this is an unbridged cast, wrap the result in an implicit
       // cast that yields the unbridged-cast placeholder type.
       if (IsARCUnbridgedCast) {
@@ -2864,6 +2877,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
   // In plain language, this means trying a const_cast ...
   // Note that for address space we check compatibility after const_cast.
   unsigned msg = diag::err_bad_cxx_cast_generic;
+  CStyleCastInterpretation Interpretation = CStyleCastInterpretation::Const;
   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
                                    /*CStyle*/ true, msg);
   if (SrcExpr.isInvalid())
@@ -2872,6 +2886,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
     Kind = CK_NoOp;
 
   if (tcr == TC_NotApplicable) {
+    Interpretation = CStyleCastInterpretation::Unknown;
     tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
                               Kind);
     if (SrcExpr.isInvalid())
@@ -2880,6 +2895,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
     if (tcr == TC_NotApplicable) {
       // ... or if that is not possible, a static_cast, ignoring const and
       // addr space, ...
+      Interpretation = CStyleCastInterpretation::Static;
       tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
                           BasePath, ListInitialization);
       if (SrcExpr.isInvalid())
@@ -2887,6 +2903,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
 
       if (tcr == TC_NotApplicable) {
         // ... and finally a reinterpret_cast, ignoring const and addr space.
+        Interpretation = CStyleCastInterpretation::Reinterpret;
         tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
                                  OpRange, msg, Kind);
         if (SrcExpr.isInvalid())
@@ -2894,6 +2911,8 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
       }
     }
   }
+  if (isValidCast(tcr))
+    CStyleInterpretation = Interpretation;
 
   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
       isValidCast(tcr))
@@ -3479,6 +3498,60 @@ static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
         << TheOffendingSrcType << TheOffendingDestType << qualifiers;
 }
 
+/// Returns the qualifiers that the explicit cast \p E casts away
+/// ([expr.const.cast]), or std::nullopt if it does not cast away constness.
+static std::optional<Qualifiers>
+getCastAwayQualifiers(Sema &Self, const ExplicitCastExpr *E) {
+  QualType DestType = E->getTypeAsWritten();
+  QualType SrcType = E->getSubExprAsWritten()->getType();
+  if (SrcType->isDependentType() || DestType->isDependentType())
+    return std::nullopt;
+  if (DestType->isReferenceType()) {
+    // A reference cast casts away constness if the corresponding pointer
+    // cast does ([expr.const.cast]p8).
+    SrcType = Self.Context.getPointerType(SrcType.getNonReferenceType());
+    DestType = Self.Context.getPointerType(DestType->getPointeeType());
+  } else if (SrcType->isArrayType()) {
+    SrcType = Self.Context.getArrayDecayedType(SrcType);
+  } else if (SrcType->isFunctionType()) {
+    SrcType = Self.Context.getPointerType(SrcType);
+  }
+
+  auto IsPointerLike = [](QualType T) {
+    return T->isAnyPointerType() || T->isMemberPointerType() ||
+           T->isBlockPointerType();
+  };
+  if (!IsPointerLike(SrcType) || !IsPointerLike(DestType))
+    return std::nullopt;
+
+  Qualifiers CastAwayQualifiers;
+  if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/true,
+                         /*CheckObjCLifetime=*/false,
+                         /*TheOffendingSrcType=*/nullptr,
+                         /*TheOffendingDestType=*/nullptr,
+                         &CastAwayQualifiers) ==
+      CastAwayConstnessKind::CACK_None)
+    return std::nullopt;
+  return CastAwayQualifiers;
+}
+
+void CastOperation::finishExplicitCast(ExplicitCastExpr *E) {
+  const LangOptions &LangOpts = Self.getLangOpts();
+  if (!LangOpts.CPlusPlus || E->isTypeDependent() ||
+      E->getCastKind() == CK_Dependent)
+    return;
+  bool IsCStyle = isa<CStyleCastExpr, CXXFunctionalCastExpr>(E);
+  if (!IsCStyle && !LangOpts.CXXProfiles)
+    return;
+
+  std::optional<Qualifiers> CastAwayQualifiers = getCastAwayQualifiers(Self, E);
+  if (IsCStyle && CStyleInterpretation != CStyleCastInterpretation::Unknown)
+    E->setCStyleCastInterpretation(CStyleInterpretation,
+                                   CastAwayQualifiers.has_value());
+  if (LangOpts.CXXProfiles)
+    Self.CXXProfiles().checkExplicitCast(E, CastAwayQualifiers);
+}
+
 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
                                      TypeSourceInfo *CastTypeInfo,
                                      SourceLocation RPLoc,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index e46c14d1513467..2af80ddd331fcf 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3053,7 +3053,7 @@ static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
     NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
     NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
-  else if (isa<SuppressAttr>(Attr))
+  else if (isa<SuppressAttr, ProfilesSuppressAttr>(Attr))
     // Do nothing. Each redeclaration should be suppressed separately.
     NewAttr = nullptr;
   else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 33b680c4d93d4c..d822bb3e5c4291 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -48,6 +48,7 @@
 #include "clang/Sema/SemaAVR.h"
 #include "clang/Sema/SemaBPF.h"
 #include "clang/Sema/SemaCUDA.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include "clang/Sema/SemaHLSL.h"
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/SemaM68k.h"
@@ -8211,6 +8212,18 @@ ProcessDeclAttribute(Sema &S, Decl *D, const ParsedAttr &AL,
   case ParsedAttr::AT_Suppress:
     handleSuppressAttr(S, D, AL);
     break;
+  case ParsedAttr::AT_ProfilesEnforce:
+    S.CXXProfiles().handleEnforceAttr(D, AL);
+    break;
+  case ParsedAttr::AT_ProfilesSuppress:
+    S.CXXProfiles().handleSuppressAttr(D, AL);
+    break;
+  case ParsedAttr::AT_ProfilesExempt:
+    S.CXXProfiles().handleExemptAttr(D, AL);
+    break;
+  case ParsedAttr::AT_ProfilesRequire:
+    S.CXXProfiles().handleMisplacedRequireAttr(AL);
+    break;
   case ParsedAttr::AT_Owner:
   case ParsedAttr::AT_Pointer:
     handleLifetimeCategoryAttr(S, D, AL);
diff --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index 7dbb38bbe078ec..8f55e51a796139 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -17,6 +17,7 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"
@@ -477,6 +478,8 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
 
   getASTContext().setCurrentNamedModule(Mod);
 
+  CXXProfiles().ActOnModuleDecl(Mod, Interface, ModuleLoc);
+
   // We already potentially made an implicit import (in the case of a module
   // implementation unit importing its interface).  Make this module visible
   // and return the import decl to be added to the current TU.
diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index bad5a3e0fb9196..02fcfbdaa43b9b 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -16,6 +16,7 @@
 #include "clang/Sema/DelayedDiagnostic.h"
 #include "clang/Sema/ParsedAttr.h"
 #include "clang/Sema/ScopeInfo.h"
+#include "clang/Sema/SemaCXXProfiles.h"
 #include <optional>
 
 using namespace clang;
@@ -794,6 +795,8 @@ static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
     return handleOpenCLUnrollHint(S, St, A, Range);
   case ParsedAttr::AT_Suppress:
     return handleSuppressAttr(S, St, A, Range);
+  case ParsedAttr::AT_ProfilesSuppress:
+    return S.CXXProfiles().handleSuppressStmtAttr(St, A);
   case ParsedAttr::AT_NoMerge:
     return handleNoMergeAttr(S, St, A, Range);
   case ParsedAttr::AT_NoInline:
diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp
index cd7d9f24924f82..b4bae7251af7da 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -6623,6 +6623,8 @@ Module *ASTReader::getSubmodule(uint32_t GlobalID) {
       // Clear out data that will be replaced by what is in the module file.
       CurrentModule->LinkLibraries.clear();
       CurrentModule->ConfigMacros.clear();
+      CurrentModule->CXXProfilesUnitEnforced.clear();
+      CurrentModule->CXXProfilesModuleEnforced.clear();
       CurrentModule->UnresolvedConflicts.clear();
       CurrentModule->Conflicts.clear();
 
@@ -6765,6 +6767,13 @@ Module *ASTReader::getSubmodule(uint32_t GlobalID) {
       CurrentModule->addSubmodule(Blob, this, GlobalID);
       break;
     }
+
+    case SUBMODULE_CXX_PROFILE:
+      if (Record[0])
+        CurrentModule->CXXProfilesModuleEnforced.push_back(Blob.str());
+      else
+        CurrentModule->CXXProfilesUnitEnforced.push_back(Blob.str());
+      break;
     }
   }
 }
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 26aee27c65e82f..3702d3d89b247a 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -1237,6 +1237,10 @@ void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
 
 void ASTStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
   VisitCastExpr(E);
+  auto Interpretation = static_cast<CStyleCastInterpretation>(
+      CurrentUnpackingBits->getNextBits(/*Width=*/2));
+  bool CastsAwayConst = CurrentUnpackingBits->getNextBit();
+  E->setCStyleCastInterpretation(Interpretation, CastsAwayConst);
   E->setTypeInfoAsWritten(readTypeSourceInfo());
 }
 
diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp
index de1c2449138e58..b315da209156e2 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1020,6 +1020,7 @@ void ASTWriter::WriteBlockInfoBlock() {
   RECORD(SUBMODULE_INITIALIZERS);
   RECORD(SUBMODULE_EXPORT_AS);
   RECORD(SUBMODULE_CHILD);
+  RECORD(SUBMODULE_CXX_PROFILE);
 
   // Comments Block.
   BLOCK(COMMENTS_BLOCK);
@@ -3120,6 +3121,12 @@ void ASTWriter::WriteSubmodules(Module *WritingModule, ASTContext *Context) {
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Child name
   unsigned ChildAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
 
+  Abbrev = std::make_shared<BitCodeAbbrev>();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CXX_PROFILE));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // OnModuleDecl
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Designator
+  unsigned CXXProfileAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
+
   SmallVector<uint64_t> SubmoduleOffsets;
   uint64_t SubmoduleOffsetBase = Stream.GetCurrentBitNo();
 
@@ -3297,6 +3304,18 @@ void ASTWriter::WriteSubmodules(Module *WritingModule, ASTContext *Context) {
         Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
     }
 
+    // Emit the C++ profiles enforced by the module unit.
+    for (const auto &Designator : Mod->CXXProfilesUnitEnforced) {
+      RecordData::value_type Record[] = {SUBMODULE_CXX_PROFILE,
+                                         /*OnModuleDecl=*/0};
+      Stream.EmitRecordWithBlob(CXXProfileAbbrev, Record, Designator);
+    }
+    for (const auto &Designator : Mod->CXXProfilesModuleEnforced) {
+      RecordData::value_type Record[] = {SUBMODULE_CXX_PROFILE,
+                                         /*OnModuleDecl=*/1};
+      Stream.EmitRecordWithBlob(CXXProfileAbbrev, Record, Designator);
+    }
+
     // Emit the name of the re-exported module, if any.
     if (!Mod->ExportAsModule.empty()) {
       RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index 4b4d179fb406ac..3d90acbadb068a 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -1242,6 +1242,9 @@ void ASTStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
 
 void ASTStmtWriter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
   VisitCastExpr(E);
+  CurrentPackingBits.addBits(
+      llvm::to_underlying(E->getCStyleCastInterpretation()), /*Width=*/2);
+  CurrentPackingBits.addBit(E->getCStyleCastCastsAwayConst());
   Record.AddTypeSourceInfo(E->getTypeInfoAsWritten());
 }
 
diff --git a/clang/test/AST/ast-dump-cstyle-cast-interpretation.cpp b/clang/test/AST/ast-dump-cstyle-cast-interpretation.cpp
new file mode 100644
index 00000000000000..8c528aa5e7f41b
--- /dev/null
+++ b/clang/test/AST/ast-dump-cstyle-cast-interpretation.cpp
@@ -0,0 +1,51 @@
+// Test that the AST records how C-style and functional-style casts were
+// resolved, and that this survives serialization.
+
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 -ast-dump %s \
+// RUN:   | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 -ast-dump=json %s \
+// RUN:   | FileCheck %s --check-prefix=JSON
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 -emit-pch -o %t %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 -x c++ \
+// RUN:   -include-pch %t -ast-dump-all /dev/null | FileCheck %s
+
+struct B {
+  virtual ~B();
+};
+struct D : B {};
+using Long = long;
+
+void casts(const int &cr, const int *cip, const B *cb, void *vp,
+           const char *cc, int i, float f) {
+  (void)(int &)cr;
+  // CHECK: CStyleCastExpr {{.*}} 'int' lvalue <NoOp> resolved_as_const_cast casts_away_const{{$}}
+
+  (void)(int *)cip;
+  // CHECK: CStyleCastExpr {{.*}} 'int *' <NoOp> resolved_as_const_cast casts_away_const{{$}}
+
+  (void)(const int *)cip;
+  // CHECK: CStyleCastExpr {{.*}} 'const int *' <NoOp> resolved_as_const_cast{{$}}
+
+  (void)(D *)cb;
+  // CHECK: CStyleCastExpr {{.*}} 'D *' <BaseToDerived (B)> resolved_as_static_cast casts_away_const{{$}}
+
+  (void)(int *)vp;
+  // CHECK: CStyleCastExpr {{.*}} 'int *' <BitCast>{{$}}
+
+  (void)(int *)cc;
+  // CHECK: CStyleCastExpr {{.*}} 'int *' <BitCast> resolved_as_reinterpret_cast casts_away_const{{$}}
+
+  (void)(long)&i;
+  // CHECK: CStyleCastExpr {{.*}} 'long' <PointerToIntegral> resolved_as_reinterpret_cast{{$}}
+
+  (void)(int)f;
+  // CHECK: CStyleCastExpr {{.*}} 'int' <FloatingToIntegral>{{$}}
+
+  (void)Long(&i);
+  // CHECK: CXXFunctionalCastExpr {{.*}} functional cast to Long <PointerToIntegral> resolved_as_reinterpret_cast{{$}}
+}
+
+// JSON: "resolvedAs": "const_cast",
+// JSON-NEXT: "castsAwayConst": true
+// JSON: "resolvedAs": "reinterpret_cast",
+// JSON-NEXT: "castsAwayConst": true
diff --git a/clang/test/AST/ast-dump-cxx-profiles-attrs.cpp b/clang/test/AST/ast-dump-cxx-profiles-attrs.cpp
new file mode 100644
index 00000000000000..4c864918efa327
--- /dev/null
+++ b/clang/test/AST/ast-dump-cxx-profiles-attrs.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles -ast-dump %s \
+// RUN:   | FileCheck %s
+
+[[profiles::enforce(std::casting)]];
+// CHECK: EmptyDecl
+// CHECK-NEXT: ProfilesEnforceAttr {{.*}} "std::casting"
+
+[[profiles::exempt(std::casting, angle_header: "legacy.h",
+                   justification: "C interface")]];
+// CHECK: EmptyDecl
+// CHECK-NEXT: ProfilesExemptAttr {{.*}} "std::casting" "legacy.h"
+
+void f(int *p) {
+  [[profiles::suppress(std::casting, rule: reinterpret_cast,
+                       justification: "testing")]]
+  (void)reinterpret_cast<char *>(p);
+}
+// CHECK: AttributedStmt
+// CHECK-NEXT: ProfilesSuppressAttr {{.*}} "std::casting" "reinterpret_cast" "testing"
diff --git a/clang/test/Modules/cxx-profiles.cppm b/clang/test/Modules/cxx-profiles.cppm
new file mode 100644
index 00000000000000..67b0f61596b363
--- /dev/null
+++ b/clang/test/Modules/cxx-profiles.cppm
@@ -0,0 +1,72 @@
+// Test C++ profiles (P3589) enforced by C++20 named modules.
+//
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -emit-module-interface %t/A.cppm -o %t/A.pcm -verify
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -emit-module-interface %t/B.cppm -o %t/B.pcm -verify
+//
+// The implementation unit of A inherits the profiles A enforces on its module
+// declaration.
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fmodule-file=A=%t/A.pcm -fsyntax-only %t/A-impl.cpp -verify
+//
+// Templates are checked according to the profiles of the module that defines
+// them, not the importer.
+// RUN: not %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fmodule-file=A=%t/A.pcm -fmodule-file=B=%t/B.pcm \
+// RUN:   -fsyntax-only %t/use.cpp 2>&1 | FileCheck %t/use.cpp
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fmodule-file=A=%t/A.pcm -fmodule-file=B=%t/B.pcm \
+// RUN:   -fsyntax-only %t/enforcing-user.cpp -verify
+
+//--- A.cppm
+// expected-no-diagnostics
+export module A [[profiles::enforce(std::casting)]];
+
+export char *a(char *p) { return p; }
+
+export template <typename T> char *at(T *p) {
+  return reinterpret_cast<char *>(p);
+}
+
+//--- B.cppm
+// expected-no-diagnostics
+export module B;
+
+export template <typename T> char *bt(T *p) {
+  return reinterpret_cast<char *>(p);
+}
+
+//--- A-impl.cpp
+module A;
+
+char *impl(int *p) {
+  return reinterpret_cast<char *>(p);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
+
+//--- use.cpp
+import A [[profiles::require(std::casting)]];
+import B [[profiles::require(std::casting)]];
+
+char *use_a(int *p) { return at(p); }
+char *use_b(int *p) { return bt(p); }
+
+// CHECK: use.cpp:2:{{[0-9]+}}: error: module 'B' does not enforce profile 'std::casting'
+// CHECK: A.cppm:7:{{[0-9]+}}: error: std::casting forbids reinterpret_cast from 'int *' to 'char *'
+// CHECK-NOT: B.cppm{{.*}}error
+
+//--- enforcing-user.cpp
+[[profiles::enforce(std::casting)]];
+import B;
+
+// B does not enforce std::casting, so its template is not checked here.
+char *use_b(int *p) { return bt(p); }
+
+char *local(int *p) {
+  return reinterpret_cast<char *>(p);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
diff --git a/clang/test/Parser/cxx-profiles-attributes.cpp b/clang/test/Parser/cxx-profiles-attributes.cpp
new file mode 100644
index 00000000000000..278f9f7a207ce5
--- /dev/null
+++ b/clang/test/Parser/cxx-profiles-attributes.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=disabled %s
+
+// Without -fexperimental-cxx-profiles, the attributes are ignored.
+
+[[profiles::enforce(std::casting)]];
+// disabled-warning at -1 {{attribute ignored}}
+
+[[using profiles: enforce(std::casting)]];
+// disabled-warning at -1 {{attribute ignored}}
+
+[[profiles::enforce(acme::hardened(level: 3, mode: fast))]]; // #hardened
+// expected-warning at -1 {{unknown profile 'acme::hardened'; it will not be enforced}}
+// disabled-warning at -2 {{attribute ignored}}
+
+[[profiles::enforce(acme::hardened(level: 4))]];
+// expected-warning at -1 {{unknown profile 'acme::hardened'; it will not be enforced}}
+// expected-error at -2 {{profile 'acme::hardened' is already enforced with designator 'acme::hardened(level: 3, mode: fast)'}}
+// expected-note@#hardened {{profile 'acme::hardened' was enforced here}}
+// disabled-warning at -4 {{attribute ignored}}
+
+[[profiles::enforce(::std::casting)]];
+// expected-error at -1 {{expected a profile name}}
+// disabled-warning at -2 {{attribute ignored}}
+
+[[profiles::enforce(std::)]];
+// expected-error at -1 {{expected a profile name}}
+// disabled-warning at -2 {{attribute ignored}}
+
+[[profiles::enforce(std::casting, acme::other)]];
+// expected-warning at -1 {{unknown profile 'acme::other'; it will not be enforced}}
+// disabled-warning at -2 {{attribute ignored}}
+
+void f(int *p) {
+  [[profiles::suppress(std::casting)]] (void)p;
+  // disabled-warning at -1 {{attribute ignored}}
+
+  [[profiles::suppress(std::casting, rule: reinterpret_cast,
+                       justification: "a reason")]] (void)p;
+  // disabled-warning at -2 {{attribute ignored}}
+
+  [[profiles::suppress(std::casting, rule)]] (void)p;
+  // expected-error at -1 {{expected 'name: value' argument in}}
+  // disabled-warning at -2 {{attribute ignored}}
+
+  [[profiles::suppress(std::casting, rule: )]] (void)p;
+  // expected-error at -1 {{invalid token in profile argument}}
+  // disabled-warning at -2 {{attribute ignored}}
+
+  [[profiles::suppress]] (void)p;
+  // expected-error at -1 {{'profiles::suppress' attribute requires a profile name}}
+  // disabled-warning at -2 {{attribute ignored}}
+}
diff --git a/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt-nested.h b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt-nested.h
new file mode 100644
index 00000000000000..c70b8e2d2f0c2a
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt-nested.h
@@ -0,0 +1 @@
+inline char *nested_cast(int *p) { return reinterpret_cast<char *>(p); }
diff --git a/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt.h b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt.h
new file mode 100644
index 00000000000000..3e434ea1b39059
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-exempt.h
@@ -0,0 +1,3 @@
+// Exempted by [[profiles::exempt]], together with the headers it includes.
+#include "cxx-profiles-exempt-nested.h"
+inline char *exempt_cast(int *p) { return reinterpret_cast<char *>(p); }
diff --git a/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-not-exempt.h b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-not-exempt.h
new file mode 100644
index 00000000000000..7d89e769a1b667
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/Inputs/cxx-profiles-not-exempt.h
@@ -0,0 +1,4 @@
+inline char *not_exempt_cast(int *p) {
+  return reinterpret_cast<char *>(p);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
diff --git a/clang/test/SemaCXX/cxx-profiles/Inputs/system/cxx-profiles-system.h b/clang/test/SemaCXX/cxx-profiles/Inputs/system/cxx-profiles-system.h
new file mode 100644
index 00000000000000..354f753fe06f16
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/Inputs/system/cxx-profiles-system.h
@@ -0,0 +1,2 @@
+// System headers are exempt from all profiles.
+inline char *system_cast(int *p) { return reinterpret_cast<char *>(p); }
diff --git a/clang/test/SemaCXX/cxx-profiles/command-line.cpp b/clang/test/SemaCXX/cxx-profiles/command-line.cpp
new file mode 100644
index 00000000000000..4af4f79adaa065
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/command-line.cpp
@@ -0,0 +1,18 @@
+// RUN: not %clang_cc1 -std=c++20 -fcxx-profiles=std::casting -fsyntax-only \
+// RUN:   %s 2>&1 | FileCheck %s --check-prefix=NOT-ENABLED
+// RUN: not %clang_cc1 -std=c++20 -fcxx-profiles-preview=std::casting \
+// RUN:   -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=PREVIEW-NOT-ENABLED
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fcxx-profiles=acme::thing -fsyntax-only %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=UNKNOWN
+// RUN: not %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fcxx-profiles=std::casting -fsyntax-only %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MISMATCH
+
+// NOT-ENABLED: error: '-fcxx-profiles=' requires '-fexperimental-cxx-profiles'
+// PREVIEW-NOT-ENABLED: error: '-fcxx-profiles-preview=' requires '-fexperimental-cxx-profiles'
+// UNKNOWN: warning: unknown profile 'acme::thing'; it will not be enforced
+
+// MISMATCH: error: profile 'std::casting' is already enforced with designator 'std::casting'
+// MISMATCH: note: profile 'std::casting' was enforced on the command line
+[[profiles::enforce(std::casting(strict))]];
diff --git a/clang/test/SemaCXX/cxx-profiles/enforce.cpp b/clang/test/SemaCXX/cxx-profiles/enforce.cpp
new file mode 100644
index 00000000000000..488c945b014111
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/enforce.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles -fsyntax-only -verify %s
+
+[[profiles::enforce(std::casting)]]; // #enforce
+[[profiles::enforce(std::casting)]]; // Repeating a designator is a no-op.
+[[profiles::enforce(std::casting(strict))]];
+// expected-error at -1 {{profile 'std::casting' is already enforced with designator 'std::casting'}}
+// expected-note@#enforce {{profile 'std::casting' was enforced here}}
+[[profiles::enforce(acme::thing)]];
+// expected-warning at -1 {{unknown profile 'acme::thing'; it will not be enforced}}
+[[profiles::enforce]];
+// expected-error at -1 {{'profiles::enforce' attribute requires at least one profile designator}}
+
+namespace N { // #first-decl
+[[profiles::enforce(std::casting)]];
+// expected-error at -1 {{'profiles::enforce' attribute must appear at translation unit scope}}
+}
+
+[[profiles::enforce(std::casting)]];
+// expected-error at -1 {{'profiles::enforce' attribute must precede every declaration in the translation unit}}
+// expected-note@#first-decl {{first declaration is here}}
+
+[[profiles::enforce(std::casting)]] int x;
+// expected-error at -1 {{'profiles::enforce' attribute only applies to empty declarations}}
+
+[[profiles::require(std::casting)]] int y;
+// expected-error at -1 {{'profiles::require' attribute may only appear on a module import declaration}}
diff --git a/clang/test/SemaCXX/cxx-profiles/exempt.cpp b/clang/test/SemaCXX/cxx-profiles/exempt.cpp
new file mode 100644
index 00000000000000..0d9427b9f1f562
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/exempt.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles -fsyntax-only \
+// RUN:   -isystem %S/Inputs/system -I %S/Inputs -verify %s
+
+[[profiles::enforce(std::casting)]];
+[[profiles::exempt(std::casting, quote_header: "cxx-profiles-exempt.h",
+                   justification: "legacy interface")]];
+[[profiles::exempt(std::casting)]];
+// expected-error at -1 {{'profiles::exempt' attribute requires an 'angle_header' or 'quote_header' argument}}
+[[profiles::exempt(std::casting, quote_header: unquoted)]];
+// expected-error at -1 {{argument 'quote_header' of 'profiles::exempt' attribute must be a string literal}}
+
+#include <cxx-profiles-system.h>
+#include "cxx-profiles-exempt.h"
+#include "cxx-profiles-not-exempt.h"
+
+char *main_file_cast(int *p) {
+  return reinterpret_cast<char *>(p);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
diff --git a/clang/test/SemaCXX/cxx-profiles/preview.cpp b/clang/test/SemaCXX/cxx-profiles/preview.cpp
new file mode 100644
index 00000000000000..46614d30ab6dc2
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/preview.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles \
+// RUN:   -fcxx-profiles-preview=std::casting -fsyntax-only -verify %s
+
+// In preview mode, violations are warnings.
+
+char *f(int *p) {
+  return reinterpret_cast<char *>(p);
+  // expected-warning at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
diff --git a/clang/test/SemaCXX/cxx-profiles/std-casting.cpp b/clang/test/SemaCXX/cxx-profiles/std-casting.cpp
new file mode 100644
index 00000000000000..f63d7cafdbd88d
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/std-casting.cpp
@@ -0,0 +1,134 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++20 \
+// RUN:   -fexperimental-cxx-profiles -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++20 \
+// RUN:   -fexperimental-cxx-profiles -fcxx-profiles=std::casting -DCMDLINE \
+// RUN:   -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++20 \
+// RUN:   -fexperimental-cxx-profiles -DCMDLINE -fsyntax-only \
+// RUN:   -verify=not-enforced %s
+
+// not-enforced-no-diagnostics
+
+#ifndef CMDLINE
+[[profiles::enforce(std::casting)]];
+#endif
+
+namespace std {
+enum class byte : unsigned char {};
+}
+
+struct B {
+  virtual ~B();
+};
+struct D : B {};
+struct NB {};
+struct ND : NB {};
+using FloatPtr = float *;
+
+void reinterpret(int *ip, double *dp, unsigned long ul) {
+  (void)reinterpret_cast<float *>(ip);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'float *'}}
+  // expected-note at -2 {{use 'std::bit_cast' to reinterpret the object representation}}
+  (void)reinterpret_cast<float *>(dp);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'double *' to 'float *'}}
+  (void)reinterpret_cast<char *>(ip);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+  (void)reinterpret_cast<std::byte *>(ip);
+  (void)reinterpret_cast<const std::byte &>(*ip);
+  (void)reinterpret_cast<__UINTPTR_TYPE__>(ip);
+  (void)reinterpret_cast<int *>(ul);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'unsigned long' to 'int *'}}
+
+  (void)(float *)ip;
+  // expected-error at -1 {{std::casting forbids a C-style cast that performs a reinterpret_cast from 'int *' to 'float *'}}
+  // expected-note at -2 {{use 'reinterpret_cast' to make the conversion explicit}}
+  // expected-note at -3 {{use 'std::bit_cast' to reinterpret the object representation}}
+  (void)FloatPtr(ip);
+  // expected-error at -1 {{std::casting forbids a functional-style cast that performs a reinterpret_cast from 'int *' to 'FloatPtr' (aka 'float *')}}
+  // expected-note at -2 {{use 'reinterpret_cast' to make the conversion explicit}}
+  // expected-note at -3 {{use 'std::bit_cast' to reinterpret the object representation}}
+}
+
+void constness(const int *cip, const int &cr, volatile int *vip,
+               const char *cc) {
+  (void)const_cast<int *>(cip);
+  // expected-error at -1 {{std::casting forbids const_cast that casts away constness from 'const int *' to 'int *'}}
+  (void)const_cast<int &>(cr);
+  // expected-error at -1 {{std::casting forbids const_cast that casts away constness from 'const int' to 'int &'}}
+  (void)const_cast<int *>(vip);
+  (void)const_cast<const int *>(cip);
+
+  (void)(int *)cip;
+  // expected-error at -1 {{std::casting forbids a C-style cast that casts away constness from 'const int *' to 'int *'}}
+  // expected-note at -2 {{use 'const_cast' to make the conversion explicit}}
+  (void)(int *)cc;
+  // expected-error at -1 {{std::casting forbids a C-style cast that performs a reinterpret_cast from 'const char *' to 'int *'}}
+  // expected-error at -2 {{std::casting forbids a C-style cast that casts away constness from 'const char *' to 'int *'}}
+}
+
+void downcast(B *b, B &br, NB *nb) {
+  (void)static_cast<D *>(b);
+  // expected-error at -1 {{std::casting forbids static_cast from base class 'B' to derived class 'D'}}
+  // expected-note at -2 {{use 'dynamic_cast' to perform a checked conversion}}
+  (void)static_cast<D &>(br);
+  // expected-error at -1 {{std::casting forbids static_cast from base class 'B' to derived class 'D'}}
+  // expected-note at -2 {{use 'dynamic_cast' to perform a checked conversion}}
+  (void)static_cast<ND *>(nb);
+  // expected-error at -1 {{std::casting forbids static_cast from base class 'NB' to derived class 'ND'}}
+  (void)dynamic_cast<D *>(b);
+  (void)static_cast<B *>(static_cast<D *>(nullptr));
+
+  (void)(D *)b;
+  // expected-error at -1 {{std::casting forbids a C-style cast from base class 'B' to derived class 'D'}}
+  // expected-note at -2 {{use 'static_cast' to make the conversion explicit}}
+  // expected-note at -3 {{use 'dynamic_cast' to perform a checked conversion}}
+}
+
+void from_void(void *vp, const void *cvp) {
+  (void)static_cast<int *>(vp);
+  // expected-error at -1 {{std::casting forbids static_cast from 'void *' to 'int *'}}
+  (void)static_cast<std::byte *>(vp);
+  (void)static_cast<const void *>(vp);
+  (void)static_cast<const int *>(cvp);
+  // expected-error at -1 {{std::casting forbids static_cast from 'const void *' to 'const int *'}}
+}
+
+void allowed(float f, int i, long l, B *b) {
+  (void)static_cast<int>(f);
+  (void)(int)f;
+  (void)int(f);
+  (void)(long)i;
+  (void)static_cast<B *>(b);
+  (void)(void)b;
+}
+
+void unevaluated(int *ip) {
+  (void)sizeof(reinterpret_cast<float *>(ip));
+  decltype(reinterpret_cast<float *>(ip)) fp = nullptr;
+  (void)fp;
+}
+
+template <typename T> float *dependent(T *p) {
+  return reinterpret_cast<float *>(p);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'float *'}}
+  // expected-note at -2 {{use 'std::bit_cast' to reinterpret the object representation}}
+  // expected-note@#dependent-int {{in instantiation of function template specialization 'dependent<int>' requested here}}
+}
+
+template <typename T> float *non_dependent(T *, int *ip) {
+  return reinterpret_cast<float *>(ip);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'float *'}}
+  // expected-note at -2 {{use 'std::bit_cast' to reinterpret the object representation}}
+}
+
+void use_templates(int *ip, long *lp) {
+  // A violation in a template is reported once, not once per instantiation.
+  (void)dependent(ip); // #dependent-int
+  (void)dependent(lp);
+  (void)non_dependent(ip, ip);
+  (void)non_dependent(lp, ip);
+}
+
+float *global = reinterpret_cast<float *>(static_cast<int *>(nullptr));
+// expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'float *'}}
+// expected-note at -2 {{use 'std::bit_cast' to reinterpret the object representation}}
diff --git a/clang/test/SemaCXX/cxx-profiles/suppress.cpp b/clang/test/SemaCXX/cxx-profiles/suppress.cpp
new file mode 100644
index 00000000000000..b47b943b4b4053
--- /dev/null
+++ b/clang/test/SemaCXX/cxx-profiles/suppress.cpp
@@ -0,0 +1,75 @@
+// RUN: %clang_cc1 -std=c++20 -fexperimental-cxx-profiles -fsyntax-only -verify %s
+
+[[profiles::enforce(std::casting)]];
+
+void statements(int *ip, const int *cip) {
+  [[profiles::suppress(std::casting)]] (void)reinterpret_cast<char *>(ip);
+
+  [[profiles::suppress(std::casting, rule: reinterpret_cast_char)]]
+  (void)reinterpret_cast<char *>(ip);
+
+  [[profiles::suppress(std::casting, rule: "reinterpret_cast_char",
+                       justification: "byte access")]]
+  (void)reinterpret_cast<char *>(ip);
+
+  // Suppressing one rule does not suppress the others.
+  [[profiles::suppress(std::casting, rule: const_cast)]]
+  (void)reinterpret_cast<char *>(ip);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+
+  [[profiles::suppress(std::casting, rule: reinterpret_cast_char)]]
+  (void)(char *)cip;
+  // expected-error at -1 {{std::casting forbids a C-style cast that casts away constness from 'const int *' to 'char *'}}
+
+  // A suppression on a compound statement covers everything in it, including
+  // lambdas.
+  [[profiles::suppress(std::casting)]] {
+    (void)reinterpret_cast<char *>(ip);
+    auto L = [&] { return reinterpret_cast<char *>(ip); };
+    (void)L;
+  }
+
+  // The suppression only covers its own statement.
+  (void)reinterpret_cast<char *>(ip);
+  // expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+}
+
+void declarations(int *ip) {
+  [[profiles::suppress(std::casting)]] char *cp = reinterpret_cast<char *>(ip);
+  (void)cp;
+}
+
+[[profiles::suppress(std::casting)]] char *suppressed_function(int *ip) {
+  return reinterpret_cast<char *>(ip);
+}
+
+[[profiles::suppress(std::casting)]] char *suppressed_variable =
+    reinterpret_cast<char *>(static_cast<int *>(nullptr));
+
+char *unsuppressed_variable =
+    reinterpret_cast<char *>(static_cast<int *>(nullptr));
+// expected-error at -1 {{std::casting forbids reinterpret_cast from 'int *' to 'char *'}}
+
+namespace [[profiles::suppress(std::casting)]] suppressed_namespace {
+char *f(int *ip) { return reinterpret_cast<char *>(ip); }
+} // namespace suppressed_namespace
+
+struct [[profiles::suppress(std::casting)]] SuppressedClass {
+  char *f(int *ip) { return reinterpret_cast<char *>(ip); }
+};
+
+template <typename T> char *suppressed_template(T *p) {
+  [[profiles::suppress(std::casting)]] return reinterpret_cast<char *>(p);
+}
+char *use(int *ip) { return suppressed_template(ip); }
+
+void diagnostics() {
+  [[profiles::suppress(std::casting, rule: bogus)]] (void)0;
+  // expected-warning at -1 {{unknown rule 'bogus' of profile 'std::casting'; the suppression has no effect}}
+  [[profiles::suppress(acme::thing)]] (void)0;
+  // expected-warning at -1 {{unknown profile 'acme::thing'}}
+  [[profiles::suppress(std::casting, justification: unquoted)]] (void)0;
+  // expected-error at -1 {{argument 'justification' of 'profiles::suppress' attribute must be a string literal}}
+  [[profiles::suppress(std::casting, colour: red)]] (void)0;
+  // expected-warning at -1 {{unknown argument 'colour' in 'profiles::suppress' attribute ignored}}
+}



More information about the cfe-commits mailing list