[clang] c25572b - [clang] NFC: rename SK_CastDerivedToBaseRValue to SK_CastDerivedToBasePRValue

2021-06-09 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-09T12:38:59+02:00
New Revision: c25572bf2993438f24b57d859d072e8b2aa975d2

URL: 
https://github.com/llvm/llvm-project/commit/c25572bf2993438f24b57d859d072e8b2aa975d2
DIFF: 
https://github.com/llvm/llvm-project/commit/c25572bf2993438f24b57d859d072e8b2aa975d2.diff

LOG: [clang] NFC: rename SK_CastDerivedToBaseRValue to 
SK_CastDerivedToBasePRValue

This is a follow up to the "rvalue-to-prvalue" rename at D103720.

Signed-off-by: Matheus Izvekov 

Depends on D103720

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D103933

Added: 


Modified: 
clang/include/clang/Sema/Initialization.h
clang/lib/Sema/SemaInit.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Initialization.h 
b/clang/include/clang/Sema/Initialization.h
index 9889d5bcced5..8feb66995f95 100644
--- a/clang/include/clang/Sema/Initialization.h
+++ b/clang/include/clang/Sema/Initialization.h
@@ -804,7 +804,7 @@ class InitializationSequence {
 SK_ResolveAddressOfOverloadedFunction,
 
 /// Perform a derived-to-base cast, producing an rvalue.
-SK_CastDerivedToBaseRValue,
+SK_CastDerivedToBasePRValue,
 
 /// Perform a derived-to-base cast, producing an xvalue.
 SK_CastDerivedToBaseXValue,

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 430b14853d38..26d681b1340d 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -3457,7 +3457,7 @@ LLVM_DUMP_METHOD void InitializedEntity::dump() const {
 void InitializationSequence::Step::Destroy() {
   switch (Kind) {
   case SK_ResolveAddressOfOverloadedFunction:
-  case SK_CastDerivedToBaseRValue:
+  case SK_CastDerivedToBasePRValue:
   case SK_CastDerivedToBaseXValue:
   case SK_CastDerivedToBaseLValue:
   case SK_BindReference:
@@ -3585,7 +3585,7 @@ void 
InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
   Step S;
   switch (VK) {
   case VK_PRValue:
-S.Kind = SK_CastDerivedToBaseRValue;
+S.Kind = SK_CastDerivedToBasePRValue;
 break;
   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
@@ -8106,7 +8106,7 @@ ExprResult InitializationSequence::Perform(Sema ,
   // initializer.
   switch (Steps.front().Kind) {
   case SK_ResolveAddressOfOverloadedFunction:
-  case SK_CastDerivedToBaseRValue:
+  case SK_CastDerivedToBasePRValue:
   case SK_CastDerivedToBaseXValue:
   case SK_CastDerivedToBaseLValue:
   case SK_BindReference:
@@ -8191,7 +8191,7 @@ ExprResult InitializationSequence::Perform(Sema ,
  Step->Function.Function);
   break;
 
-case SK_CastDerivedToBaseRValue:
+case SK_CastDerivedToBasePRValue:
 case SK_CastDerivedToBaseXValue:
 case SK_CastDerivedToBaseLValue: {
   // We have a derived-to-base cast that produces either an rvalue or an
@@ -9617,8 +9617,8 @@ void InitializationSequence::dump(raw_ostream ) const {
   OS << "resolve address of overloaded function";
   break;
 
-case SK_CastDerivedToBaseRValue:
-  OS << "derived-to-base (rvalue)";
+case SK_CastDerivedToBasePRValue:
+  OS << "derived-to-base (prvalue)";
   break;
 
 case SK_CastDerivedToBaseXValue:



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1e50c3d - [clang] NRVO: Improvements and handling of more cases.

2021-06-12 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-12T16:43:32+02:00
New Revision: 1e50c3d785f4563873ab1ce86559f2a1285b5678

URL: 
https://github.com/llvm/llvm-project/commit/1e50c3d785f4563873ab1ce86559f2a1285b5678
DIFF: 
https://github.com/llvm/llvm-project/commit/1e50c3d785f4563873ab1ce86559f2a1285b5678.diff

LOG: [clang] NRVO: Improvements and handling of more cases.

This expands NRVO propagation for more cases:

Parse analysis improvement:
* Lambdas and Blocks with dependent return type can have their variables
  marked as NRVO Candidates.

Variable instantiation improvements:
* Fixes crash when instantiating NRVO variables in Blocks.
* Functions, Lambdas, and Blocks which have auto return type have their
  variables' NRVO status propagated. For Blocks with non-auto return type,
  as a limitation, this propagation does not consider the actual return
  type.

This also implements exclusion of VarDecls which are references to
dependent types.

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99696

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ade9d7691266..f7ec89a33e00c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3455,12 +3455,6 @@ class Sema final {
   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
 
-  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
- const VarDecl *NRVOCandidate,
- QualType ResultType,
- Expr *Value,
- bool AllowNRVO = true);
-
   bool CanPerformAggregateInitializationForOverloadResolution(
   const InitializedEntity , InitListExpr *From);
 
@@ -4760,28 +4754,30 @@ class Sema final {
SourceLocation Loc,
unsigned NumParams);
 
-  enum CopyElisionSemanticsKind {
-CES_Strict = 0,
-CES_AllowParameters = 1,
-CES_AllowDifferentTypes = 2,
-CES_AllowExceptionVariables = 4,
-CES_AllowRValueReferenceType = 8,
-CES_ImplicitlyMovableCXX11CXX14CXX17 =
-(CES_AllowParameters | CES_AllowDifferentTypes),
-CES_ImplicitlyMovableCXX20 =
-(CES_AllowParameters | CES_AllowDifferentTypes |
- CES_AllowExceptionVariables | CES_AllowRValueReferenceType),
+  struct NamedReturnInfo {
+const VarDecl *Candidate;
+
+enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
+Status S;
+
+bool isMoveEligible() const { return S != None; };
+bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
+  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
+ bool ForceCXX20 = false);
+  const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,
+ QualType ReturnType);
 
-  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
-   CopyElisionSemanticsKind CESK);
-  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
-  CopyElisionSemanticsKind CESK);
+  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
+ const NamedReturnInfo ,
+ Expr *Value);
 
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  Scope *CurScope);
   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
-  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr 
*RetValExp);
+  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
+ NamedReturnInfo );
 
   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
  bool IsVolatile, unsigned NumOutputs,

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 850c189cc51a3..cdde9a83a6d02 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1962,9 +1962,10 @@ static void checkEscapingByref(VarDecl *VD, Sema ) {
   SourceLocation Loc = VD->getLocation();
   Expr *VarRef =
   new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
-  ExprResult Result = 

[clang] 667fbcd - [clang] NRVO: Improvements and handling of more cases.

2021-06-10 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-10T23:02:51+02:00
New Revision: 667fbcdd0b2ee5e78f5ce9789b862e3bbca94644

URL: 
https://github.com/llvm/llvm-project/commit/667fbcdd0b2ee5e78f5ce9789b862e3bbca94644
DIFF: 
https://github.com/llvm/llvm-project/commit/667fbcdd0b2ee5e78f5ce9789b862e3bbca94644.diff

LOG: [clang] NRVO: Improvements and handling of more cases.

This expands NRVO propagation for more cases:

Parse analysis improvement:
* Lambdas and Blocks with dependent return type can have their variables
  marked as NRVO Candidates.

Variable instantiation improvements:
* Fixes crash when instantiating NRVO variables in Blocks.
* Functions, Lambdas, and Blocks which have auto return type have their
  variables' NRVO status propagated. For Blocks with non-auto return type,
  as a limitation, this propagation does not consider the actual return
  type.

This also implements exclusion of VarDecls which are references to
dependent types.

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99696

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ade9d769126..f7ec89a33e00 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3455,12 +3455,6 @@ class Sema final {
   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
 
-  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
- const VarDecl *NRVOCandidate,
- QualType ResultType,
- Expr *Value,
- bool AllowNRVO = true);
-
   bool CanPerformAggregateInitializationForOverloadResolution(
   const InitializedEntity , InitListExpr *From);
 
@@ -4760,28 +4754,30 @@ class Sema final {
SourceLocation Loc,
unsigned NumParams);
 
-  enum CopyElisionSemanticsKind {
-CES_Strict = 0,
-CES_AllowParameters = 1,
-CES_AllowDifferentTypes = 2,
-CES_AllowExceptionVariables = 4,
-CES_AllowRValueReferenceType = 8,
-CES_ImplicitlyMovableCXX11CXX14CXX17 =
-(CES_AllowParameters | CES_AllowDifferentTypes),
-CES_ImplicitlyMovableCXX20 =
-(CES_AllowParameters | CES_AllowDifferentTypes |
- CES_AllowExceptionVariables | CES_AllowRValueReferenceType),
+  struct NamedReturnInfo {
+const VarDecl *Candidate;
+
+enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
+Status S;
+
+bool isMoveEligible() const { return S != None; };
+bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
+  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
+ bool ForceCXX20 = false);
+  const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,
+ QualType ReturnType);
 
-  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
-   CopyElisionSemanticsKind CESK);
-  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
-  CopyElisionSemanticsKind CESK);
+  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
+ const NamedReturnInfo ,
+ Expr *Value);
 
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  Scope *CurScope);
   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
-  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr 
*RetValExp);
+  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
+ NamedReturnInfo );
 
   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
  bool IsVolatile, unsigned NumOutputs,

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 8fd4c680d3bf..9af247e0ab4f 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1949,9 +1949,10 @@ static void checkEscapingByref(VarDecl *VD, Sema ) {
   SourceLocation Loc = VD->getLocation();
   Expr *VarRef =
   new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
-  ExprResult Result = 

[clang] cbd0054 - [clang] Implement P2266 Simpler implicit move

2021-06-10 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-11T00:56:06+02:00
New Revision: cbd0054b9eb17ec48f0702e3828209646c8f5ebd

URL: 
https://github.com/llvm/llvm-project/commit/cbd0054b9eb17ec48f0702e3828209646c8f5ebd
DIFF: 
https://github.com/llvm/llvm-project/commit/cbd0054b9eb17ec48f0702e3828209646c8f5ebd.diff

LOG: [clang] Implement P2266 Simpler implicit move

This Implements 
[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2266r1.html|P2266 
Simpler implicit move]].

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99005

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p7-cxx14.cpp
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/coroutine-rvo.cpp
clang/test/SemaCXX/coroutines.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp
clang/test/SemaCXX/return-stack-addr.cpp
clang/test/SemaCXX/warn-return-std-move.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f7ec89a33e00..db389922ae3a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4763,7 +4763,7 @@ class Sema final {
 bool isMoveEligible() const { return S != None; };
 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
-  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(Expr *, bool ForceCXX2b = false);
   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
  bool ForceCXX20 = false);
   const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,

diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index 187e7a0516d1..cec80436d575 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -994,22 +994,10 @@ StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, 
Expr *E,
 E = R.get();
   }
 
-  // Move the return value if we can
-  NamedReturnInfo NRInfo = getNamedReturnInfo(E, /*ForceCXX20=*/true);
-  if (NRInfo.isMoveEligible()) {
-InitializedEntity Entity = InitializedEntity::InitializeResult(
-Loc, E->getType(), NRInfo.Candidate);
-ExprResult MoveResult = PerformMoveOrCopyInitialization(Entity, NRInfo, E);
-if (MoveResult.get())
-  E = MoveResult.get();
-  }
-
-  // FIXME: If the operand is a reference to a variable that's about to go out
-  // of scope, we should treat the operand as an xvalue for this overload
-  // resolution.
   VarDecl *Promise = FSI->CoroutinePromise;
   ExprResult PC;
   if (E && (isa(E) || !E->getType()->isVoidType())) {
+getNamedReturnInfo(E, /*ForceCXX2b=*/true);
 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
   } else {
 E = MakeFullDiscardedValueExpr(E).get();

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 784da7889091..a76976070cc5 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -854,10 +854,6 @@ ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr 
*Ex,
 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
 
   if (Ex && !Ex->isTypeDependent()) {
-QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
-if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
-  return ExprError();
-
 // Initialize the exception result.  This implicitly weeds out
 // abstract types or types with inaccessible copy constructors.
 
@@ -876,6 +872,10 @@ ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr 
*Ex,
 NamedReturnInfo NRInfo =
 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
 
+QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
+if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
+  return ExprError();
+
 InitializedEntity Entity = InitializedEntity::InitializeException(
 OpLoc, ExceptionObjectTy,
 /*NRVO=*/NRInfo.isCopyElidable());

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 35d29b8f12dd..7ef50b327678 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3312,15 +3312,16 @@ Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope 
*CurScope) {
 /// without considering function return type, if applicable.
 ///
 /// \param E The expression being returned from the 

[clang] bf20631 - [clang] Implement P2266 Simpler implicit move

2021-06-13 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-13T12:10:56+02:00
New Revision: bf20631782183cd19e0bb7219e908c2bbb01a75f

URL: 
https://github.com/llvm/llvm-project/commit/bf20631782183cd19e0bb7219e908c2bbb01a75f
DIFF: 
https://github.com/llvm/llvm-project/commit/bf20631782183cd19e0bb7219e908c2bbb01a75f.diff

LOG: [clang] Implement P2266 Simpler implicit move

This Implements 
[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2266r1.html|P2266 
Simpler implicit move]].

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99005

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p7-cxx14.cpp
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/coroutine-rvo.cpp
clang/test/SemaCXX/coroutines.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp
clang/test/SemaCXX/return-stack-addr.cpp
clang/test/SemaCXX/warn-return-std-move.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f7ec89a33e00c..db389922ae3a1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4763,7 +4763,7 @@ class Sema final {
 bool isMoveEligible() const { return S != None; };
 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
-  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(Expr *, bool ForceCXX2b = false);
   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
  bool ForceCXX20 = false);
   const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,

diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index 187e7a0516d10..cec80436d575e 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -994,22 +994,10 @@ StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, 
Expr *E,
 E = R.get();
   }
 
-  // Move the return value if we can
-  NamedReturnInfo NRInfo = getNamedReturnInfo(E, /*ForceCXX20=*/true);
-  if (NRInfo.isMoveEligible()) {
-InitializedEntity Entity = InitializedEntity::InitializeResult(
-Loc, E->getType(), NRInfo.Candidate);
-ExprResult MoveResult = PerformMoveOrCopyInitialization(Entity, NRInfo, E);
-if (MoveResult.get())
-  E = MoveResult.get();
-  }
-
-  // FIXME: If the operand is a reference to a variable that's about to go out
-  // of scope, we should treat the operand as an xvalue for this overload
-  // resolution.
   VarDecl *Promise = FSI->CoroutinePromise;
   ExprResult PC;
   if (E && (isa(E) || !E->getType()->isVoidType())) {
+getNamedReturnInfo(E, /*ForceCXX2b=*/true);
 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
   } else {
 E = MakeFullDiscardedValueExpr(E).get();

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index e9ab2bcd67c2e..20925f95f18e7 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -854,10 +854,6 @@ ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr 
*Ex,
 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
 
   if (Ex && !Ex->isTypeDependent()) {
-QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
-if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
-  return ExprError();
-
 // Initialize the exception result.  This implicitly weeds out
 // abstract types or types with inaccessible copy constructors.
 
@@ -876,6 +872,10 @@ ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr 
*Ex,
 NamedReturnInfo NRInfo =
 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
 
+QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
+if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
+  return ExprError();
+
 InitializedEntity Entity = InitializedEntity::InitializeException(
 OpLoc, ExceptionObjectTy,
 /*NRVO=*/NRInfo.isCopyElidable());

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 136e39198c728..afea878b299a6 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3312,15 +3312,16 @@ Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope 
*CurScope) {
 /// without considering function return type, if applicable.
 ///
 /// \param E The expression being returned 

[clang] 7ddd15c - [clang] Exclude function pointers on DefaultedComparisonAnalyzer

2021-06-18 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-18T13:07:47+02:00
New Revision: 7ddd15cd5dea76a19a9c5315e2a9903d74a49be8

URL: 
https://github.com/llvm/llvm-project/commit/7ddd15cd5dea76a19a9c5315e2a9903d74a49be8
DIFF: 
https://github.com/llvm/llvm-project/commit/7ddd15cd5dea76a19a9c5315e2a9903d74a49be8.diff

LOG: [clang] Exclude function pointers on DefaultedComparisonAnalyzer

This implements a more comprehensive fix than was done at D95409.
Instead of excluding just function pointer subobjects, we also
exclude any user-defined function pointer conversion operators.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D103855

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/class/class.compare/class.spaceship/p2.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c07e6f9d7421a..33aa5d0483e9c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9143,6 +9143,9 @@ def 
note_defaulted_comparison_cannot_deduce_undeduced_auto : Note<
   "%select{|member|base class}0 %1 declared here">;
 def note_defaulted_comparison_cannot_deduce_callee : Note<
   "selected 'operator<=>' for %select{|member|base class}0 %1 declared here">;
+def note_defaulted_comparison_selected_invalid : Note<
+  "would compare %select{|member|base class}0 %1 "
+  "as %2, which does not support relational comparisons">;
 def err_incorrect_defaulted_comparison_constexpr : Error<
   "defaulted definition of %select{%sub{select_defaulted_comparison_kind}1|"
   "three-way comparison operator}0 "

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index d39837d277045..5109f1e877a26 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7749,16 +7749,11 @@ class DefaultedComparisonAnalyzer
 
 if (Args[0]->getType()->isOverloadableType())
   S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
-else if (OO == OO_EqualEqual ||
- !Args[0]->getType()->isFunctionPointerType()) {
+else
   // FIXME: We determine whether this is a valid expression by checking to
   // see if there's a viable builtin operator candidate for it. That isn't
   // really what the rules ask us to do, but should give the right results.
-  //
-  // Note that the builtin operator for relational comparisons on function
-  // pointers is the only known case which cannot be used.
   S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, 
CandidateSet);
-}
 
 Result R;
 
@@ -7802,11 +7797,14 @@ class DefaultedComparisonAnalyzer
   return Result::deleted();
   }
 
-  // C++2a [class.compare.default]p3 [P2002R0]:
-  //   A defaulted comparison function is constexpr-compatible if [...]
-  //   no overlod resolution performed [...] results in a non-constexpr
-  //   function.
+  bool NeedsDeducing =
+  OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
+
   if (FunctionDecl *BestFD = Best->Function) {
+// C++2a [class.compare.default]p3 [P2002R0]:
+//   A defaulted comparison function is constexpr-compatible if
+//   [...] no overlod resolution performed [...] results in a
+//   non-constexpr function.
 assert(!BestFD->isDeleted() && "wrong overload resolution result");
 // If it's not constexpr, explain why not.
 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
@@ -7819,10 +7817,8 @@ class DefaultedComparisonAnalyzer
   return Result::deleted();
 }
 R.Constexpr &= BestFD->isConstexpr();
-  }
 
-  if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
-if (auto *BestFD = Best->Function) {
+if (NeedsDeducing) {
   // If any callee has an undeduced return type, deduce it now.
   // FIXME: It's not clear how a failure here should be handled. For
   // now, we produce an eager diagnostic, because that is forward
@@ -7848,10 +7844,9 @@ class DefaultedComparisonAnalyzer
 }
 return Result::deleted();
   }
-  if (auto *Info = S.Context.CompCategories.lookupInfoForType(
-  BestFD->getCallResultType())) {
-R.Category = Info->Kind;
-  } else {
+  auto *Info = S.Context.CompCategories.lookupInfoForType(
+  BestFD->getCallResultType());
+  if (!Info) {
 if (Diagnose == ExplainDeleted) {
   S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
   << Subobj.Kind << Subobj.Decl
@@ -7862,12 +7857,25 @@ class DefaultedComparisonAnalyzer
 }
   

[clang] 12c90e2 - [clang] NRVO: Improvements and handling of more cases.

2021-06-16 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-17T01:56:38+02:00
New Revision: 12c90e2e25dfd1d38250055efc21acb42d158912

URL: 
https://github.com/llvm/llvm-project/commit/12c90e2e25dfd1d38250055efc21acb42d158912
DIFF: 
https://github.com/llvm/llvm-project/commit/12c90e2e25dfd1d38250055efc21acb42d158912.diff

LOG: [clang] NRVO: Improvements and handling of more cases.

This expands NRVO propagation for more cases:

Parse analysis improvement:
* Lambdas and Blocks with dependent return type can have their variables
  marked as NRVO Candidates.

Variable instantiation improvements:
* Fixes crash when instantiating NRVO variables in Blocks.
* Functions, Lambdas, and Blocks which have auto return type have their
  variables' NRVO status propagated. For Blocks with non-auto return type,
  as a limitation, this propagation does not consider the actual return
  type.

This also implements exclusion of VarDecls which are references to
dependent types.

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99696

Added: 
clang/test/SemaObjCXX/block-capture.mm

Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ade9d7691266..f7ec89a33e00c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3455,12 +3455,6 @@ class Sema final {
   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
 
-  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
- const VarDecl *NRVOCandidate,
- QualType ResultType,
- Expr *Value,
- bool AllowNRVO = true);
-
   bool CanPerformAggregateInitializationForOverloadResolution(
   const InitializedEntity , InitListExpr *From);
 
@@ -4760,28 +4754,30 @@ class Sema final {
SourceLocation Loc,
unsigned NumParams);
 
-  enum CopyElisionSemanticsKind {
-CES_Strict = 0,
-CES_AllowParameters = 1,
-CES_AllowDifferentTypes = 2,
-CES_AllowExceptionVariables = 4,
-CES_AllowRValueReferenceType = 8,
-CES_ImplicitlyMovableCXX11CXX14CXX17 =
-(CES_AllowParameters | CES_AllowDifferentTypes),
-CES_ImplicitlyMovableCXX20 =
-(CES_AllowParameters | CES_AllowDifferentTypes |
- CES_AllowExceptionVariables | CES_AllowRValueReferenceType),
+  struct NamedReturnInfo {
+const VarDecl *Candidate;
+
+enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
+Status S;
+
+bool isMoveEligible() const { return S != None; };
+bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
+  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
+ bool ForceCXX20 = false);
+  const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,
+ QualType ReturnType);
 
-  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
-   CopyElisionSemanticsKind CESK);
-  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
-  CopyElisionSemanticsKind CESK);
+  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
+ const NamedReturnInfo ,
+ Expr *Value);
 
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  Scope *CurScope);
   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
-  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr 
*RetValExp);
+  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
+ NamedReturnInfo );
 
   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
  bool IsVolatile, unsigned NumOutputs,

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 850c189cc51a3..b87e2c2bea80d 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1955,6 +1955,9 @@ void Sema::RecordParsingTemplateParameterDepth(unsigned 
Depth) {
 
 // Check that the type of the VarDecl has an accessible copy constructor and
 // resolve its destructor's 

[clang] b88eb85 - [clang] use correct builtin type for defaulted comparison analyzer

2021-06-16 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-17T02:08:31+02:00
New Revision: b88eb855b53184161ad1ea0eea1962100941cf0b

URL: 
https://github.com/llvm/llvm-project/commit/b88eb855b53184161ad1ea0eea1962100941cf0b
DIFF: 
https://github.com/llvm/llvm-project/commit/b88eb855b53184161ad1ea0eea1962100941cf0b.diff

LOG: [clang] use correct builtin type for defaulted comparison analyzer

Fixes PR50591.

When analyzing classes with members which have user-defined conversion
operators to builtin types, the defaulted comparison analyzer was
picking the member type instead of the type for the builtin operator
which was selected as the best match.

This could either result in wrong comparison category being selected,
or a crash when runtime checks are enabled.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D103760

Added: 


Modified: 
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/class/class.compare/class.spaceship/p2.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index fd2d93e490c92..d39837d277045 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7863,8 +7863,13 @@ class DefaultedComparisonAnalyzer
 return Result::deleted();
   }
 } else {
+  QualType T = Best->BuiltinParamTypes[0];
+  assert(T == Best->BuiltinParamTypes[1] &&
+ "builtin comparison for 
diff erent types?");
+  assert(Best->BuiltinParamTypes[2].isNull() &&
+ "invalid builtin comparison");
   Optional Cat =
-  getComparisonCategoryForBuiltinCmp(Args[0]->getType());
+  getComparisonCategoryForBuiltinCmp(T);
   assert(Cat && "no category for builtin comparison?");
   R.Category = *Cat;
 }

diff  --git a/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp 
b/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
index 06126a48acf1a..47b14cb5f9616 100644
--- a/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
+++ b/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
@@ -172,3 +172,23 @@ namespace PR48856 {
 int C::*x;   // expected-note {{because 
there is no viable three-way comparison function for member 'x'}}
   };
 }
+
+namespace PR50591 {
+  struct a1 {
+operator int() const;
+  };
+  struct b1 {
+auto operator<=>(b1 const &) const = default;
+a1 f;
+  };
+  std::strong_ordering cmp_b1 = b1() <=> b1();
+
+  struct a2 {
+operator float() const;
+  };
+  struct b2 {
+auto operator<=>(b2 const &) const = default;
+a2 f;
+  };
+  std::partial_ordering cmp_b2 = b2() <=> b2();
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ced6b20 - [clang] Implement P2266 Simpler implicit move

2021-06-18 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-18T17:08:59+02:00
New Revision: ced6b204d18e6eed611f8ebf27122ec19147ea7a

URL: 
https://github.com/llvm/llvm-project/commit/ced6b204d18e6eed611f8ebf27122ec19147ea7a
DIFF: 
https://github.com/llvm/llvm-project/commit/ced6b204d18e6eed611f8ebf27122ec19147ea7a.diff

LOG: [clang] Implement P2266 Simpler implicit move

This Implements 
[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2266r1.html|P2266 
Simpler implicit move]].

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D99005

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p7-cxx14.cpp
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/coroutine-rvo.cpp
clang/test/SemaCXX/coroutines.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp
clang/test/SemaCXX/return-stack-addr.cpp
clang/test/SemaCXX/warn-return-std-move.cpp
clang/test/SemaObjCXX/block-capture.mm
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f7ec89a33e00c..db389922ae3a1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4763,7 +4763,7 @@ class Sema final {
 bool isMoveEligible() const { return S != None; };
 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
-  NamedReturnInfo getNamedReturnInfo(const Expr *E, bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(Expr *, bool ForceCXX2b = false);
   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
  bool ForceCXX20 = false);
   const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index b87e2c2bea80d..b450216dcc8b7 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1965,9 +1965,17 @@ static void checkEscapingByref(VarDecl *VD, Sema ) {
   SourceLocation Loc = VD->getLocation();
   Expr *VarRef =
   new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
-  ExprResult Result = S.PerformMoveOrCopyInitialization(
-  InitializedEntity::InitializeBlock(Loc, T, false),
-  Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible}, VarRef);
+  ExprResult Result;
+  auto IE = InitializedEntity::InitializeBlock(Loc, T, false);
+  if (S.getLangOpts().CPlusPlus2b) {
+auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
+   VK_XValue, FPOptionsOverride());
+Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
+  } else {
+Result = S.PerformMoveOrCopyInitialization(
+IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
+VarRef);
+  }
 
   if (!Result.isInvalid()) {
 Result = S.MaybeCreateExprWithCleanups(Result);

diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index 187e7a0516d10..cec80436d575e 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -994,22 +994,10 @@ StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, 
Expr *E,
 E = R.get();
   }
 
-  // Move the return value if we can
-  NamedReturnInfo NRInfo = getNamedReturnInfo(E, /*ForceCXX20=*/true);
-  if (NRInfo.isMoveEligible()) {
-InitializedEntity Entity = InitializedEntity::InitializeResult(
-Loc, E->getType(), NRInfo.Candidate);
-ExprResult MoveResult = PerformMoveOrCopyInitialization(Entity, NRInfo, E);
-if (MoveResult.get())
-  E = MoveResult.get();
-  }
-
-  // FIXME: If the operand is a reference to a variable that's about to go out
-  // of scope, we should treat the operand as an xvalue for this overload
-  // resolution.
   VarDecl *Promise = FSI->CoroutinePromise;
   ExprResult PC;
   if (E && (isa(E) || !E->getType()->isVoidType())) {
+getNamedReturnInfo(E, /*ForceCXX2b=*/true);
 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
   } else {
 E = MakeFullDiscardedValueExpr(E).get();

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 9d554b5b3a909..a57c5ad198e1b 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -854,10 +854,6 @@ ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr 
*Ex,
 Diag(OpLoc, 

[clang] 2c60d22 - [clang] disable P2266 simpler implicit moves under -fms-compatibility

2021-07-07 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-08T00:13:11+02:00
New Revision: 2c60d22610325bcd6fb4c4bcc8b522b9fdfb46ee

URL: 
https://github.com/llvm/llvm-project/commit/2c60d22610325bcd6fb4c4bcc8b522b9fdfb46ee
DIFF: 
https://github.com/llvm/llvm-project/commit/2c60d22610325bcd6fb4c4bcc8b522b9fdfb46ee.diff

LOG: [clang] disable P2266 simpler implicit moves under -fms-compatibility

The Microsoft STL currently has some issues with P2266.
We disable it for now in that mode, but we might come back later with a
more targetted approach.

Signed-off-by: Matheus Izvekov 

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D105518

Added: 
clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp

Modified: 
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Sema/SemaStmt.cpp

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index bca0bb4ada672..676421552a757 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -598,7 +598,8 @@ static void InitializeCPlusPlusFeatureTestMacros(const 
LangOptions ,
   }
   // C++2b features.
   if (LangOpts.CPlusPlus2b) {
-Builder.defineMacro("__cpp_implicit_move", "202011L");
+if (!LangOpts.MSVCCompat)
+  Builder.defineMacro("__cpp_implicit_move", "202011L");
 Builder.defineMacro("__cpp_size_t_suffix", "202011L");
   }
   if (LangOpts.Char8)

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 506c06b412b6f..59e64c4b1c5b1 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -,8 +,13 @@ Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *, 
bool ForceCXX2b) {
   if (!VD)
 return NamedReturnInfo();
   NamedReturnInfo Res = getNamedReturnInfo(VD);
+  // FIXME: We supress simpler implicit move here (unless ForceCXX2b is true)
+  //in msvc compatibility mode just as a temporary work around,
+  //as the MSVC STL has issues with this change.
+  //We will come back later with a more targeted approach.
   if (Res.Candidate && !E->isXValue() &&
-  (ForceCXX2b || getLangOpts().CPlusPlus2b)) {
+  (ForceCXX2b ||
+   (getLangOpts().CPlusPlus2b && !getLangOpts().MSVCCompat))) {
 E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
  CK_NoOp, E, nullptr, VK_XValue,
  FPOptionsOverride());

diff  --git a/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp 
b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp
new file mode 100644
index 0..2143c0535e606
--- /dev/null
+++ b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -fcxx-exceptions   
 -verify=new %s
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -fcxx-exceptions 
-fms-compatibility -verify=old %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions   
 -verify=old %s
+
+// FIXME: This is a test for a temporary workaround where we disable simpler 
implicit moves
+//when compiling with -fms-compatibility, because the MSVC STL does 
not compile.
+//A better workaround is under discussion.
+//The test cases here are just a copy from 
`CXX/class/class.init/class.copy.elision/p3.cpp`,
+//so feel free to delete this file when the workaround is not needed 
anymore.
+
+struct CopyOnly {
+  CopyOnly(); // new-note {{candidate constructor not viable: requires 0 
arguments, but 1 was provided}}
+  // new-note@-1 {{candidate constructor not viable: requires 0 arguments, but 
1 was provided}}
+  CopyOnly(CopyOnly &); // new-note {{candidate constructor not viable: 
expects an lvalue for 1st argument}}
+  // new-note@-1 {{candidate constructor not viable: expects an lvalue for 1st 
argument}}
+};
+struct MoveOnly {
+  MoveOnly();
+  MoveOnly(MoveOnly &&);
+};
+MoveOnly &();
+
+MoveOnly &(MoveOnly &) {
+  return w; // old-error {{cannot bind to lvalue of type}}
+}
+
+CopyOnly test2(bool b) {
+  static CopyOnly w1;
+  CopyOnly w2;
+  if (b) {
+return w1;
+  } else {
+return w2; // new-error {{no matching constructor for initialization}}
+  }
+}
+
+template  T &(T &) { return x; } // old-error {{cannot bind 
to lvalue of type}}
+template MoveOnly (MoveOnly &);
+template MoveOnly &(MoveOnly &&); // old-note {{in 
instantiation of function template specialization}}
+
+MoveOnly &() {
+  MoveOnly & = rref();
+  return x; // old-error {{cannot bind to lvalue of type}}
+}
+
+void test5() try {
+  CopyOnly x;
+  throw x; // new-error {{no matching constructor for initialization}}
+} catch (...) {
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] 5a1c504 - [clang] fix constexpr code generation for user conversions.

2021-07-08 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-08T20:23:19+02:00
New Revision: 5a1c50410ccc1973a1a0a4acca0c01677c28e9b6

URL: 
https://github.com/llvm/llvm-project/commit/5a1c50410ccc1973a1a0a4acca0c01677c28e9b6
DIFF: 
https://github.com/llvm/llvm-project/commit/5a1c50410ccc1973a1a0a4acca0c01677c28e9b6.diff

LOG: [clang] fix constexpr code generation for user conversions.

When building the member call to a user conversion function during an
implicit cast, the expression was not being checked for immediate
invocation, so we were never adding the ConstantExpr node to AST.

This would cause the call to the user conversion operator to be emitted
even if it was constantexpr evaluated, and this would even trip an
assert when said user conversion was declared consteval:
`Assertion failed: !cast(GD.getDecl())->isConsteval() && 
"consteval function should never be emitted", file 
clang\lib\CodeGen\CodeGenModule.cpp, line 3530`

Fixes PR48855.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D105446

Added: 


Modified: 
clang/lib/AST/Expr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/test/CodeGenCXX/cxx2a-consteval.cpp

Removed: 




diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 03dc65eeb6b03..842b9c0a8a0e2 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -1913,6 +1913,7 @@ Expr *CastExpr::getSubExprAsWritten() {
   SubExpr =
 
skipImplicitTemporary(cast(SubExpr->IgnoreImplicit())->getArg(0));
 else if (E->getCastKind() == CK_UserDefinedConversion) {
+  SubExpr = SubExpr->IgnoreImplicit();
   assert((isa(SubExpr) ||
   isa(SubExpr)) &&
  "Unexpected SubExpr for CK_UserDefinedConversion.");

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index b0b6b3dca5f6a..2e9e9a4a88dff 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -7786,7 +7786,7 @@ ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, 
NamedDecl *FoundDecl,
 Method->getType()->castAs()))
 return ExprError();
 
-  return CE;
+  return CheckForImmediateInvocation(CE, CE->getMethodDecl());
 }
 
 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,

diff  --git a/clang/test/CodeGenCXX/cxx2a-consteval.cpp 
b/clang/test/CodeGenCXX/cxx2a-consteval.cpp
index e5bd99c6ca537..7ee693ca2 100644
--- a/clang/test/CodeGenCXX/cxx2a-consteval.cpp
+++ b/clang/test/CodeGenCXX/cxx2a-consteval.cpp
@@ -210,3 +210,36 @@ long test_AggCtor() {
   AggCtor C(i);
   return C.a + C.b;
 }
+
+struct UserConv {
+  consteval operator int() const noexcept { return 42; }
+};
+
+// EVAL-FN-LABEL: @_Z13test_UserConvv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:ret i32 42
+//
+int test_UserConv() {
+  return UserConv();
+}
+
+int test_UserConvOverload_helper(int a) { return a; }
+
+// EVAL-FN-LABEL: @_Z21test_UserConvOverloadv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:%call = call i32 @_Z28test_UserConvOverload_helperi(i32 42)
+// EVAL-FN-NEXT:ret i32 %call
+//
+int test_UserConvOverload() {
+  return test_UserConvOverload_helper(UserConv());
+}
+
+consteval int test_UserConvOverload_helper_ceval(int a) { return a; }
+
+// EVAL-FN-LABEL: @_Z27test_UserConvOverload_cevalv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:ret i32 42
+//
+int test_UserConvOverload_ceval() {
+  return test_UserConvOverload_helper_ceval(UserConv());
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ad14b5b - [clang] Stop providing builtin overload candidate for relational function pointer comparisons

2021-06-25 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-26T00:08:02+02:00
New Revision: ad14b5b008e2f643cb989ec645f12bf26a8659bb

URL: 
https://github.com/llvm/llvm-project/commit/ad14b5b008e2f643cb989ec645f12bf26a8659bb
DIFF: 
https://github.com/llvm/llvm-project/commit/ad14b5b008e2f643cb989ec645f12bf26a8659bb.diff

LOG: [clang] Stop providing builtin overload candidate for relational function 
pointer comparisons

Word on the grapevine was that the committee had some discussion that
ended with unanimous agreement on eliminating relational function pointer 
comparisons.

We wanted to be bold and just ban all of them cold turkey.
But then we chickened out at the last second and are going for
eliminating just the spaceship overload candidate instead, for now.

See D104680 for reference.

This should be fine and "safe", because the only possible semantic change this
would cause is that overload resolution could possibly be ambiguous if
there was another viable candidate equally as good.

But to save face a little we are going to:
* Issue an "error" for three-way comparisons on function pointers.
  But all this is doing really is changing one vague error message,
  from an "invalid operands to binary expression" into an
  "ordered comparison of function pointers", which sounds more like we mean 
business.
* Otherwise "warn" that comparing function pointers like that is totally
  not cool (unless we are told to keep quiet about this).

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D104892

Added: 
clang/test/SemaCXX/compare-function-pointer.cpp

Modified: 
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
clang/test/CXX/drs/dr15xx.cpp
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/expr/expr.const/p2-0x.cpp
clang/test/FixIt/fixit.cpp
clang/test/Parser/cxx-template-argument.cpp
clang/test/Sema/compare.c
clang/test/SemaCXX/compare-cxx2a.cpp
clang/test/SemaTemplate/resolve-single-template-id.cpp
compiler-rt/test/asan/TestCases/Posix/coverage-module-unloaded.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index ca8e05f27fc5..f35c105964a3 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -525,6 +525,7 @@ def OpenCLUnsupportedRGBA: 
DiagGroup<"opencl-unsupported-rgba">;
 def UnderalignedExceptionObject : DiagGroup<"underaligned-exception-object">;
 def DeprecatedObjCIsaUsage : DiagGroup<"deprecated-objc-isa-usage">;
 def ExplicitInitializeCall : DiagGroup<"explicit-initialize-call">;
+def OrderedCompareFunctionPointers : 
DiagGroup<"ordered-compare-function-pointers">;
 def Packed : DiagGroup<"packed">;
 def Padded : DiagGroup<"padded">;
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b114cdff1d94..b5b8bc6aa3c5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6794,9 +6794,14 @@ def ext_typecheck_compare_complete_incomplete_pointers : 
Extension<
   "%0 is %select{|in}2complete and "
   "%1 is %select{|in}3complete">,
   InGroup;
+def warn_typecheck_ordered_comparison_of_function_pointers : Warning<
+  "ordered comparison of function pointers (%0 and %1)">,
+  InGroup;
 def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn<
   "ordered comparison of function pointers (%0 and %1)">,
-  InGroup>;
+  InGroup;
+def err_typecheck_ordered_comparison_of_function_pointers : Error<
+  "ordered comparison of function pointers (%0 and %1)">;
 def ext_typecheck_comparison_of_fptr_to_void : Extension<
   "equality comparison between function pointer and void pointer (%0 and %1)">;
 def err_typecheck_comparison_of_fptr_to_void : Error<
@@ -9143,9 +9148,6 @@ def 
note_defaulted_comparison_cannot_deduce_undeduced_auto : Note<
   "%select{|member|base class}0 %1 declared here">;
 def note_defaulted_comparison_cannot_deduce_callee : Note<
   "selected 'operator<=>' for %select{|member|base class}0 %1 declared here">;
-def note_defaulted_comparison_selected_invalid : Note<
-  "would compare %select{|member|base class}0 %1 "
-  "as %2, which does not support relational comparisons">;
 def err_incorrect_defaulted_comparison_constexpr : Error<
   "defaulted definition of %select{%sub{select_defaulted_comparison_kind}1|"
   "three-way comparison operator}0 "

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a68a06eb4d27..83c97626ff7e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7869,15 +7869,6 

[clang] 7d2d5a3 - [clang] Apply P1825 as Defect Report from C++11 up to C++20.

2021-07-01 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-01T12:10:06+02:00
New Revision: 7d2d5a3a6d7aaa40468c30250bf6b0938ef02c08

URL: 
https://github.com/llvm/llvm-project/commit/7d2d5a3a6d7aaa40468c30250bf6b0938ef02c08
DIFF: 
https://github.com/llvm/llvm-project/commit/7d2d5a3a6d7aaa40468c30250bf6b0938ef02c08.diff

LOG: [clang] Apply P1825 as Defect Report from C++11 up to C++20.

This extends the effects of [[ 
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1825r0.html | P1825 ]] 
to all C++ standards from C++11 up to C++20.

According to Motion 23 from Cologne 2019, P1825R0 was accepted as a Defect 
Report, so we retroactively apply this all the way back to C++11.

Note that we also remove implicit moves from C++98 as an extension
altogether, since the expanded first overload resolution from P1825
can cause some meaning changes in C++98.
For example it can change which copy constructor is picked when both const
and non-const ones are available.

This also rips out warn_return_std_move since there are no cases where it would 
be worthwhile to suggest it.

This also fixes a bug with bailing into the second overload resolution
when encountering a non-rvref qualified conversion operator.
This was unnoticed until now, so two new test cases cover these.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D104500

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaStmt.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/SemaCXX/P1155.cpp
clang/test/SemaCXX/conversion-function.cpp
clang/test/SemaObjCXX/block-capture.mm

Removed: 
clang/test/SemaCXX/warn-return-std-move.cpp



diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 22c2a1a39ea13..a9d7388950331 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6485,12 +6485,6 @@ def warn_pessimizing_move_on_initialization : Warning<
   InGroup, DefaultIgnore;
 def note_remove_move : Note<"remove std::move call here">;
 
-def warn_return_std_move : Warning<
-  "local variable %0 will be copied despite being %select{returned|thrown}1 by 
name">,
-  InGroup, DefaultIgnore;
-def note_add_std_move : Note<
-  "call 'std::move' explicitly to avoid copying">;
-
 def warn_string_plus_int : Warning<
   "adding %0 to a string does not append to the string">,
   InGroup;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3f7db9bc5be8b..ad987dffac03a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4782,8 +4782,7 @@ class Sema final {
 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
   NamedReturnInfo getNamedReturnInfo(Expr *, bool ForceCXX2b = false);
-  NamedReturnInfo getNamedReturnInfo(const VarDecl *VD,
- bool ForceCXX20 = false);
+  NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
   const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,
  QualType ReturnType);
 

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index afea878b299a6..1e86f382f060b 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3332,7 +3332,7 @@ Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *, 
bool ForceCXX2b) {
   const auto *VD = dyn_cast(DR->getDecl());
   if (!VD)
 return NamedReturnInfo();
-  NamedReturnInfo Res = getNamedReturnInfo(VD, /*ForceCXX20=*/ForceCXX2b);
+  NamedReturnInfo Res = getNamedReturnInfo(VD);
   if (Res.Candidate && !E->isXValue() &&
   (ForceCXX2b || getLangOpts().CPlusPlus2b)) {
 E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
@@ -3342,46 +3342,28 @@ Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr 
*, bool ForceCXX2b) {
   return Res;
 }
 
-/// Updates the status in the given NamedReturnInfo object to disallow
-/// copy elision, and optionally also implicit move.
-///
-/// \param Info The NamedReturnInfo object to update.
-///
-/// \param CanMove If true, disallow only copy elision.
-/// If false, also disallow implcit move.
-static void disallowNRVO(Sema::NamedReturnInfo , bool CanMove) {
-  Info.S = std::min(Info.S, CanMove ? Sema::NamedReturnInfo::MoveEligible
-: Sema::NamedReturnInfo::None);
-}
-
 /// Determine whether the given NRVO candidate variable is move-eligible or
 /// copy-elidable, without considering function return type.
 ///
 /// \param VD The NRVO candidate variable.
 ///
-/// \param ForceCXX20 Overrides detection of current language mode
-/// and uses the rules for C++20.
-///
 /// \returns An aggregate which contains the Candidate and isMoveEligible

[clang] d6144c3 - [clang] add C++ feature test macro for P2266 simpler implicit move

2021-06-26 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-06-26T23:05:23+02:00
New Revision: d6144c30fb6ae7ac15c82d512f8da7572577c2d2

URL: 
https://github.com/llvm/llvm-project/commit/d6144c30fb6ae7ac15c82d512f8da7572577c2d2
DIFF: 
https://github.com/llvm/llvm-project/commit/d6144c30fb6ae7ac15c82d512f8da7572577c2d2.diff

LOG: [clang] add C++ feature test macro for P2266 simpler implicit move

The feature was implemented in D99005, but we forgot to add the test
macro.

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D104984

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Lexer/cxx-features.cpp

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index af1196f131925..bca0bb4ada672 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -597,8 +597,10 @@ static void InitializeCPlusPlusFeatureTestMacros(const 
LangOptions ,
 Builder.defineMacro("__cpp_using_enum", "201907L");
   }
   // C++2b features.
-  if (LangOpts.CPlusPlus2b)
+  if (LangOpts.CPlusPlus2b) {
+Builder.defineMacro("__cpp_implicit_move", "202011L");
 Builder.defineMacro("__cpp_size_t_suffix", "202011L");
+  }
   if (LangOpts.Char8)
 Builder.defineMacro("__cpp_char8_t", "201811L");
   Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");

diff  --git a/clang/test/Lexer/cxx-features.cpp 
b/clang/test/Lexer/cxx-features.cpp
index 8f283dd8c8d9f..40c73f6019420 100644
--- a/clang/test/Lexer/cxx-features.cpp
+++ b/clang/test/Lexer/cxx-features.cpp
@@ -31,6 +31,10 @@
 
 // --- C++2b features ---
 
+#if check(implicit_move, 0, 0, 0, 0, 0, 202011)
+#error "wrong value for __cpp_implicit_move"
+#endif
+
 #if check(size_t_suffix, 0, 0, 0, 0, 0, 202011)
 #error "wrong value for __cpp_size_t_suffix"
 #endif



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2110638 - [clang] fixes named return of variables with dependent alignment

2021-07-05 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-06T02:30:44+02:00
New Revision: 21106388eb96c87b3f580c42a322c76a61605261

URL: 
https://github.com/llvm/llvm-project/commit/21106388eb96c87b3f580c42a322c76a61605261
DIFF: 
https://github.com/llvm/llvm-project/commit/21106388eb96c87b3f580c42a322c76a61605261.diff

LOG: [clang] fixes named return of variables with dependent alignment

Named return of a variable with aligned attribute would
trip an assert in case alignment was dependent.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D105380

Added: 


Modified: 
clang/include/clang/AST/Decl.h
clang/lib/AST/Decl.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 020df62755706..d22594ae8442a 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1494,6 +1494,9 @@ class VarDecl : public DeclaratorDecl, public 
Redeclarable {
 NonParmVarDeclBits.EscapingByref = true;
   }
 
+  /// Determines if this variable's alignment is dependent.
+  bool hasDependentAlignment() const;
+
   /// Retrieve the variable declaration from which this variable could
   /// be instantiated, if it is an instantiation (rather than a non-template).
   VarDecl *getTemplateInstantiationPattern() const;

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 5047dc19b0c6f..a92d3726e8474 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2534,6 +2534,13 @@ bool VarDecl::isNonEscapingByref() const {
   return hasAttr() && !NonParmVarDeclBits.EscapingByref;
 }
 
+bool VarDecl::hasDependentAlignment() const {
+  return getType()->isDependentType() ||
+ llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) 
{
+   return AA->isAlignmentDependent();
+ });
+}
+
 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
   const VarDecl *VD = this;
 

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0075464552321..9e1f42a15e556 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13310,16 +13310,6 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl 
*var) {
 CheckCompleteDecompositionDeclaration(DD);
 }
 
-/// Determines if a variable's alignment is dependent.
-static bool hasDependentAlignment(VarDecl *VD) {
-  if (VD->getType()->isDependentType())
-return true;
-  for (auto *I : VD->specific_attrs())
-if (I->isAlignmentDependent())
-  return true;
-  return false;
-}
-
 /// Check if VD needs to be dllexport/dllimport due to being in a
 /// dllexport/import function.
 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
@@ -13408,7 +13398,7 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) {
   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
 // Protect the check so that it's not performed on dependent types and
 // dependent alignments (we can't determine the alignment in that case).
-if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
+if (VD->getTLSKind() && !VD->hasDependentAlignment() &&
 !VD->isInvalidDecl()) {
   CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
   if (Context.getDeclAlign(VD) > MaxAlignChars) {

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 1e86f382f060b..506c06b412b6f 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3395,7 +3395,7 @@ Sema::NamedReturnInfo Sema::getNamedReturnInfo(const 
VarDecl *VD) {
 
   // Variables with higher required alignment than their type's ABI
   // alignment cannot use NRVO.
-  if (!VDType->isDependentType() && VD->hasAttr() &&
+  if (!VD->hasDependentAlignment() &&
   Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
 Info.S = NamedReturnInfo::MoveEligible;
 

diff  --git a/clang/test/CodeGen/nrvo-tracking.cpp 
b/clang/test/CodeGen/nrvo-tracking.cpp
index 7893140e1010a..2d6eb9efeca20 100644
--- a/clang/test/CodeGen/nrvo-tracking.cpp
+++ b/clang/test/CodeGen/nrvo-tracking.cpp
@@ -1,9 +1,9 @@
 // RUN: %clang_cc1 -std=c++20 -fblocks -Wno-return-stack-address -triple 
x86_64-unknown-unknown-gnu -emit-llvm -O1 -fexperimental-new-pass-manager -o - 
%s | FileCheck %s
 
-struct X {
-X();
-X(const X&);
-X(X&&);
+struct alignas(4) X {
+  X();
+  X(const X &);
+  X(X &&);
 };
 
 #define L(A, B, C) void l##A() {\
@@ -210,3 +210,75 @@ void b_attr() {
 };
   }()();
 }
+
+namespace test_alignas {
+
+template  X t1() {
+  X a [[gnu::aligned(A)]];
+  return a;
+}
+
+// CHECK-LABEL: define{{.*}} void @_ZN12test_alignas2t1ILi1EEE1Xv
+// CHECK:   call {{.*}} @_ZN1XC1Ev
+// CHECK-NEXT:  ret void
+template X t1<1>();
+
+// CHECK-LABEL: define{{.*}} void 

[clang] f2d5fce - [clang] fixes named return of variables with dependent alignment

2021-07-06 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-07T02:54:55+02:00
New Revision: f2d5fce86e81a8b37fbc0829a1c68b6eb48f8365

URL: 
https://github.com/llvm/llvm-project/commit/f2d5fce86e81a8b37fbc0829a1c68b6eb48f8365
DIFF: 
https://github.com/llvm/llvm-project/commit/f2d5fce86e81a8b37fbc0829a1c68b6eb48f8365.diff

LOG: [clang] fixes named return of variables with dependent alignment

Named return of a variable with aligned attribute would
trip an assert in case alignment was dependent.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D105380

Added: 


Modified: 
clang/include/clang/AST/Decl.h
clang/lib/AST/Decl.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 020df62755706..d22594ae8442a 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1494,6 +1494,9 @@ class VarDecl : public DeclaratorDecl, public 
Redeclarable {
 NonParmVarDeclBits.EscapingByref = true;
   }
 
+  /// Determines if this variable's alignment is dependent.
+  bool hasDependentAlignment() const;
+
   /// Retrieve the variable declaration from which this variable could
   /// be instantiated, if it is an instantiation (rather than a non-template).
   VarDecl *getTemplateInstantiationPattern() const;

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 5047dc19b0c6f..5dcfca45a54b6 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2534,6 +2534,14 @@ bool VarDecl::isNonEscapingByref() const {
   return hasAttr() && !NonParmVarDeclBits.EscapingByref;
 }
 
+bool VarDecl::hasDependentAlignment() const {
+  QualType T = getType();
+  return T->isDependentType() || T->isUndeducedAutoType() ||
+ llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) 
{
+   return AA->isAlignmentDependent();
+ });
+}
+
 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
   const VarDecl *VD = this;
 

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0075464552321..700a6db7fea89 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13310,16 +13310,6 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl 
*var) {
 CheckCompleteDecompositionDeclaration(DD);
 }
 
-/// Determines if a variable's alignment is dependent.
-static bool hasDependentAlignment(VarDecl *VD) {
-  if (VD->getType()->isDependentType())
-return true;
-  for (auto *I : VD->specific_attrs())
-if (I->isAlignmentDependent())
-  return true;
-  return false;
-}
-
 /// Check if VD needs to be dllexport/dllimport due to being in a
 /// dllexport/import function.
 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
@@ -13408,8 +13398,7 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) {
   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
 // Protect the check so that it's not performed on dependent types and
 // dependent alignments (we can't determine the alignment in that case).
-if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
-!VD->isInvalidDecl()) {
+if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
   CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
   if (Context.getDeclAlign(VD) > MaxAlignChars) {
 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 1e86f382f060b..506c06b412b6f 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3395,7 +3395,7 @@ Sema::NamedReturnInfo Sema::getNamedReturnInfo(const 
VarDecl *VD) {
 
   // Variables with higher required alignment than their type's ABI
   // alignment cannot use NRVO.
-  if (!VDType->isDependentType() && VD->hasAttr() &&
+  if (!VD->hasDependentAlignment() &&
   Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
 Info.S = NamedReturnInfo::MoveEligible;
 

diff  --git a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp 
b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
index ed6bec97e0bf2..a85475ece7bf5 100644
--- a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
+++ b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
@@ -487,3 +487,29 @@ void test5() try {
 }
 
 } // namespace test_simpler_implicit_move
+
+namespace test_auto_variables {
+
+struct S {};
+
+template  struct range {
+  S *begin() const;
+  S *end() const;
+};
+
+template  S test_dependent_ranged_for() {
+  for (auto x : range())
+return x;
+  return S();
+}
+template S test_dependent_ranged_for();
+
+template  struct X {};
+
+template  X test_dependent_invalid_decl() {
+  auto x = X().foo(); // 

[clang] bac74a5 - [clang] NFC: remove trailing white spaces from some tests

2021-04-02 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-04-03T03:18:22+02:00
New Revision: bac74a50e99f3d014d6e5a67272fd3b20eeb7fed

URL: 
https://github.com/llvm/llvm-project/commit/bac74a50e99f3d014d6e5a67272fd3b20eeb7fed
DIFF: 
https://github.com/llvm/llvm-project/commit/bac74a50e99f3d014d6e5a67272fd3b20eeb7fed.diff

LOG: [clang] NFC: remove trailing white spaces from some tests

Differential Revision: https://reviews.llvm.org/D99826

Added: 


Modified: 
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp
clang/test/CXX/special/class.copy/p33-0x.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/SemaCXX/conversion-function.cpp
clang/test/SemaCXX/cxx1y-deduced-return-type.cpp

Removed: 




diff  --git a/clang/test/CXX/drs/dr3xx.cpp b/clang/test/CXX/drs/dr3xx.cpp
index 5eb6e05126295..239a04c685d73 100644
--- a/clang/test/CXX/drs/dr3xx.cpp
+++ b/clang/test/CXX/drs/dr3xx.cpp
@@ -1103,7 +1103,7 @@ namespace dr384 { // dr384: yes
 }
 
 namespace dr385 { // dr385: yes
-  struct A { protected: void f(); }; 
+  struct A { protected: void f(); };
   struct B : A { using A::f; };
   struct C : A { void g(B b) { b.f(); } };
   void h(B b) { b.f(); }

diff  --git a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp
index f2b0e26e29f94..95ae7f7588088 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp
@@ -9,7 +9,7 @@ int  = [] (int r) -> decltype(auto) { return r; } (a); // 
expected-error {{can
 int  = [] (int r) -> decltype(auto) { return (r); } (a); // expected-warning 
{{reference to stack}}
 
 
-int test_explicit_auto_return() 
+int test_explicit_auto_return()
 {
 struct X {};
 auto L = [](auto F, auto a) { return F(a); };
@@ -18,32 +18,32 @@ int test_explicit_auto_return()
 auto MPtr = [](auto c) -> auto* { return  }; 
//expected-warning{{address of stack}}
 auto MDeclType = [](auto&& d) -> decltype(auto) { return 
static_cast(d); }; //OK
 M(3);
-
+
 auto & = MDeclType(X{});
 auto & = M(X{});
 auto & = MRef(X{});//expected-note{{in instantiation of}}
 auto & = MPtr(X{}); //expected-note{{in instantiation of}}
-return 0;
+return 0;
 }
 
-int test_implicit_auto_return() 
-{  
+int test_implicit_auto_return()
+{
   {
 auto M = [](auto a) { return a; };
 struct X {};
 X x = M(X{});
-
+
   }
 }
- 
+
 int test_multiple_returns()  {
-auto M = [](auto a) { 
+auto M = [](auto a) {
   bool k;
   if (k)
 return a;
   else
 return 5; //expected-error{{deduced as 'int' here}}
-}; 
+};
 M(3); // OK
 M('a'); //expected-note{{in instantiation of}}
   return 0;
@@ -60,7 +60,7 @@ int test_no_parameter_list()
 }
 
 int test_conditional_in_return() {
-  auto Fac = [](auto f, auto n) { 
+  auto Fac = [](auto f, auto n) {
 return n <= 0 ? n : f(f, n - 1) * n;
   };
   // FIXME: this test causes a recursive limit - need to error more gracefully.

diff  --git a/clang/test/CXX/special/class.copy/p33-0x.cpp 
b/clang/test/CXX/special/class.copy/p33-0x.cpp
index 28cd4f33a8aa6..ab6be4782e17d 100644
--- a/clang/test/CXX/special/class.copy/p33-0x.cpp
+++ b/clang/test/CXX/special/class.copy/p33-0x.cpp
@@ -22,7 +22,7 @@ void throw_move_only(X x) {
   throw x;
   throw x2;
 }
-  
+
 namespace PR10142 {
   struct X {
 X();

diff  --git a/clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp 
b/clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
index a41ea6b5e109e..10f4988ec5a73 100644
--- a/clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
+++ b/clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
@@ -1,15 +1,15 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-struct A { 
+struct A {
   template  operator T*();
-}; 
+};
 
 template  A::operator T*() { return 0; }
 template <> A::operator char*(){ return 0; } // specialization
 template A::operator void*(); // explicit instantiation
 
-int main() { 
+int main() {
   A a;
-  int *ip; 
+  int *ip;
   ip = a.operator int*();
 }
 
@@ -33,7 +33,7 @@ namespace PR5742 {
 class Foo {
  public:
   template  operator T();
-  
+
   template 
   T As() {
 return this->operator T();
@@ -43,7 +43,7 @@ class Foo {
   T As2() {
 return operator T();
   }
-  
+
   int AsInt() {
 return this->operator int();
   }
@@ -58,9 +58,9 @@ struct X0 {
 T x = 1; // expected-note{{variable 'x' declared const here}}
 x = 17; // expected-error{{cannot assign to variable 'x' with 
const-qualified type 'const int'}}
   }
-  
+
   template operator T*() const; // expected-note{{explicit 
instantiation refers here}}
-  
+
   template operator const T*() const {
 T x = T();
 return x; // expected-error{{cannot initialize return object of type 
'const char *' with an lvalue of type 'char'}} \

diff  --git 

[clang] 3ad6dd5 - [clang] Use decltype((E)) for compound requirement type constraint

2021-03-30 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-03-30T22:00:33+02:00
New Revision: 3ad6dd5d8f0a70756f665e8179ad7c5210022c11

URL: 
https://github.com/llvm/llvm-project/commit/3ad6dd5d8f0a70756f665e8179ad7c5210022c11
DIFF: 
https://github.com/llvm/llvm-project/commit/3ad6dd5d8f0a70756f665e8179ad7c5210022c11.diff

LOG: [clang] Use decltype((E)) for compound requirement type constraint

See PR45088.

Compound requirement type constraints were using decltype(E) instead of
decltype((E)), as per `[expr.prim.req]p1.3.3`.

Since neither instantiation nor type dependence should matter for
the constraints, this uses an approach where a `decltype` type is not built,
and just the canonical type of the expression after template instantiation
is used on the requirement.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D98160

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index efabc78b45ba9..8e1bc3f2dbdab 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2293,6 +2293,7 @@ class Sema final {
  const CXXScopeSpec , QualType T,
  TagDecl *OwnedTagDecl = nullptr);
 
+  QualType getDecltypeForParenthesizedExpr(Expr *E);
   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
   /// If AsUnevaluated is false, E is treated as though it were an evaluated
   /// context, such as when building a type for decltype(auto).

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 1ff7b1cdd5155..592bf5633ea5f 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -439,18 +439,19 @@ static void diagnoseUnsatisfiedRequirement(Sema ,
 case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
   ConceptSpecializationExpr *ConstraintExpr =
   Req->getReturnTypeRequirementSubstitutedConstraintExpr();
-  if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1)
+  if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
 // A simple case - expr type is the type being constrained and the 
concept
 // was not provided arguments.
-S.Diag(ConstraintExpr->getBeginLoc(),
+Expr *e = Req->getExpr();
+S.Diag(e->getBeginLoc(),
diag::note_expr_requirement_constraints_not_satisfied_simple)
-<< (int)First << S.BuildDecltypeType(Req->getExpr(),
- Req->getExpr()->getBeginLoc())
+<< (int)First << S.getDecltypeForParenthesizedExpr(e)
 << ConstraintExpr->getNamedConcept();
-  else
+  } else {
 S.Diag(ConstraintExpr->getBeginLoc(),
diag::note_expr_requirement_constraints_not_satisfied)
 << (int)First << ConstraintExpr;
+  }
   S.DiagnoseUnsatisfiedConstraint(ConstraintExpr->getSatisfaction());
   break;
 }

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 720e7b81c6378..4a4c8116d6f13 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -8663,7 +8663,7 @@ Sema::BuildExprRequirement(
 TemplateParameterList *TPL =
 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
 QualType MatchedType =
-BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
+getDecltypeForParenthesizedExpr(E).getCanonicalType();
 llvm::SmallVector Args;
 Args.push_back(TemplateArgument(MatchedType));
 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 97971b3009817..ed0480ec2ac3c 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8830,6 +8830,29 @@ QualType Sema::BuildTypeofExprType(Expr *E, 
SourceLocation Loc) {
   return Context.getTypeOfExprType(E);
 }
 
+/// getDecltypeForParenthesizedExpr - Given an expr, will return the type for
+/// that expression, as in [dcl.type.simple]p4 but without taking 
id-expressions
+/// and class member access into account.
+QualType Sema::getDecltypeForParenthesizedExpr(Expr *E) {
+  // C++11 [dcl.type.simple]p4:
+  //   [...]
+  QualType T = E->getType();
+  switch (E->getValueKind()) {
+  // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
+  //   type of e;
+  case VK_XValue:
+return Context.getRValueReferenceType(T);
+  // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
+  //   type of e;
+  case VK_LValue:
+return 

[clang] d4a8c73 - [clang] Fix ICE on invalid type parameters for concepts

2021-03-12 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-03-13T01:23:02+01:00
New Revision: d4a8c7359b57bafc7bfa2a9dea30017fb0153c1a

URL: 
https://github.com/llvm/llvm-project/commit/d4a8c7359b57bafc7bfa2a9dea30017fb0153c1a
DIFF: 
https://github.com/llvm/llvm-project/commit/d4a8c7359b57bafc7bfa2a9dea30017fb0153c1a.diff

LOG: [clang] Fix ICE on invalid type parameters for concepts

See PR48593.

Constraints with invalid type parameters were causing a null pointer
dereference.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D98095

Added: 


Modified: 
clang/lib/Sema/SemaType.cpp
clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 5f5b0361eab5..ffd431608b82 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -1256,25 +1256,6 @@ getImageAccess(const ParsedAttributesView ) {
   return OpenCLAccessAttr::Keyword_read_only;
 }
 
-static QualType ConvertConstrainedAutoDeclSpecToType(Sema , DeclSpec ,
- AutoTypeKeyword AutoKW) {
-  assert(DS.isConstrainedAuto());
-  TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
-  TemplateArgumentListInfo TemplateArgsInfo;
-  TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
-  TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
-  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
- TemplateId->NumArgs);
-  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
-  llvm::SmallVector TemplateArgs;
-  for (auto  : TemplateArgsInfo.arguments())
-TemplateArgs.push_back(ArgLoc.getArgument());
-  return S.Context.getAutoType(
-  QualType(), AutoKW, false, /*IsPack=*/false,
-  cast(TemplateId->Template.get().getAsTemplateDecl()),
-  TemplateArgs);
-}
-
 /// Convert the specified declspec to the appropriate type
 /// object.
 /// \param state Specifies the declarator containing the declaration specifier
@@ -1655,29 +1636,39 @@ static QualType 
ConvertDeclSpecToType(TypeProcessingState ) {
 break;
 
   case DeclSpec::TST_auto:
+  case DeclSpec::TST_decltype_auto: {
+auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
+  ? AutoTypeKeyword::DecltypeAuto
+  : AutoTypeKeyword::Auto;
+
+ConceptDecl *TypeConstraintConcept = nullptr;
+llvm::SmallVector TemplateArgs;
 if (DS.isConstrainedAuto()) {
-  Result = ConvertConstrainedAutoDeclSpecToType(S, DS,
-AutoTypeKeyword::Auto);
-  break;
+  if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
+TypeConstraintConcept =
+cast(TemplateId->Template.get().getAsTemplateDecl());
+TemplateArgumentListInfo TemplateArgsInfo;
+TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
+TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
+ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
+   TemplateId->NumArgs);
+S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
+for (const auto  : TemplateArgsInfo.arguments())
+  TemplateArgs.push_back(ArgLoc.getArgument());
+  } else {
+declarator.setInvalidType(true);
+  }
 }
-Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
+Result = S.Context.getAutoType(QualType(), AutoKW,
+   /*IsDependent*/ false, /*IsPack=*/false,
+   TypeConstraintConcept, TemplateArgs);
 break;
+  }
 
   case DeclSpec::TST_auto_type:
 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, 
false);
 break;
 
-  case DeclSpec::TST_decltype_auto:
-if (DS.isConstrainedAuto()) {
-  Result =
-  ConvertConstrainedAutoDeclSpecToType(S, DS,
-   AutoTypeKeyword::DecltypeAuto);
-  break;
-}
-Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
- /*IsDependent*/ false);
-break;
-
   case DeclSpec::TST_unknown_anytype:
 Result = Context.UnknownAnyTy;
 break;
@@ -5962,6 +5953,8 @@ namespace {
   if (!DS.isConstrainedAuto())
 return;
   TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
+  if (!TemplateId)
+return;
   if (DS.getTypeSpecScope().isNotEmpty())
 TL.setNestedNameSpecifierLoc(
 DS.getTypeSpecScope().getWithLocInContext(Context));

diff  --git a/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp 
b/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp
index 44539bd125ff..7830d1f43526 100644
--- 

[clang] c9fd92d - [clang] Improve diagnostics on implicitly deleted defaulted comparisons

2021-03-12 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-03-13T01:13:52+01:00
New Revision: c9fd92d573988c59b7a613f07909596cdad36095

URL: 
https://github.com/llvm/llvm-project/commit/c9fd92d573988c59b7a613f07909596cdad36095
DIFF: 
https://github.com/llvm/llvm-project/commit/c9fd92d573988c59b7a613f07909596cdad36095.diff

LOG: [clang] Improve diagnostics on implicitly deleted defaulted comparisons

This patch just makes the error message clearer by reinforcing the cause
was a lack of viable **three-way** comparison function for the
**complete object**.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D97990

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
clang/test/CXX/class/class.compare/class.eq/p2.cpp
clang/test/CXX/class/class.compare/class.spaceship/p1.cpp
clang/test/CXX/class/class.compare/class.spaceship/p2.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d4578c5263a0..8e037260288f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8979,8 +8979,8 @@ def note_defaulted_comparison_calls_deleted : Note<
   "defaulted %0 is implicitly deleted because it would invoke a deleted "
   "comparison function%select{| for member %2| for base class %2}1">;
 def note_defaulted_comparison_no_viable_function : Note<
-  "defaulted %0 is implicitly deleted because there is no viable comparison "
-  "function%select{| for member %2| for base class %2}1">;
+  "defaulted %0 is implicitly deleted because there is no viable three-way "
+  "comparison function for%select{| member| base class}1 %2">;
 def note_defaulted_comparison_no_viable_function_synthesized : Note<
   "three-way comparison cannot be synthesized because there is no viable "
   "function for %select{'=='|'<'}0 comparison">;

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 940ef796ce5e..0365d77cfc4e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7632,7 +7632,7 @@ class DefaultedComparisonAnalyzer
 
 private:
   Subobject getCompleteObject() {
-return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
+return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
   }
 
   Subobject getBase(CXXBaseSpecifier *Base) {

diff  --git a/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp 
b/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
index 1a0ccc91741b..dd622988d458 100644
--- a/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
+++ b/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
@@ -127,7 +127,7 @@ namespace P1946 {
 friend bool operator==(A &, A &); // expected-note {{would lose const 
qualifier}}
   };
   struct B {
-A a; // expected-note {{no viable comparison}}
+A a; // expected-note {{no viable three-way comparison}}
 friend bool operator==(B, B) = default; // ok
 friend bool operator==(const B&, const B&) = default; // expected-warning 
{{deleted}}
   };

diff  --git a/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp 
b/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
index 226245ce8a44..a1653d85abbf 100644
--- a/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
+++ b/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
@@ -44,7 +44,7 @@ struct A3 {
 
   bool operator==(const A3 &) const = default; // expected-warning 
{{implicitly deleted}}
   bool operator<(const A3 &) const = default;  // expected-warning 
{{implicitly deleted}}
-  // expected-note@-1 {{because there is no viable comparison function}}
+  // expected-note@-1 {{because there is no viable three-way comparison 
function for 'A3'}}
 };
 
 struct B1 {

diff  --git a/clang/test/CXX/class/class.compare/class.compare.default/p4.cpp 
b/clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
index 8c303c63d899..02adf3d51ded 100644
--- a/clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
+++ b/clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
@@ -99,7 +99,7 @@ namespace DeleteAfterFirstDecl {
   struct Q {
 struct X {
   friend std::strong_ordering operator<=>(const X&, const X&);
-} x; // expected-note {{no viable comparison}}
+} x; // expected-note {{no viable three-way comparison}}
 // expected-error@+1 {{defaulting the corresponding implicit 'operator==' 
for this defaulted 'operator<=>' would delete it after its first declaration}}
 friend 

[clang] 1819222 - [clang] tests: cleanup, update and add some new ones

2021-04-09 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-04-09T17:24:08+02:00
New Revision: 18192228602c6a8093fb0eefa863ab854dd03e59

URL: 
https://github.com/llvm/llvm-project/commit/18192228602c6a8093fb0eefa863ab854dd03e59
DIFF: 
https://github.com/llvm/llvm-project/commit/18192228602c6a8093fb0eefa863ab854dd03e59.diff

LOG: [clang] tests: cleanup, update and add some new ones

This reworks a small set of tests, as preparatory work for implementing
P2266.
* Run for more standard versions, including c++2b.
* Normalize file names and run commands.
* Adds some extra tests.

New Coroutine tests taken from Aaron Puchert's D68845.

Signed-off-by: Matheus Izvekov 

Reviewed By: thakis

Differential Revision: https://reviews.llvm.org/D99225

Added: 
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p7-cxx14.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
clang/test/CXX/special/class.copy/p3-cxx11.cpp
clang/test/CodeGen/nrvo-tracking.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp

Modified: 
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/CXX/drs/dr3xx.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/SemaCXX/P1155.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/conversion-function.cpp
clang/test/SemaCXX/coroutine-rvo.cpp
clang/test/SemaCXX/coroutines.cpp
clang/test/SemaCXX/return-stack-addr.cpp
clang/test/SemaCXX/warn-return-std-move.cpp

Removed: 
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p7-1y.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-1y.cpp
clang/test/CXX/special/class.copy/p33-0x.cpp
clang/test/SemaCXX/constant-expression-cxx1y.cpp
clang/test/SemaCXX/cxx1y-deduced-return-type.cpp



diff  --git a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp 
b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
index e4056221b4f3c..9d1d7d9a0d8bd 100644
--- a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
+++ b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx20 %s
-// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_14_17 %s
-// RUN: %clang_cc1 -std=c++14 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_14_17 %s
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_14_17 %s
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx20_2b %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx20_2b %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_17 %s
+// RUN: %clang_cc1 -std=c++14 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_17 %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fcxx-exceptions 
-verify=expected,cxx11_17 %s
 
 namespace test_delete_function {
 struct A1 {
@@ -54,38 +55,38 @@ B2 test4() {
 namespace test_implicitly_movable_rvalue_ref {
 struct A1 {
   A1(A1 &&);
-  A1(const A1 &) = delete; // cxx11_14_17-note {{'A1' has been explicitly 
marked deleted here}}
+  A1(const A1 &) = delete; // cxx11_17-note {{'A1' has been explicitly marked 
deleted here}}
 };
 A1 test1(A1 &) {
-  return a; // cxx11_14_17-error {{call to deleted constructor of 
'test_implicitly_movable_rvalue_ref::A1'}}
+  return a; // cxx11_17-error {{call to deleted constructor of 
'test_implicitly_movable_rvalue_ref::A1'}}
 }
 
 struct A2 {
   A2(A2 &&);
 
 private:
-  A2(const A2 &); // cxx11_14_17-note {{declared private here}}
+  A2(const A2 &); // cxx11_17-note {{declared private here}}
 };
 A2 test2(A2 &) {
-  return a; // cxx11_14_17-error {{calling a private constructor of class 
'test_implicitly_movable_rvalue_ref::A2'}}
+  return a; // cxx11_17-error {{calling a private constructor of class 
'test_implicitly_movable_rvalue_ref::A2'}}
 }
 
 struct B1 {
   B1(const B1 &);
-  B1(B1 &&) = delete; // cxx20-note {{'B1' has been explicitly marked deleted 
here}}
+  B1(B1 &&) = delete; // cxx20_2b-note {{'B1' has been explicitly marked 
deleted here}}
 };
 B1 test3(B1 &) {
-  return b; // cxx20-error {{call to deleted constructor of 
'test_implicitly_movable_rvalue_ref::B1'}}
+  return b; // cxx20_2b-error {{call to deleted constructor of 
'test_implicitly_movable_rvalue_ref::B1'}}
 }
 
 struct B2 {
   B2(const B2 &);
 
 private:
-  B2(B2 &&); // cxx20-note {{declared private here}}
+  B2(B2 &&); // cxx20_2b-note {{declared private here}}
 };
 B2 test4(B2 &) {
-  return b; // cxx20-error {{calling a private constructor of class 
'test_implicitly_movable_rvalue_ref::B2'}}
+  return b; // cxx20_2b-error {{calling a private constructor of class 
'test_implicitly_movable_rvalue_ref::B2'}}
 }
 } // namespace test_implicitly_movable_rvalue_ref
 
@@ 

[clang] d98c34f - [clang] fix error recovery ICE on copy elision when returing invalid variable

2021-09-03 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-03T20:34:08+02:00
New Revision: d98c34f4d7950f531661ba3f498222ccf6239a0f

URL: 
https://github.com/llvm/llvm-project/commit/d98c34f4d7950f531661ba3f498222ccf6239a0f
DIFF: 
https://github.com/llvm/llvm-project/commit/d98c34f4d7950f531661ba3f498222ccf6239a0f.diff

LOG: [clang] fix error recovery ICE on copy elision when returing invalid 
variable

See PR51708.

Attempting copy elision in dependent contexts with invalid variable,
such as a variable with incomplete type, would cause a crash when attempting
to calculate it's alignment.

The fix is to just skip this optimization on invalid VarDecl, as otherwise this
provides no benefit to error recovery: This functionality does not try to
diagnose anything, it only calculates a flag which will affect where the
variable will be allocated during codegen.

Signed-off-by: Matheus Izvekov 

Reviewed By: rtrieu

Differential Revision: https://reviews.llvm.org/D109191

Added: 


Modified: 
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index d33c2545b4844..54ba12e0e644f 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1087,7 +1087,7 @@ Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
 
   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  StartingScope, InstantiatingVarTemplate);
-  if (D->isNRVOVariable()) {
+  if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
 QualType RT;
 if (auto *F = dyn_cast(DC))
   RT = F->getReturnType();

diff  --git a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp 
b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
index cd981264c9b69..7055acad6ccf9 100644
--- a/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
+++ b/clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
@@ -518,3 +518,37 @@ template  X test_dependent_invalid_decl() {
 template X test_dependent_invalid_decl(); // expected-note 
{{requested here}}
 
 } // namespace test_auto_variables
+
+namespace PR51708 {
+
+class a1;  // expected-note 4 {{forward declaration of 
'PR51708::a1'}}
+template  class A2; // expected-note 4 {{template is declared here}}
+using a2 = A2;
+
+template  b f() {
+  // expected-error@-1 {{incomplete result type 'PR51708::a1' in function 
definition}}
+  // expected-error@-2 {{implicit instantiation of undefined template 
'PR51708::A2}}
+
+  b d;
+  // expected-error@-1 {{variable has incomplete type 'PR51708::a1'}}
+  // expected-error@-2 {{implicit instantiation of undefined template 
'PR51708::A2}}
+
+  return d;
+}
+template a1 f(); // expected-note-re {{in instantiation {{.*}} requested 
here}}
+template a2 f(); // expected-note-re {{in instantiation {{.*}} requested 
here}}
+
+template  b g() {
+  // expected-error@-1 {{incomplete result type 'PR51708::a1' in function 
definition}}
+  // expected-error@-2 {{implicit instantiation of undefined template 
'PR51708::A2}}
+
+  b d __attribute__((aligned(1)));
+  // expected-error@-1 {{variable has incomplete type 'PR51708::a1'}}
+  // expected-error@-2 {{implicit instantiation of undefined template 
'PR51708::A2}}
+
+  return d;
+}
+template a1 g(); // expected-note-re {{in instantiation {{.*}} requested 
here}}
+template a2 g(); // expected-note-re {{in instantiation {{.*}} requested 
here}}
+
+} // namespace PR51708



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2d6829b - [clang] disable implicit moves when not in CPlusPLus

2021-09-14 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-14T11:29:47+02:00
New Revision: 2d6829bbbe6877920d9be1db93b9f3fc85b43d10

URL: 
https://github.com/llvm/llvm-project/commit/2d6829bbbe6877920d9be1db93b9f3fc85b43d10
DIFF: 
https://github.com/llvm/llvm-project/commit/2d6829bbbe6877920d9be1db93b9f3fc85b43d10.diff

LOG: [clang] disable implicit moves when not in CPlusPLus

See PR51842.

This fixes an assert firing in the static analyzer, triggered by implicit moves
in blocks in C mode:

This also simplifies the AST a little bit when compiling non C++ code,
as the xvalue implicit casts are not inserted.

We keep and test that the nrvo flag is still being set on the VarDecls,
as that is still a bit beneficial while not really making anything
more complicated.

Signed-off-by: Matheus Izvekov 

Reviewed By: NoQ

Differential Revision: https://reviews.llvm.org/D109654

Added: 
clang/test/AST/nrvo.c
clang/test/Analysis/blocks-nrvo.c

Modified: 
clang/lib/Sema/SemaStmt.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index dc93e9e1c51c5..813925460241e 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3481,7 +3481,8 @@ VerifyInitializationSequenceCXX98(const Sema ,
 ExprResult Sema::PerformMoveOrCopyInitialization(
 const InitializedEntity , const NamedReturnInfo , Expr 
*Value,
 bool SupressSimplerImplicitMoves) {
-  if ((!getLangOpts().CPlusPlus2b || SupressSimplerImplicitMoves) &&
+  if (getLangOpts().CPlusPlus &&
+  (!getLangOpts().CPlusPlus2b || SupressSimplerImplicitMoves) &&
   NRInfo.isMoveEligible()) {
 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
   CK_NoOp, Value, VK_XValue, FPOptionsOverride());

diff  --git a/clang/test/AST/nrvo.c b/clang/test/AST/nrvo.c
new file mode 100644
index 0..4f50d6a1e384b
--- /dev/null
+++ b/clang/test/AST/nrvo.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -ast-dump -fblocks %s | FileCheck -strict-whitespace %s
+
+struct A {};
+
+struct A f1() {
+  // CHECK:  FunctionDecl 0x{{[^ ]*}}  line:[[@LINE-1]]:10 f1 'struct A ()'
+  // CHECK-NEXT: CompoundStmt 0x{{[^ ]*}} 
+  struct A a;
+  // CHECK-NEXT: DeclStmt 0x{{[^ ]*}} 
+  // CHECK-NEXT: VarDecl 0x{{[^ ]*}}  col:12 used a 'struct 
A':'struct A' nrvo
+  return a;
+  // CHECK-NEXT: ReturnStmt 0x{{[^ ]*}} 
+  // CHECK-NEXT: ImplicitCastExpr 0x{{[^ ]*}}  'struct A':'struct A' 

+  // CHECK-NEXT: DeclRefExpr 0x{{[^ ]*}}  'struct A':'struct A' lvalue 
Var 0x{{[^ ]*}} 'a' 'struct A':'struct A'
+}
+
+void f2() {
+  (void)^{
+// CHECK:  BlockDecl 0x{{[^ ]*}}  line:[[@LINE-1]]:9
+// CHECK-NEXT: CompoundStmt 0x{{[^ ]*}} 
+struct A a;
+// CHECK-NEXT: DeclStmt 0x{{[^ ]*}} 
+// CHECK-NEXT: VarDecl 0x{{[^ ]*}}  col:14 used a 'struct 
A':'struct A' nrvo
+return a;
+// CHECK-NEXT: ReturnStmt 0x{{[^ ]*}} 
+// CHECK-NEXT: ImplicitCastExpr 0x{{[^ ]*}}  'struct A':'struct A' 

+// CHECK-NEXT: DeclRefExpr 0x{{[^ ]*}}  'struct A':'struct A' 
lvalue Var 0x{{[^ ]*}} 'a' 'struct A':'struct A'
+  }();
+}

diff  --git a/clang/test/Analysis/blocks-nrvo.c 
b/clang/test/Analysis/blocks-nrvo.c
new file mode 100644
index 0..bb0be869ee767
--- /dev/null
+++ b/clang/test/Analysis/blocks-nrvo.c
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -fblocks -verify %s
+
+// expected-no-diagnostics
+
+typedef struct {
+  int x;
+} S;
+
+void foo() {
+  ^{
+S s;
+return s; // no-crash
+  };
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 68b9d8e - [clang] fix transformation of template arguments of 'auto' type constraints

2021-09-07 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-08T03:22:34+02:00
New Revision: 68b9d8ed7abe4046992ae1557990edfbb3a772bc

URL: 
https://github.com/llvm/llvm-project/commit/68b9d8ed7abe4046992ae1557990edfbb3a772bc
DIFF: 
https://github.com/llvm/llvm-project/commit/68b9d8ed7abe4046992ae1557990edfbb3a772bc.diff

LOG: [clang] fix transformation of template arguments of 'auto' type constraints

See PR48617.

When assigning the new template arguments to the new TypeLoc, we were looping
on the argument count of the original TypeLoc instead of the new one,
which can be different when packs are present.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D109406

Added: 


Modified: 
clang/lib/Sema/TreeTransform.h
clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp

Removed: 




diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 8841b2e00d40f..2a7ceaf6425ee 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -6578,7 +6578,7 @@ QualType 
TreeTransform::TransformAutoType(TypeLocBuilder ,
   NewTL.setFoundDecl(TL.getFoundDecl());
   NewTL.setLAngleLoc(TL.getLAngleLoc());
   NewTL.setRAngleLoc(TL.getRAngleLoc());
-  for (unsigned I = 0; I < TL.getNumArgs(); ++I)
+  for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
 
   return Result;

diff  --git a/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp 
b/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp
index 7830d1f435262..4941027423217 100644
--- a/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp
+++ b/clang/test/CXX/dcl/dcl.spec/dcl.type/dcl.spec.auto/p6.cpp
@@ -76,3 +76,25 @@ namespace PR48593 {
   template concept d = true;
   d<,> auto e = 0; // expected-error{{expected expression}}
 }
+
+namespace PR48617 {
+  template  concept C = true;
+  template  class A {};
+
+  template  C auto e(A) { return 0; }
+
+  // FIXME: The error here does not make sense.
+  template auto e<>(A<>);
+  // expected-error@-1 {{explicit instantiation of 'e' does not refer to a 
function template}}
+  // expected-note@-5  {{candidate template ignored: failed template argument 
deduction}}
+
+  // FIXME: Should be able to instantiate this with no errors.
+  template C auto e(A);
+  // expected-error@-1 {{explicit instantiation of 'e' does not refer to a 
function template}}
+  // expected-note@-10 {{candidate template ignored: could not match 'C auto' against 'C auto'}}
+  
+  template C<> auto e<>(A<>);
+
+  template  A c(Ts...);
+  int f = e(c(1, 2));
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 03282f2 - [clang] C++98 implicit moves are back with a vengeance

2021-07-13 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-13T19:16:49+02:00
New Revision: 03282f2fe14e9dd61aaeeda3785f56c7ccb4f3c9

URL: 
https://github.com/llvm/llvm-project/commit/03282f2fe14e9dd61aaeeda3785f56c7ccb4f3c9
DIFF: 
https://github.com/llvm/llvm-project/commit/03282f2fe14e9dd61aaeeda3785f56c7ccb4f3c9.diff

LOG: [clang] C++98 implicit moves are back with a vengeance

After taking C++98 implicit moves out in D104500,
we put it back in, but now in a new form which preserves
compatibility with pure C++98 programs, while at the same time
giving almost all the goodies from P1825.

* We use the exact same rules as C++20 with regards to which
  id-expressions are move eligible. The previous
  incarnation would only benefit from the proper subset which is
  copy ellidable. This means we can implicit move, in addition:
  * Parameters.
  * RValue references.
  * Exception variables.
  * Variables with higher-than-natural required alignment.
  * Objects with different type from the function return type.
* We preserve the two-overload resolution, with one small tweak to the
  first one: If we either pick a (possibly converting) constructor which
  does not take an rvalue reference, or a user conversion operator which
  is not ref-qualified, we abort into the second overload resolution.

This gives C++98 almost all the implicit move patterns which we had created test
cases for, while at the same time preserving the meaning of these
three patterns, which are found in pure C++98 programs:
* Classes with both const and non-const copy constructors, but no move
  constructors, continue to have their non-const copy constructor
  selected.
* We continue to reject as ambiguous the following pattern:
```
struct A { A(B &); };
struct B { operator A(); };
A foo(B x) { return x; }
```
* We continue to pick the copy constructor in the following pattern:
```
class AutoPtrRef { };
struct AutoPtr {
  AutoPtr(AutoPtr &);
  AutoPtr();

  AutoPtr(AutoPtrRef);
  operator AutoPtrRef();
};
AutoPtr test_auto_ptr() {
  AutoPtr p;
  return p;
}
```

Signed-off-by: Matheus Izvekov 

Reviewed By: Quuxplusone

Differential Revision: https://reviews.llvm.org/D105756

Added: 


Modified: 
clang/lib/Sema/SemaStmt.cpp
clang/test/CXX/class/class.init/class.copy.elision/p3.cpp
clang/test/SemaCXX/conversion-function.cpp
clang/test/SemaObjCXX/block-capture.mm

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index fa798c2d557ca..643dde437fc94 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3451,6 +3451,28 @@ const VarDecl 
*Sema::getCopyElisionCandidate(NamedReturnInfo ,
   return Info.isCopyElidable() ? Info.Candidate : nullptr;
 }
 
+/// Verify that the initialization sequence that was picked for the
+/// first overload resolution is permissible under C++98.
+///
+/// Reject (possibly converting) contructors not taking an rvalue reference,
+/// or user conversion operators which are not ref-qualified.
+static bool
+VerifyInitializationSequenceCXX98(const Sema ,
+  const InitializationSequence ) {
+  const auto *Step = llvm::find_if(Seq.steps(), [](const auto ) {
+return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
+   Step.Kind == InitializationSequence::SK_UserConversion;
+  });
+  if (Step != Seq.step_end()) {
+const auto *FD = Step->Function.Function;
+if (isa(FD)
+? !FD->getParamDecl(0)->getType()->isRValueReferenceType()
+: cast(FD)->getRefQualifier() == RQ_None)
+  return false;
+  }
+  return true;
+}
+
 /// Perform the initialization of a potentially-movable value, which
 /// is the result of return value.
 ///
@@ -3461,8 +3483,7 @@ ExprResult
 Sema::PerformMoveOrCopyInitialization(const InitializedEntity ,
   const NamedReturnInfo ,
   Expr *Value) {
-  if (getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus2b &&
-  NRInfo.isMoveEligible()) {
+  if (!getLangOpts().CPlusPlus2b && NRInfo.isMoveEligible()) {
 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
   CK_NoOp, Value, VK_XValue, FPOptionsOverride());
 Expr *InitExpr = 
@@ -3470,7 +3491,9 @@ Sema::PerformMoveOrCopyInitialization(const 
InitializedEntity ,
Value->getBeginLoc());
 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
 auto Res = Seq.getFailedOverloadResult();
-if (Res == OR_Success || Res == OR_Deleted) {
+if ((Res == OR_Success || Res == OR_Deleted) &&
+(getLangOpts().CPlusPlus11 ||
+ VerifyInitializationSequenceCXX98(*this, Seq))) {
   // Promote "AsRvalue" to the heap, since we now need this
   // expression node to persist.
   Value =

diff  --git 

[clang] 219790c - [clang] fix canonicalization of nested name specifiers

2021-08-03 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-08-03T22:39:48+02:00
New Revision: 219790c1f53665a8b5f7578472e5c2675f9bec6a

URL: 
https://github.com/llvm/llvm-project/commit/219790c1f53665a8b5f7578472e5c2675f9bec6a
DIFF: 
https://github.com/llvm/llvm-project/commit/219790c1f53665a8b5f7578472e5c2675f9bec6a.diff

LOG: [clang] fix canonicalization of nested name specifiers

See PR47174.

When canonicalizing nested name specifiers of the type kind,
the prefix for 'DependentTemplateSpecialization' types was being
dropped, leading to malformed types which would cause failures
when rebuilding template names.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D107311

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTContext.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 07b7e61821f7..854070aee428 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7830,8 +7830,7 @@ class Sema final {
  TemplateArgumentLoc ,
SmallVectorImpl );
 
-  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
- TypeSourceInfo *Arg);
+  bool CheckTemplateArgument(TypeSourceInfo *Arg);
   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument ,

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 4c16ddc782fa..4ff2aa5307bb 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -6089,9 +6089,11 @@ 
ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
 NNS->getAsNamespaceAlias()->getNamespace()
   
->getOriginalNamespace());
 
+  // The 
diff erence between TypeSpec and TypeSpecWithTemplate is that the
+  // latter will have the 'template' keyword when printed.
   case NestedNameSpecifier::TypeSpec:
   case NestedNameSpecifier::TypeSpecWithTemplate: {
-QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
+const Type *T = getCanonicalType(NNS->getAsType());
 
 // If we have some kind of dependent-named type (e.g., "typename T::type"),
 // break it apart into its prefix and identifier, then reconsititute those
@@ -6101,14 +6103,16 @@ 
ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
 //   typedef typename T::type T1;
 //   typedef typename T1::type T2;
 if (const auto *DNT = T->getAs())
-  return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
-   const_cast(DNT->getIdentifier()));
-
-// Otherwise, just canonicalize the type, and force it to be a TypeSpec.
-// FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
-// first place?
+  return NestedNameSpecifier::Create(
+  *this, DNT->getQualifier(),
+  const_cast(DNT->getIdentifier()));
+if (const auto *DTST = T->getAs())
+  return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
+ const_cast(T));
+
+// TODO: Set 'Template' parameter to true for other template types.
 return NestedNameSpecifier::Create(*this, nullptr, false,
-   const_cast(T.getTypePtr()));
+   const_cast(T));
   }
 
   case NestedNameSpecifier::Global:

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 72b277821978..708b5cd8cb76 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -12472,6 +12472,8 @@ bool Sema::CheckUsingDeclRedeclaration(SourceLocation 
UsingLoc,
 return false;
   }
 
+  const NestedNameSpecifier *CNNS =
+  Context.getCanonicalNestedNameSpecifier(Qual);
   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
 NamedDecl *D = *I;
 
@@ -12497,8 +12499,7 @@ bool Sema::CheckUsingDeclRedeclaration(SourceLocation 
UsingLoc,
 // using decls 
diff er if they name 
diff erent scopes (but note that
 // template instantiation can cause this check to trigger when it
 // didn't before instantiation).
-if (Context.getCanonicalNestedNameSpecifier(Qual) !=
-Context.getCanonicalNestedNameSpecifier(DQual))
+if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
   continue;
 
 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 

[clang] e64e692 - [clang] fix crash on template instantiation of invalid requires expressions

2021-08-03 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-08-03T23:16:04+02:00
New Revision: e64e6924b8aef8d48117beb6e87162109ac2512c

URL: 
https://github.com/llvm/llvm-project/commit/e64e6924b8aef8d48117beb6e87162109ac2512c
DIFF: 
https://github.com/llvm/llvm-project/commit/e64e6924b8aef8d48117beb6e87162109ac2512c.diff

LOG: [clang] fix crash on template instantiation of invalid requires expressions

See PR48656.

The implementation of the template instantiation of requires expressions
was incorrectly trying to get the expression from an 'ExprRequirement'
before checking if it was an error state.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D107399

Added: 


Modified: 
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp
clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index f18f77d3442a..74889aa3ca88 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1934,25 +1934,23 @@ 
TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
 return Req;
 
   Sema::SFINAETrap Trap(SemaRef);
-  TemplateDeductionInfo Info(Req->getExpr()->getBeginLoc());
 
   llvm::PointerUnion
   TransExpr;
   if (Req->isExprSubstitutionFailure())
 TransExpr = Req->getExprSubstitutionDiagnostic();
   else {
-Sema::InstantiatingTemplate ExprInst(SemaRef, 
Req->getExpr()->getBeginLoc(),
- Req, Info,
- Req->getExpr()->getSourceRange());
+Expr *E = Req->getExpr();
+TemplateDeductionInfo Info(E->getBeginLoc());
+Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
+ E->getSourceRange());
 if (ExprInst.isInvalid())
   return nullptr;
-ExprResult TransExprRes = TransformExpr(Req->getExpr());
+ExprResult TransExprRes = TransformExpr(E);
 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
-  TransExpr = createSubstDiag(SemaRef, Info,
-  [&] (llvm::raw_ostream& OS) {
-  Req->getExpr()->printPretty(OS, nullptr,
-  SemaRef.getPrintingPolicy());
-  });
+  TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream ) {
+E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
+  });
 else
   TransExpr = TransExprRes.get();
   }
@@ -1966,6 +1964,7 @@ 
TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
   else if (RetReq.isTypeConstraint()) {
 TemplateParameterList *OrigTPL =
 RetReq.getTypeConstraintTemplateParameterList();
+TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
 Req, Info, OrigTPL->getSourceRange());
 if (TPLInst.isInvalid())

diff  --git a/clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp
index 15cbe6637845..5433cfb21955 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp
@@ -192,3 +192,29 @@ namespace std_example {
   using c3 = C2_check; // expected-error{{constraints not satisfied 
for class template 'C2_check' [with T = std_example::has_inner]}}
   using c4 = C3_check; // expected-error{{constraints not satisfied for 
class template 'C3_check' [with T = void]}}
 }
+
+namespace PR48656 {
+
+template  concept C = requires { requires requires { T::a; }; };
+// expected-note@-1 {{because 'T::a' would be invalid: no member named 'a' in 
'PR48656::T1'}}
+
+template  struct A {};
+// expected-note@-1 {{because 'PR48656::T1' does not satisfy 'C'}}
+
+struct T1 {};
+template struct A; // expected-error {{constraints not satisfied for class 
template 'A' [with $0 = ]}}
+
+struct T2 { static constexpr bool a = false; };
+template struct A;
+
+template  struct T3 {
+  static void m(auto) requires requires { T::fail; } {}
+  // expected-note@-1 {{constraints not satisfied}}
+  // expected-note@-2 {{type 'int' cannot be used prior to '::'}}
+};
+template  void t3(Args... args) { (..., T3::m(args)); }
+// expected-error@-1 {{no matching function for call to 'm'}}
+
+template void t3(int); // expected-note {{requested here}}
+
+} // namespace PR48656

diff  --git a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp 
b/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
index 593902c6b74d..d80710937cdf 100644
--- a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
+++ 

[clang] 0c7cd4a - [clang] NFC: refactor multiple implementations of getDecltypeForParenthesizedExpr

2021-07-28 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-28T23:27:43+02:00
New Revision: 0c7cd4a873138f2116403a733274c8cb7dbf925f

URL: 
https://github.com/llvm/llvm-project/commit/0c7cd4a873138f2116403a733274c8cb7dbf925f
DIFF: 
https://github.com/llvm/llvm-project/commit/0c7cd4a873138f2116403a733274c8cb7dbf925f.diff

LOG: [clang] NFC: refactor multiple implementations of 
getDecltypeForParenthesizedExpr

This cleanup patch refactors a bunch of functional duplicates of
getDecltypeForParenthesizedExpr into a common implementation.

Signed-off-by: Matheus Izvekov 

Reviewed By: aaronpuchert

Differential Revision: https://reviews.llvm.org/D100713

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ExprObjC.cpp
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 34299581d89d4..da372e854700b 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1631,6 +1631,8 @@ class ASTContext : public RefCountedBase {
   QualType getTypeOfExprType(Expr *e) const;
   QualType getTypeOfType(QualType t) const;
 
+  QualType getReferenceQualifiedType(const Expr *e) const;
+
   /// C++11 decltype.
   QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
 

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 375b650b8ecb3..1a696b4938061 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2330,7 +2330,6 @@ class Sema final {
  const CXXScopeSpec , QualType T,
  TagDecl *OwnedTagDecl = nullptr);
 
-  QualType getDecltypeForParenthesizedExpr(Expr *E);
   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
   /// If AsUnevaluated is false, E is treated as though it were an evaluated
   /// context, such as when building a type for decltype(auto).

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index e102a3ba508d4..4c16ddc782fa9 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -5454,6 +5454,29 @@ QualType ASTContext::getTypeOfType(QualType tofType) 
const {
   return QualType(tot, 0);
 }
 
+/// getReferenceQualifiedType - Given an expr, will return the type for
+/// that expression, as in [dcl.type.simple]p4 but without taking 
id-expressions
+/// and class member access into account.
+QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
+  // C++11 [dcl.type.simple]p4:
+  //   [...]
+  QualType T = E->getType();
+  switch (E->getValueKind()) {
+  // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
+  //   type of e;
+  case VK_XValue:
+return getRValueReferenceType(T);
+  // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
+  //   type of e;
+  case VK_LValue:
+return getLValueReferenceType(T);
+  //  - otherwise, decltype(e) is the type of e.
+  case VK_PRValue:
+return T;
+  }
+  llvm_unreachable("Unknown value kind");
+}
+
 /// Unlike many "get" functions, we don't unique DecltypeType
 /// nodes. This would never be helpful, since each such type has its own
 /// expression, and would not give a significant memory saving, since there

diff  --git a/clang/lib/AST/ExprObjC.cpp b/clang/lib/AST/ExprObjC.cpp
index 7d932c8b059da..a3222c2da24fd 100644
--- a/clang/lib/AST/ExprObjC.cpp
+++ b/clang/lib/AST/ExprObjC.cpp
@@ -271,20 +271,7 @@ QualType ObjCMessageExpr::getCallReturnType(ASTContext 
) const {
 }
 return QT;
   }
-
-  // Expression type might be 
diff erent from an expected call return type,
-  // as expression type would never be a reference even if call returns a
-  // reference. Reconstruct the original expression type.
-  QualType QT = getType();
-  switch (getValueKind()) {
-  case VK_LValue:
-return Ctx.getLValueReferenceType(QT);
-  case VK_XValue:
-return Ctx.getRValueReferenceType(QT);
-  case VK_PRValue:
-return QT;
-  }
-  llvm_unreachable("Unsupported ExprValueKind");
+  return Ctx.getReferenceQualifiedType(this);
 }
 
 SourceRange ObjCMessageExpr::getReceiverRange() const {

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f2c70d0a56efb..30f0730671c0a 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -461,7 +461,7 @@ static void diagnoseUnsatisfiedRequirement(Sema ,
 Expr *e = Req->getExpr();
 S.Diag(e->getBeginLoc(),
diag::note_expr_requirement_constraints_not_satisfied_simple)
-<< (int)First << S.getDecltypeForParenthesizedExpr(e)
+<< (int)First << 

[clang] 87aa318 - [clang] fix concepts crash on substitution failure during normalization

2021-07-28 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-28T23:28:45+02:00
New Revision: 87aa31827b293127619e2ef96e80baf709eae338

URL: 
https://github.com/llvm/llvm-project/commit/87aa31827b293127619e2ef96e80baf709eae338
DIFF: 
https://github.com/llvm/llvm-project/commit/87aa31827b293127619e2ef96e80baf709eae338.diff

LOG: [clang] fix concepts crash on substitution failure during normalization

When substitution failed on the first constrained template argument (but
only the first), we would assert / crash. Checking for failure was only
being performed from the second constraint on.

This changes it so the checking is performed in that case,
and the code is also now simplified a little bit to hopefully
avoid this confusion.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D106907

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 30f0730671c0a..82443be09c062 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -742,22 +742,15 @@ Optional
 NormalizedConstraint::fromConstraintExprs(Sema , NamedDecl *D,
   ArrayRef E) {
   assert(E.size() != 0);
-  auto First = fromConstraintExpr(S, D, E[0]);
-  if (E.size() == 1)
-return First;
-  auto Second = fromConstraintExpr(S, D, E[1]);
-  if (!Second)
+  auto Conjunction = fromConstraintExpr(S, D, E[0]);
+  if (!Conjunction)
 return None;
-  llvm::Optional Conjunction;
-  Conjunction.emplace(S.Context, std::move(*First), std::move(*Second),
-  CCK_Conjunction);
-  for (unsigned I = 2; I < E.size(); ++I) {
+  for (unsigned I = 1; I < E.size(); ++I) {
 auto Next = fromConstraintExpr(S, D, E[I]);
 if (!Next)
-  return llvm::Optional{};
-NormalizedConstraint NewConjunction(S.Context, std::move(*Conjunction),
+  return None;
+*Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
 std::move(*Next), CCK_Conjunction);
-*Conjunction = std::move(NewConjunction);
   }
   return Conjunction;
 }

diff  --git a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp 
b/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
index 153d4a56bea31..2134968101470 100644
--- a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
+++ b/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
@@ -67,3 +67,18 @@ namespace non_type_pack {
 
   static_assert((foo<1>(), true));
 }
+
+namespace PR47174 {
+// This checks that we don't crash with a failed substitution on the first 
constrained argument when
+// performing normalization.
+template 
+requires true struct S3; // expected-note {{template is declared here}}
+template 
+requires true struct S3; // expected-error {{class template partial 
specialization is not more specialized than the primary template}}
+
+// Same as above, for the second position (but this was already working).
+template 
+requires true struct S4; // expected-note {{template is declared here}}
+template 
+requires true struct S4; // expected-error {{class template partial 
specialization is not more specialized than the primary template}}
+} // namespace PR47174



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d9308aa - [clang] don't mark as Elidable CXXConstruct expressions used in NRVO

2021-09-21 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-21T21:41:20+02:00
New Revision: d9308aa39b236064a680ca57178af3c731e13e49

URL: 
https://github.com/llvm/llvm-project/commit/d9308aa39b236064a680ca57178af3c731e13e49
DIFF: 
https://github.com/llvm/llvm-project/commit/d9308aa39b236064a680ca57178af3c731e13e49.diff

LOG: [clang] don't mark as Elidable CXXConstruct expressions used in NRVO

See PR51862.

The consumers of the Elidable flag in CXXConstructExpr assume that
an elidable construction just goes through a single copy/move construction,
so that the source object is immediately passed as an argument and is the same
type as the parameter itself.

With the implementation of P2266 and after some adjustments to the
implementation of P1825, we started (correctly, as per standard)
allowing more cases where the copy initialization goes through
user defined conversions.

With this patch we stop using this flag in NRVO contexts, to preserve code
that relies on that assumption.
This causes no known functional changes, we just stop firing some asserts
in a cople of included test cases.

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D109800

Added: 
clang/test/CodeGenCXX/copy-elision.cpp

Modified: 
clang/include/clang/Sema/Initialization.h
clang/lib/AST/ExprConstant.cpp
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaObjCProperty.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/CodeGen/nrvo-tracking.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Initialization.h 
b/clang/include/clang/Sema/Initialization.h
index 4664861c4e32a..8c1856f208279 100644
--- a/clang/include/clang/Sema/Initialization.h
+++ b/clang/include/clang/Sema/Initialization.h
@@ -298,8 +298,8 @@ class alignas(8) InitializedEntity {
 
   /// Create the initialization entity for the result of a function.
   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
-QualType Type, bool NRVO) {
-return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
+QualType Type) {
+return InitializedEntity(EK_Result, ReturnLoc, Type);
   }
 
   static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc,
@@ -308,20 +308,20 @@ class alignas(8) InitializedEntity {
   }
 
   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
-   QualType Type, bool NRVO) {
-return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
+   QualType Type) {
+return InitializedEntity(EK_BlockElement, BlockVarLoc, Type);
   }
 
   static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
-   QualType Type, bool NRVO) {
+   QualType Type) {
 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
- BlockVarLoc, Type, NRVO);
+ BlockVarLoc, Type);
   }
 
   /// Create the initialization entity for an exception object.
   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
-   QualType Type, bool NRVO) {
-return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
+   QualType Type) {
+return InitializedEntity(EK_Exception, ThrowLoc, Type);
   }
 
   /// Create the initialization entity for an object allocated via new.

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 296e9e7e5995e..ea7818c43e321 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -9933,10 +9933,19 @@ bool RecordExprEvaluator::VisitCXXConstructExpr(const 
CXXConstructExpr *E,
 return false;
 
   // Avoid materializing a temporary for an elidable copy/move constructor.
-  if (E->isElidable() && !ZeroInit)
-if (const MaterializeTemporaryExpr *ME
-  = dyn_cast(E->getArg(0)))
+  if (E->isElidable() && !ZeroInit) {
+// FIXME: This only handles the simplest case, where the source object
+//is passed directly as the first argument to the constructor.
+//This should also handle stepping though implicit casts and
+//and conversion sequences which involve two steps, with a
+//conversion operator followed by a converting constructor.
+const Expr *SrcObj = E->getArg(0);
+assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
+assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
+if (const 

[clang] 37adc4f - [clang] set templates as invalid when any of the parameters are invalid

2021-09-24 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-25T04:04:47+02:00
New Revision: 37adc4f957c2383a625e2e593ba1d18a25d92b91

URL: 
https://github.com/llvm/llvm-project/commit/37adc4f957c2383a625e2e593ba1d18a25d92b91
DIFF: 
https://github.com/llvm/llvm-project/commit/37adc4f957c2383a625e2e593ba1d18a25d92b91.diff

LOG: [clang] set templates as invalid when any of the parameters are invalid

See PR51872 for the original repro.

This fixes a crash when converting a templated constructor into a deduction
guide, in case any of the template parameters were invalid.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D110460

Added: 


Modified: 
clang/lib/AST/DeclTemplate.cpp
clang/test/SemaTemplate/deduction-crash.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp
index a25185067b9c5..fa73c53866490 100644
--- a/clang/lib/AST/DeclTemplate.cpp
+++ b/clang/lib/AST/DeclTemplate.cpp
@@ -165,14 +165,20 @@ unsigned TemplateParameterList::getDepth() const {
 return cast(FirstParm)->getDepth();
 }
 
-static void AdoptTemplateParameterList(TemplateParameterList *Params,
+static bool AdoptTemplateParameterList(TemplateParameterList *Params,
DeclContext *Owner) {
+  bool Invalid = false;
   for (NamedDecl *P : *Params) {
 P->setDeclContext(Owner);
 
 if (const auto *TTP = dyn_cast(P))
-  AdoptTemplateParameterList(TTP->getTemplateParameters(), Owner);
+  if (AdoptTemplateParameterList(TTP->getTemplateParameters(), Owner))
+Invalid = true;
+
+if (P->isInvalidDecl())
+  Invalid = true;
   }
+  return Invalid;
 }
 
 void TemplateParameterList::
@@ -339,14 +345,15 @@ void RedeclarableTemplateDecl::addSpecializationImpl(
 // FunctionTemplateDecl Implementation
 
//===--===//
 
-FunctionTemplateDecl *FunctionTemplateDecl::Create(ASTContext ,
-   DeclContext *DC,
-   SourceLocation L,
-   DeclarationName Name,
-   TemplateParameterList *Params,
-   NamedDecl *Decl) {
-  AdoptTemplateParameterList(Params, cast(Decl));
-  return new (C, DC) FunctionTemplateDecl(C, DC, L, Name, Params, Decl);
+FunctionTemplateDecl *
+FunctionTemplateDecl::Create(ASTContext , DeclContext *DC, SourceLocation L,
+ DeclarationName Name,
+ TemplateParameterList *Params, NamedDecl *Decl) {
+  bool Invalid = AdoptTemplateParameterList(Params, cast(Decl));
+  auto *TD = new (C, DC) FunctionTemplateDecl(C, DC, L, Name, Params, Decl);
+  if (Invalid)
+TD->setInvalidDecl();
+  return TD;
 }
 
 FunctionTemplateDecl *FunctionTemplateDecl::CreateDeserialized(ASTContext ,
@@ -438,15 +445,16 @@ void 
FunctionTemplateDecl::mergePrevDecl(FunctionTemplateDecl *Prev) {
 // ClassTemplateDecl Implementation
 
//===--===//
 
-ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext ,
- DeclContext *DC,
+ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext , DeclContext *DC,
  SourceLocation L,
  DeclarationName Name,
  TemplateParameterList *Params,
  NamedDecl *Decl) {
-  AdoptTemplateParameterList(Params, cast(Decl));
-
-  return new (C, DC) ClassTemplateDecl(C, DC, L, Name, Params, Decl);
+  bool Invalid = AdoptTemplateParameterList(Params, cast(Decl));
+  auto *TD = new (C, DC) ClassTemplateDecl(C, DC, L, Name, Params, Decl);
+  if (Invalid)
+TD->setInvalidDecl();
+  return TD;
 }
 
 ClassTemplateDecl *ClassTemplateDecl::CreateDeserialized(ASTContext ,
@@ -1005,8 +1013,11 @@ ConceptDecl *ConceptDecl::Create(ASTContext , 
DeclContext *DC,
  SourceLocation L, DeclarationName Name,
  TemplateParameterList *Params,
  Expr *ConstraintExpr) {
-  AdoptTemplateParameterList(Params, DC);
-  return new (C, DC) ConceptDecl(DC, L, Name, Params, ConstraintExpr);
+  bool Invalid = AdoptTemplateParameterList(Params, DC);
+  auto *TD = new (C, DC) ConceptDecl(DC, L, Name, Params, ConstraintExpr);
+  if (Invalid)
+TD->setInvalidDecl();
+  return TD;
 }
 
 ConceptDecl *ConceptDecl::CreateDeserialized(ASTContext ,
@@ -1039,7 +1050,8 @@ ClassTemplatePartialSpecializationDecl(ASTContext 
, TagKind TK,
   SpecializedTemplate, Args, PrevDecl),
   

[clang] 489561d - [clang] fix typo correction not looking for candidates in base classes.

2021-10-15 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-10-16T00:35:22+02:00
New Revision: 489561d46381d41a068beed1a2e18e00f0660248

URL: 
https://github.com/llvm/llvm-project/commit/489561d46381d41a068beed1a2e18e00f0660248
DIFF: 
https://github.com/llvm/llvm-project/commit/489561d46381d41a068beed1a2e18e00f0660248.diff

LOG: [clang] fix typo correction not looking for candidates in base classes.

RecordMemberExprValidator was not looking through ElaboratedType
nodes when looking for candidates which occur in base classes.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D111830

Added: 


Modified: 
clang/lib/Sema/SemaExprMember.cpp
clang/test/CXX/drs/dr1xx.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprMember.cpp 
b/clang/lib/Sema/SemaExprMember.cpp
index 2a3b696417d8..83006f9d804a 100644
--- a/clang/lib/Sema/SemaExprMember.cpp
+++ b/clang/lib/Sema/SemaExprMember.cpp
@@ -611,11 +611,10 @@ class RecordMemberExprValidatorCCC final : public 
CorrectionCandidateCallback {
 if (Record->containsDecl(ND))
   return true;
 
-if (const CXXRecordDecl *RD = dyn_cast(Record)) {
+if (const auto *RD = dyn_cast(Record)) {
   // Accept candidates that occur in any of the current class' base 
classes.
   for (const auto  : RD->bases()) {
-if (const RecordType *BSTy =
-dyn_cast_or_null(BS.getType().getTypePtrOrNull())) 
{
+if (const auto *BSTy = BS.getType()->getAs()) {
   if (BSTy->getDecl()->containsDecl(ND))
 return true;
 }

diff  --git a/clang/test/CXX/drs/dr1xx.cpp b/clang/test/CXX/drs/dr1xx.cpp
index 4efa2e2fa943..51abb36dc9e3 100644
--- a/clang/test/CXX/drs/dr1xx.cpp
+++ b/clang/test/CXX/drs/dr1xx.cpp
@@ -477,7 +477,7 @@ namespace dr140 { // dr140: yes
 
 namespace dr141 { // dr141: yes
   template void f();
-  template struct S { int n; };
+  template struct S { int n; }; // expected-note 
{{'::dr141::S::n' declared here}}
   struct A : S {
 template void f();
 template struct S {};
@@ -485,7 +485,7 @@ namespace dr141 { // dr141: yes
   struct B : S {} b;
   void g() {
 a.f();
-(void)a.S::n; // expected-error {{no member named 'n'}}
+(void)a.S::n; // expected-error {{no member named 'n' in 
'dr141::A::S'; did you mean '::dr141::S::n'?}}
 #if __cplusplus < 201103L
 // expected-error@-2 {{ambiguous}}
 // expected-note@-11 {{lookup from the current scope}}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] af10d6f - [clang] don't instantiate templates with injected arguments

2021-09-29 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-29T23:19:13+02:00
New Revision: af10d6f350ff3e92c6ffae66cc9dac36884cdd55

URL: 
https://github.com/llvm/llvm-project/commit/af10d6f350ff3e92c6ffae66cc9dac36884cdd55
DIFF: 
https://github.com/llvm/llvm-project/commit/af10d6f350ff3e92c6ffae66cc9dac36884cdd55.diff

LOG: [clang] don't instantiate templates with injected arguments

There is a special situation with templates in local classes,
as can be seen in this example with generic lambdas in function scope:
```
template void foo() {
(void)[]() {
  struct S {
void bar() { (void)[](T2) {}; }
  };
};
};
template void foo();
```

As a consequence of the resolution of DR1484, bar is instantiated during the
substitution of foo, and in this context we would substitute the lambda within
it with it's own parameters "injected" (turned into arguments).

This can't be properly dealt with for at least a couple of reasons:
* The 'TemplateTypeParm' type itself can only deal with canonical replacement
  types, which the injected arguments are not.
* If T3 were constrained in the example above, our (non-conforming) eager
  substitution of type constraints would just leave that parameter dangling.

Instead of substituting with injected parameters, this patch just leaves those
inner levels unreplaced.

Since injected arguments appear to be unused within the users of
`getTemplateInstantiationArgs`, this patch just removes that support there and
leaves a couple of asserts in place.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D110727

Added: 
clang/test/SemaTemplate/generic-lambda.cpp

Modified: 
clang/lib/Sema/SemaTemplateInstantiate.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 3a09badf84960..a0f4d0cd8c241 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -161,10 +161,9 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D,
 if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
   break;
 
-  } else if (FunctionTemplateDecl *FunTmpl
-   = Function->getDescribedFunctionTemplate()) 
{
-// Add the "injected" template arguments.
-Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
+  } else if (Function->getDescribedFunctionTemplate()) {
+assert(Result.getNumSubstitutedLevels() == 0 &&
+   "Outer template not instantiated?");
   }
 
   // If this is a friend declaration and it declares an entity at
@@ -180,11 +179,8 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D,
   }
 } else if (CXXRecordDecl *Rec = dyn_cast(Ctx)) {
   if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) 
{
-QualType T = ClassTemplate->getInjectedClassNameSpecialization();
-const TemplateSpecializationType *TST =
-cast(Context.getCanonicalType(T));
-Result.addOuterTemplateArguments(
-llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
+assert(Result.getNumSubstitutedLevels() == 0 &&
+   "Outer template not instantiated?");
 if (ClassTemplate->isMemberSpecialization())
   break;
   }

diff  --git a/clang/test/SemaTemplate/generic-lambda.cpp 
b/clang/test/SemaTemplate/generic-lambda.cpp
new file mode 100644
index 0..fb5fa09ebcc1f
--- /dev/null
+++ b/clang/test/SemaTemplate/generic-lambda.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+// expected-no-diagnostics
+
+template  constexpr bool is_same_v = false;
+template  constexpr bool is_same_v = true;
+template 
+concept is_same = is_same_v;
+
+template  struct X {};
+template 
+concept C1 = is_same>;
+
+template  X>> t1() {
+  return [](T2) -> X> {
+struct S {
+  static X> f() {
+return [](T3) -> X {
+  static_assert(is_same>);
+  static_assert(is_same>);
+  return X();
+}(X());
+  }
+};
+return S::f();
+  }(X());
+};
+template X>> t1();
+
+#if 0 // FIXME: crashes
+template auto t2() {
+  return [](T2) {
+struct S {
+  static auto f() {
+return [](T3) {
+  static_assert(is_same>);
+  static_assert(is_same>);
+  return X();
+}(X());
+  }
+};
+return S::f();
+  }(X());
+};
+template auto t2();
+static_assert(is_same()), X>>>);
+
+template C1>> auto t3() {
+  return [] T2>(T2) -> C1> auto {
+struct S {
+  static auto f() {
+return [] T3>(T3) -> C1 auto {
+  return X();
+}(X());
+  }
+};
+return S::f();
+  }(X());
+};
+template C1>> auto t3();
+static_assert(is_same()), X>>>);
+#endif



___
cfe-commits 

[clang] 1f6458c - [clang] NFC: remove duplicated code around type constraint and templ arg subst

2021-09-29 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-09-29T23:05:46+02:00
New Revision: 1f6458cb1944b69f052db463e5f2c6304f16b256

URL: 
https://github.com/llvm/llvm-project/commit/1f6458cb1944b69f052db463e5f2c6304f16b256
DIFF: 
https://github.com/llvm/llvm-project/commit/1f6458cb1944b69f052db463e5f2c6304f16b256.diff

LOG: [clang] NFC: remove duplicated code around type constraint and templ arg 
subst

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D110726

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index d59a0549f4c10..2408f50c074bb 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -729,6 +729,10 @@ class DependentFunctionTemplateSpecializationInfo final
   /// Returns the number of explicit template arguments that were given.
   unsigned getNumTemplateArgs() const { return NumArgs; }
 
+  llvm::ArrayRef arguments() const {
+return llvm::makeArrayRef(getTemplateArgs(), getNumTemplateArgs());
+  }
+
   /// Returns the nth template argument.
   const TemplateArgumentLoc (unsigned I) const {
 assert(I < getNumTemplateArgs() && "template arg index out of range");

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index bd5cf12183712..64863e3a57813 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9483,9 +9483,9 @@ class Sema final {
   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
 SourceLocation Loc,
 const MultiLevelTemplateArgumentList );
-  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
- TemplateArgumentListInfo ,
- const MultiLevelTemplateArgumentList );
+
+  bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint 
*TC,
+   const MultiLevelTemplateArgumentList );
 
   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
   ParmVarDecl *Param);

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 00fe811860e5f..de05450d48eb1 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2267,22 +2267,8 @@ struct ConvertConstructorToDeductionGuideTransform {
   TTP->isParameterPack(), TTP->hasTypeConstraint(),
   TTP->isExpandedParameterPack() ?
   llvm::Optional(TTP->getNumExpansionParameters()) : None);
-  if (const auto *TC = TTP->getTypeConstraint()) {
-TemplateArgumentListInfo TransformedArgs;
-const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
-if (!ArgsAsWritten ||
-SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
-  ArgsAsWritten->NumTemplateArgs, TransformedArgs,
-  Args))
-  SemaRef.AttachTypeConstraint(
-  TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
-  TC->getNamedConcept(), ArgsAsWritten ?  : 
nullptr,
-  NewTTP,
-  NewTTP->isParameterPack()
- ? cast(TC->getImmediatelyDeclaredConstraint())
- ->getEllipsisLoc()
- : SourceLocation());
-  }
+  if (const auto *TC = TTP->getTypeConstraint())
+SemaRef.SubstTypeConstraint(NewTTP, TC, Args);
   if (TTP->hasDefaultArgument()) {
 TypeSourceInfo *InstantiatedDefaultArg =
 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,

diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 060f42bf9d644..424342df7725b 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -2979,14 +2979,13 @@ FinishTemplateArgumentDeduction(
   auto *Template = Partial->getSpecializedTemplate();
   const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
   Partial->getTemplateArgsAsWritten();
-  const TemplateArgumentLoc *PartialTemplateArgs =
-  PartialTemplArgInfo->getTemplateArgs();
 
   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
 PartialTemplArgInfo->RAngleLoc);
 
-  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
-  InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) 
{
+  if (S.SubstTemplateArguments(
+  PartialTemplArgInfo->arguments(),
+  MultiLevelTemplateArgumentList(*DeducedArgumentList), InstArgs)) {
 unsigned ArgIdx = 

[clang] 85914b7 - [clang] fix regression deducing pack expansion arguments introduced by D110216

2021-11-18 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-11-19T03:36:20+01:00
New Revision: 85914b757015dfbc780dc254696acb95b8dc7679

URL: 
https://github.com/llvm/llvm-project/commit/85914b757015dfbc780dc254696acb95b8dc7679
DIFF: 
https://github.com/llvm/llvm-project/commit/85914b757015dfbc780dc254696acb95b8dc7679.diff

LOG: [clang] fix regression deducing pack expansion arguments introduced by 
D110216

This test case had been missing when the original code
was introduced by 2fcb863b2b278.

Signed-off-by: Matheus Izvekov 

Differential Revision: https://reviews.llvm.org/D114207

Added: 


Modified: 
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.partial/p12.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 3c67b5b5072e..81edae10335d 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1337,6 +1337,13 @@ static Sema::TemplateDeductionResult 
DeduceTemplateArgumentsByTypeMatch(
 TemplateDeductionInfo ,
 SmallVectorImpl , unsigned TDF,
 bool PartialOrdering, bool DeducedFromArrayBound) {
+
+  // If the argument type is a pack expansion, look at its pattern.
+  // This isn't explicitly called out
+  if (const auto *AExp = dyn_cast(A))
+A = AExp->getPattern();
+  assert(!isa(A.getCanonicalType()));
+
   if (PartialOrdering) {
 // C++11 [temp.deduct.partial]p5:
 //   Before the partial ordering is done, certain transformations are

diff  --git 
a/clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.partial/p12.cpp 
b/clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.partial/p12.cpp
index ec7e8970b1b5..bb7f9da58eda 100644
--- a/clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.partial/p12.cpp
+++ b/clang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.partial/p12.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
-// expected-no-diagnostics
 
 // Note: Partial ordering of function templates containing template
 // parameter packs is independent of the number of deduced arguments
@@ -26,3 +25,15 @@ void test_h() {
   double  = h((int(*)(int, float&))0);
   double  = h((int(*)(int))0);
 }
+
+namespace test_j {
+
+template  struct ref {};
+
+template  void map(ref...);
+template  void map(ref x, ref... xs); // 
expected-note {{here}}
+
+template void map<0, 1>(ref<0>, ref<1>);
+// expected-error@-1 {{explicit instantiation of undefined function template 
'map'}}
+
+} // namespace test_j



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 21ed00b - [clang] NFC: rename internal `IsPossiblyOpaquelyQualifiedType` overload

2021-11-15 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-11-16T03:09:50+01:00
New Revision: 21ed00bc1bfd2b0b81d288f7f096a31079c24c4a

URL: 
https://github.com/llvm/llvm-project/commit/21ed00bc1bfd2b0b81d288f7f096a31079c24c4a
DIFF: 
https://github.com/llvm/llvm-project/commit/21ed00bc1bfd2b0b81d288f7f096a31079c24c4a.diff

LOG: [clang] NFC: rename internal `IsPossiblyOpaquelyQualifiedType` overload

Rename `IsPossiblyOpaquelyQualifiedType` overload taking a Type*
as `IsPossiblyOpaquelyQualifiedTypeInternal` instead.

Signed-off-by: Matheus Izvekov 

Differential Revision: https://reviews.llvm.org/D113954

Added: 


Modified: 
clang/lib/Sema/SemaTemplateDeduction.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index a1722c45b632..3c67b5b5072e 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -603,7 +603,7 @@ DeduceTemplateSpecArguments(Sema , TemplateParameterList 
*TemplateParams,
  /*NumberOfArgumentsMustMatch=*/true);
 }
 
-static bool IsPossiblyOpaquelyQualifiedType(const Type *T) {
+static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
   assert(T->isCanonicalUnqualified());
 
   switch (T->getTypeClass()) {
@@ -619,7 +619,7 @@ static bool IsPossiblyOpaquelyQualifiedType(const Type *T) {
   case Type::IncompleteArray:
   case Type::VariableArray:
   case Type::DependentSizedArray:
-return IsPossiblyOpaquelyQualifiedType(
+return IsPossiblyOpaquelyQualifiedTypeInternal(
 cast(T)->getElementType().getTypePtr());
 
   default:
@@ -630,7 +630,7 @@ static bool IsPossiblyOpaquelyQualifiedType(const Type *T) {
 /// Determines whether the given type is an opaque type that
 /// might be more qualified when instantiated.
 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
-  return IsPossiblyOpaquelyQualifiedType(
+  return IsPossiblyOpaquelyQualifiedTypeInternal(
   T->getCanonicalTypeInternal().getTypePtr());
 }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9fec50f - [cmake] use project relative paths when generating ASTNodeAPI.json

2021-11-15 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-11-15T12:35:34+01:00
New Revision: 9fec50f001b1ab86ff36c6e92336ae1c1d3fcdef

URL: 
https://github.com/llvm/llvm-project/commit/9fec50f001b1ab86ff36c6e92336ae1c1d3fcdef
DIFF: 
https://github.com/llvm/llvm-project/commit/9fec50f001b1ab86ff36c6e92336ae1c1d3fcdef.diff

LOG: [cmake] use project relative paths when generating ASTNodeAPI.json

Signed-off-by: Matheus Izvekov 

Reviewed By: stephenneuendorffer

Differential Revision: https://reviews.llvm.org/D113664

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 558385b0eb5a..403d2dfb45e8 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -60,11 +60,11 @@ else()
   $
 # Skip this in debug mode because parsing AST.h is too slow
 --skip-processing=${skip_expensive_processing}
--I ${CMAKE_BINARY_DIR}/lib/clang/${CLANG_VERSION}/include
--I ${CMAKE_SOURCE_DIR}/../clang/include
--I ${CMAKE_BINARY_DIR}/tools/clang/include
--I ${CMAKE_BINARY_DIR}/include
--I ${CMAKE_SOURCE_DIR}/include
+-I ${LLVM_BINARY_DIR}/lib/clang/${CLANG_VERSION}/include
+-I ${CLANG_SOURCE_DIR}/include
+-I ${LLVM_BINARY_DIR}/tools/clang/include
+-I ${LLVM_BINARY_DIR}/include
+-I ${LLVM_SOURCE_DIR}/include
 ${implicitDirs}
 --json-output-path ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
   )



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2d7fba5 - [clang] deprecate frelaxed-template-template-args, make it on by default

2021-10-27 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-10-27T22:48:27+02:00
New Revision: 2d7fba5f95f0614f6f2c4a4ed966b307d617898b

URL: 
https://github.com/llvm/llvm-project/commit/2d7fba5f95f0614f6f2c4a4ed966b307d617898b
DIFF: 
https://github.com/llvm/llvm-project/commit/2d7fba5f95f0614f6f2c4a4ed966b307d617898b.diff

LOG: [clang] deprecate frelaxed-template-template-args, make it on by default

A resolution to the ambiguity issues created by P0522, which is a DR solving
CWG 150, did not come as expected, so we are just going to accept the change,
and watch how users digest it.

For now we deprecate the flag with a warning, and make it on by default.
We don't remove the flag completely in order to give users a chance to
work around any problems by disabling it.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D109496

Added: 
clang/test/Driver/frelaxed-template-template-args.cpp

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
clang/test/Lexer/cxx-features.cpp
clang/test/SemaTemplate/deduction.cpp
clang/test/SemaTemplate/default-arguments.cpp
clang/test/SemaTemplate/instantiate-template-template-parm.cpp
clang/test/SemaTemplate/nested-template.cpp
clang/test/SemaTemplate/temp_arg_template.cpp
clang/test/SemaTemplate/temp_arg_template_cxx1z.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 0cf49ed397f60..e013cf25db809 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -355,7 +355,7 @@ def warn_drv_diagnostics_hotness_requires_pgo : Warning<
 def warn_drv_clang_unsupported : Warning<
   "the clang compiler does not support '%0'">;
 def warn_drv_deprecated_arg : Warning<
-  "argument '%0' is deprecated, use '%1' instead">, InGroup;
+  "argument '%0' is deprecated%select{|, use '%2' instead}1">, 
InGroup;
 def warn_drv_assuming_mfloat_abi_is : Warning<
   "unknown platform, assuming -mfloat-abi=%0">;
 def warn_ignoring_ftabstop_value : Warning<

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 4651f4fff6aa0..565ecd94f977c 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -149,7 +149,7 @@ LANGOPT(NoMathBuiltin , 1, 0, "disable math builtin 
functions")
 LANGOPT(GNUAsm, 1, 1, "GNU-style inline assembly")
 LANGOPT(Coroutines, 1, 0, "C++20 coroutines")
 LANGOPT(DllExportInlines  , 1, 1, "dllexported classes dllexport inline 
methods")
-LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template 
template arguments")
+LANGOPT(RelaxedTemplateTemplateArgs, 1, 1, "C++17 relaxed matching of template 
template arguments")
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index b4a2411fa5c5c..0d3c053e89ae4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2335,9 +2335,9 @@ defm application_extension : 
BoolFOption<"application-extension",
   PosFlag,
   NegFlag>;
 defm relaxed_template_template_args : 
BoolFOption<"relaxed-template-template-args",
-  LangOpts<"RelaxedTemplateTemplateArgs">, DefaultFalse,
-  PosFlag,
-  NegFlag>;
+  LangOpts<"RelaxedTemplateTemplateArgs">, DefaultTrue,
+  PosFlag,
+  NegFlag>;
 defm sized_deallocation : BoolFOption<"sized-deallocation",
   LangOpts<"SizedDeallocation">, DefaultFalse,
   PosFlag,

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index bef0dec64d4e1..44692e131d3e1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -683,7 +683,8 @@ SanitizerArgs::SanitizerArgs(const ToolChain ,
 Arg->claim();
 if (LegacySanitizeCoverage != 0) {
   D.Diag(diag::warn_drv_deprecated_arg)
-  << Arg->getAsString(Args) << 
"-fsanitize-coverage=trace-pc-guard";
+  << Arg->getAsString(Args) << true
+  << "-fsanitize-coverage=trace-pc-guard";
 }
 continue;
   }
@@ -718,11 +719,11 @@ SanitizerArgs::SanitizerArgs(const ToolChain ,
   // enabled.
   if (CoverageFeatures & CoverageTraceBB)
 D.Diag(clang::diag::warn_drv_deprecated_arg)
-<< "-fsanitize-coverage=trace-bb"
+<< "-fsanitize-coverage=trace-bb" 

[clang] 086e111 - [clang] NFC: include non friendly types and missing sugar in test expectations

2021-10-27 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-10-27T23:03:29+02:00
New Revision: 086e111216bc4fb8065aa7ef4bc226380d1c237e

URL: 
https://github.com/llvm/llvm-project/commit/086e111216bc4fb8065aa7ef4bc226380d1c237e
DIFF: 
https://github.com/llvm/llvm-project/commit/086e111216bc4fb8065aa7ef4bc226380d1c237e.diff

LOG: [clang] NFC: include non friendly types and missing sugar in test 
expectations

The dump of all diagnostics of all tests under 
`clang/test/{CXX,SemaCXX,SemaTemplate}` was analyzed , and all the cases where 
there were obviously bad canonical types being printed, like 
`type-parameter-*-*` and `` were identified. Also a 
small amount of cases of missing sugar were analyzed.

This patch then spells those explicitly in the test expectations, as 
preparatory work for future fixes for these problems.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D110210

Added: 


Modified: 
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp

clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
clang/test/CXX/temp/temp.decls/temp.class.spec/p6.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p5.cpp
clang/test/CXX/temp/temp.decls/temp.variadic/multi-level-substitution.cpp
clang/test/SemaCXX/conversion-function.cpp
clang/test/SemaCXX/cxx1y-generic-lambdas-variadics.cpp
clang/test/SemaCXX/cxx1y-generic-lambdas.cpp
clang/test/SemaCXX/cxx1z-decomposition.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp
clang/test/SemaCXX/recovery-expr-type.cpp
clang/test/SemaCXX/redeclared-alias-template.cpp
clang/test/SemaTemplate/instantiate-var-template.cpp
clang/test/SemaTemplate/temp_arg_nontype.cpp
clang/test/SemaTemplate/temp_arg_nontype_cxx1z.cpp

Removed: 




diff  --git a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
index f780bf796ee43..2933532627d4c 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4-cxx14.cpp
@@ -7,7 +7,7 @@ int  = [] (int ) -> decltype(auto) { return r; } (a);
 int  = [] (int ) -> decltype(auto) { return (r); } (a);
 int  = [] (int ) -> auto & { return r; } (a);
 int  = [] (int ) -> auto { return r; } (a); // expected-error {{cannot 
bind to a temporary}}
-int  = [] (int r) -> decltype(auto) { return r; } (a); // expected-error 
{{cannot bind to a temporary}}
+int  = [] (int r) -> decltype(auto) { return r; } (a); // expected-error 
{{non-const lvalue reference to type 'int' cannot bind to a temporary of type 
'int'}}
 int  = [] (int r) -> decltype(auto) { return (r); } (a); // expected-warning 
{{reference to stack}}
 // cxx2b-error@-1 {{non-const lvalue reference to type 'int' cannot bind to a 
temporary of type 'int'}}
 

diff  --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index cb9541caaddd4..cb9407b1db88b 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -36,7 +36,7 @@ namespace std {
 
 namespace p0702r1 {
   template struct X { // expected-note {{candidate}}
-X(std::initializer_list); // expected-note {{candidate}}
+X(std::initializer_list); // expected-note {{candidate template 
ignored: could not match 'initializer_list' against 
'p0702r1::Z'}}
   };
 
   X xi = {0};
@@ -84,4 +84,4 @@ int main() {
 }
 
 
-}
\ No newline at end of file
+}

diff  --git a/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp 
b/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
index d6d171470c21d..0963dd23724a8 100644
--- a/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
+++ b/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
@@ -336,9 +336,9 @@ namespace p0962r1 {
   void use(NA::A a, NB::B b, NC::C c, ND::D d, NE::E e, NF::F f) {
 for (auto x : a) {}
 for (auto x : b) {}
-for (auto x : c) {} // expected-error {{no viable 'end' function}}
-for (auto x : d) {} // expected-error {{no viable 'begin' function}}
-for (auto x : e) {} // expected-error {{no viable 'begin' function}}
-for (auto x : f) {} // expected-error {{no viable 'end' function}}
+for (auto x : c) {} // expected-error {{invalid range expression of type 
'p0962r1::NC::C'; no viable 'end' function available}}
+for (auto x : d) {} // expected-error {{invalid range expression of type 
'p0962r1::ND::D'; no viable 'begin' function available}}
+for (auto x : e) {} // expected-error {{invalid range expression of type 
'p0962r1::NE::E'; no viable 'begin' function available}}
+for (auto x : f) {} // expected-error 

[clang] 1d68eca - [clang] fix oops: enable implicit moves in MSVC compatibility mode

2021-07-20 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-20T23:32:05+02:00
New Revision: 1d68ecafd6ad9ba8857c78e567abbc58810329c1

URL: 
https://github.com/llvm/llvm-project/commit/1d68ecafd6ad9ba8857c78e567abbc58810329c1
DIFF: 
https://github.com/llvm/llvm-project/commit/1d68ecafd6ad9ba8857c78e567abbc58810329c1.diff

LOG: [clang] fix oops: enable implicit moves in MSVC compatibility mode

When disabling simpler implicit moves in MSVC compatibility mode as
a workaround in D105518, we forgot to make the opposite change and
enable regular (P1825) implicit moves in the same mode.

As a result, we were not doing any implicit moves at all. OOPS!

This fixes it and adds test for this.

This is a fix to a temporary workaround, there is ongoing
work to replace this, applying the workaround only to
system headers and the ::stl namespace.

Signed-off-by: Matheus Izvekov 

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D106303

Added: 


Modified: 
clang/lib/Sema/SemaStmt.cpp
clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 643dde437fc94..2ae27de9b2079 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3483,7 +3483,12 @@ ExprResult
 Sema::PerformMoveOrCopyInitialization(const InitializedEntity ,
   const NamedReturnInfo ,
   Expr *Value) {
-  if (!getLangOpts().CPlusPlus2b && NRInfo.isMoveEligible()) {
+  // FIXME: We force P1825 implicit moves here in msvc compatibility mode
+  // because we are disabling simpler implicit moves as a temporary
+  // work around, as the MSVC STL has issues with this change.
+  // We will come back later with a more targeted approach.
+  if ((!getLangOpts().CPlusPlus2b || getLangOpts().MSVCCompat) &&
+  NRInfo.isMoveEligible()) {
 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
   CK_NoOp, Value, VK_XValue, FPOptionsOverride());
 Expr *InitExpr = 

diff  --git a/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp 
b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp
index 2143c0535e606..07db9b8333fa6 100644
--- a/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp
+++ b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp
@@ -48,3 +48,5 @@ void test5() try {
   throw x; // new-error {{no matching constructor for initialization}}
 } catch (...) {
 }
+
+MoveOnly test6(MoveOnly x) { return x; }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4819b75 - [clang] NFC: change uses of `Expr->getValueKind` into `is?Value`

2021-07-27 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-28T03:09:31+02:00
New Revision: 4819b751bd875f458eb0060f7c586aa9ac41965c

URL: 
https://github.com/llvm/llvm-project/commit/4819b751bd875f458eb0060f7c586aa9ac41965c
DIFF: 
https://github.com/llvm/llvm-project/commit/4819b751bd875f458eb0060f7c586aa9ac41965c.diff

LOG: [clang] NFC: change uses of `Expr->getValueKind` into `is?Value`

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D100733

Added: 


Modified: 
clang/include/clang/AST/ExprCXX.h
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprClassification.cpp
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaInit.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 2626f9b925962..161287adce4ca 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -4528,9 +4528,7 @@ class MaterializeTemporaryExpr : public Expr {
 
   /// Determine whether this materialized temporary is bound to an
   /// lvalue reference; otherwise, it's bound to an rvalue reference.
-  bool isBoundToLvalueReference() const {
-return getValueKind() == VK_LValue;
-  }
+  bool isBoundToLvalueReference() const { return isLValue(); }
 
   /// Determine whether this temporary object is usable in constant
   /// expressions, as specified in C++20 [expr.const]p4.

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index ebf87618e1277..e8b4aaa2b81e6 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -2406,7 +2406,7 @@ bool Expr::isReadIfDiscardedInCPlusPlus11() const {
   // In C++11, discarded-value expressions of a certain form are special,
   // according to [expr]p10:
   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
-  //   expression is an lvalue of volatile-qualified type and it has
+  //   expression is a glvalue of volatile-qualified type and it has
   //   one of the following forms:
   if (!isGLValue() || !getType().isVolatileQualified())
 return false;
@@ -3874,8 +3874,7 @@ Expr::isNullPointerConstant(ASTContext ,
 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
   const Expr *E = this;
   while (true) {
-assert((E->getValueKind() == VK_LValue &&
-E->getObjectKind() == OK_ObjCProperty) &&
+assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
"expression is not a property reference");
 E = E->IgnoreParenCasts();
 if (const BinaryOperator *BO = dyn_cast(E)) {
@@ -3914,7 +3913,7 @@ FieldDecl *Expr::getSourceBitField() {
 
   while (ImplicitCastExpr *ICE = dyn_cast(E)) {
 if (ICE->getCastKind() == CK_LValueToRValue ||
-(ICE->getValueKind() != VK_PRValue && ICE->getCastKind() == CK_NoOp))
+(ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
   E = ICE->getSubExpr()->IgnoreParens();
 else
   break;
@@ -3961,7 +3960,7 @@ bool Expr::refersToVectorElement() const {
   const Expr *E = this->IgnoreParens();
 
   while (const ImplicitCastExpr *ICE = dyn_cast(E)) {
-if (ICE->getValueKind() != VK_PRValue && ICE->getCastKind() == CK_NoOp)
+if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
   E = ICE->getSubExpr()->IgnoreParens();
 else
   break;

diff  --git a/clang/lib/AST/ExprClassification.cpp 
b/clang/lib/AST/ExprClassification.cpp
index 07fb44ceef2a4..6998e28fd2ea8 100644
--- a/clang/lib/AST/ExprClassification.cpp
+++ b/clang/lib/AST/ExprClassification.cpp
@@ -53,8 +53,12 @@ Cl Expr::ClassifyImpl(ASTContext , SourceLocation *Loc) 
const {
 
   // Enable this assertion for testing.
   switch (kind) {
-  case Cl::CL_LValue: assert(getValueKind() == VK_LValue); break;
-  case Cl::CL_XValue: assert(getValueKind() == VK_XValue); break;
+  case Cl::CL_LValue:
+assert(isLValue());
+break;
+  case Cl::CL_XValue:
+assert(isXValue());
+break;
   case Cl::CL_Function:
   case Cl::CL_Void:
   case Cl::CL_AddressableVoid:
@@ -65,7 +69,7 @@ Cl Expr::ClassifyImpl(ASTContext , SourceLocation *Loc) 
const {
   case Cl::CL_ArrayTemporary:
   case Cl::CL_ObjCMessageRValue:
   case Cl::CL_PRValue:
-assert(getValueKind() == VK_PRValue);
+assert(isPRValue());
 break;
   }
 

diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index de9f3f6f899c6..5b3d39f20b416 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -714,10 +714,10 @@ static bool tryEmitARCCopyWeakInit(CodeGenFunction ,
   }
 
   // If it was an l-value, use objc_copyWeak.
-  if (srcExpr->getValueKind() == VK_LValue) {
+  if (srcExpr->isLValue()) {
 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
   } else {
-

[clang] 20555a1 - [clang] P2266 implicit moves STL workaround

2021-07-26 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2021-07-26T22:21:31+02:00
New Revision: 20555a15a596012ef827e29b665db53a4fc0b86c

URL: 
https://github.com/llvm/llvm-project/commit/20555a15a596012ef827e29b665db53a4fc0b86c
DIFF: 
https://github.com/llvm/llvm-project/commit/20555a15a596012ef827e29b665db53a4fc0b86c.diff

LOG: [clang] P2266 implicit moves STL workaround

This patch replaces the workaround for simpler implicit moves
implemented in D105518.

The Microsoft STL currently has some issues with P2266.

Where before, with -fms-compatibility, we would disable simpler
implicit moves globally, with this change, we disable it only
when the returned expression is in a context contained by
std namespace and is located within a system header.

Signed-off-by: Matheus Izvekov 

Reviewed By: aaron.ballman, mibintc

Differential Revision: https://reviews.llvm.org/D105951

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 013722cfbe1e5..83a2d132bf6a4 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4785,20 +4785,24 @@ class Sema final {
 bool isMoveEligible() const { return S != None; };
 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
   };
-  NamedReturnInfo getNamedReturnInfo(Expr *, bool ForceCXX2b = false);
+  enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
+  NamedReturnInfo getNamedReturnInfo(
+  Expr *, SimplerImplicitMoveMode Mode = 
SimplerImplicitMoveMode::Normal);
   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
   const VarDecl *getCopyElisionCandidate(NamedReturnInfo ,
  QualType ReturnType);
 
-  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity ,
- const NamedReturnInfo ,
- Expr *Value);
+  ExprResult
+  PerformMoveOrCopyInitialization(const InitializedEntity ,
+  const NamedReturnInfo , Expr *Value,
+  bool SupressSimplerImplicitMoves = false);
 
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  Scope *CurScope);
   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
- NamedReturnInfo );
+ NamedReturnInfo ,
+ bool SupressSimplerImplicitMoves);
 
   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
  bool IsVolatile, unsigned NumOutputs,

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 676421552a757..bca0bb4ada672 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -598,8 +598,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const 
LangOptions ,
   }
   // C++2b features.
   if (LangOpts.CPlusPlus2b) {
-if (!LangOpts.MSVCCompat)
-  Builder.defineMacro("__cpp_implicit_move", "202011L");
+Builder.defineMacro("__cpp_implicit_move", "202011L");
 Builder.defineMacro("__cpp_size_t_suffix", "202011L");
   }
   if (LangOpts.Char8)

diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index 31a4092b5b604..098fe618865fa 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -977,7 +977,7 @@ StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr 
*E,
   VarDecl *Promise = FSI->CoroutinePromise;
   ExprResult PC;
   if (E && (isa(E) || !E->getType()->isVoidType())) {
-getNamedReturnInfo(E, /*ForceCXX2b=*/true);
+getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
   } else {
 E = MakeFullDiscardedValueExpr(E).get();

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 64c53df0b..3baccec2d7bb4 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3322,7 +3322,8 @@ Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope 
*CurScope) {
 /// \returns An aggregate which contains the Candidate and isMoveEligible
 /// and isCopyElidable methods. If Candidate is non-null, it means
 /// isMoveEligible() would be true under the most permissive language standard.
-Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *, bool ForceCXX2b) {
+Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *,
+   

[clang] [AST] Only dump desugared type when visibly different (PR #65214)

2023-09-08 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Yep, I definitely I agree this is a good change, thanks for working on it!
I thought about doing the same at the time, but I just didn't have the 
bandwidth for yet another patch with a lot of test churn :)

https://github.com/llvm/llvm-project/pull/65214
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-19 Thread Matheus Izvekov via cfe-commits


@@ -153,6 +153,67 @@ Please run this, then file a bug with the instructions and 
reduced .bc file
 that bugpoint emits.  If something goes wrong with bugpoint, please submit
 the "foo.bc" file and the option that llc crashes with.
 
+LTO bugs
+---
+
+If you encounter a bug that leads to crashes in the LLVM LTO phase when using
+the `-flto` option, follow these steps to diagnose and report the issue:
+
+Compile your source file to a .bc (Bitcode) file with the following flags,
+in addition to your existing compilation options:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld" CXXFLAGS="-flto -fuse-ld=lld" 
LDFLAGS="-Wl,-plugin-opt=save-temps"
+
+These flags enable LTO and save temporary files generated during compilation
+for later analysis.
+
+On Windows, you should use lld-link as the linker. Adjust your compilation 
+flags as follows:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld-link" CXXFLAGS="-flto -fuse-ld=lld-link" 
LDFLAGS="-Wl,-plugin-opt=save-temps"

mizvekov wrote:

Does this actually work? The option is spelled `/lldsavetemps` in the COFF 
linker.

https://github.com/llvm/llvm-project/pull/68389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-25 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/70282

>From 9f3711c112159c57becae105561bc988a0caaeb5 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 26 Oct 2023 06:07:57 +0200
Subject: [PATCH 1/2] [clang][driver] remove accidentally added NoXarchOption
 flag

This flag was accidentally added in 6da382d27bb5c21dfce8ae5239ab5797bc191cab
Explained in 
https://github.com/llvm/llvm-project/pull/70282#discussion_r1372537230
---
 clang/include/clang/Driver/Options.td | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c6b1903a32a0621..f9bf170c32ba25e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1922,10 +1922,10 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   NegFlag>;
 def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
-  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+  HelpText<"Enable verification of LLVM IR">;
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
-  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+  HelpText<"Disable verification of LLVM IR">;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;

>From c4b858b791792626e0a5584a0a2aeb877a0151c9 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 12:09:15 +0200
Subject: [PATCH 2/2] [Clang][Driver] Add new flags to control machine
 instruction verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 8 
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 26 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 42f20b9a9bb0410..80cebbe3210983f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -206,6 +206,13 @@ New Compiler Flags
   Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
   build times, it's disabled by default, unless your LLVM distribution itself 
is
   compiled with runtime checks enabled.
+* ``-fverify-machine-code`` and its complement ``-fno-verify-machine-code``.
+  Enable or disable the verification of the generated machine code.
+  Users can pass this to turn on extra verification to catch certain types of
+  compiler bugs at the cost of extra compile time.
+  This verifier adds a huge overhead to compile time, it's expected that build 
times
+  can double, so this is disabled by default.
+  This flag is currently limited to non-LTO builds.
 * ``-fkeep-system-includes`` modifies the behavior of the ``-E`` option,
   preserving ``#include`` directives for "system" headers instead of copying
   the preprocessed text to the output. This can greatly reduce the size of the
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f9bf170c32ba25e..092b54967ccdab0 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1926,6 +1926,12 @@ def fverify_intermediate_code : Flag<["-"], 
"fverify-intermediate-code">,
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
   HelpText<"Disable verification of LLVM IR">;
+def fverify_machine_code : Flag<["-"], "fverify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of generated machine code">;
+def fno_verify_machine_code : Flag<["-"], "fno-verify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of generated machine code">;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 601bbfb927746fc..6b7ae896863e4da 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5175,6 +5175,14 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 CmdArgs.push_back("-disable-llvm-verifier");
   }
 
+  // Enable the machine code verification pass. Note that this is force enabled
+  // elsewhere with LLVM_ENABLE_EXPENSIVE_CHECKS.
+  if (Args.hasFlag(options::OPT_fverify_machine_code,
+   options::OPT_fno_verify_machine_code, false)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-verify-machineinstrs");
+  }
+
   // 

[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-25 Thread Matheus Izvekov via cfe-commits


@@ -1926,6 +1926,12 @@ def fverify_intermediate_code : Flag<["-"], 
"fverify-intermediate-code">,
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
   HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fverify_machine_code : Flag<["-"], "fverify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of generated machine code">, 
Flags<[NoXarchOption]>;

mizvekov wrote:

Done. I also fixed in a separate commit the related flag above it, which I 
added recently.

https://github.com/llvm/llvm-project/pull/70282
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-25 Thread Matheus Izvekov via cfe-commits


@@ -1926,6 +1926,12 @@ def fverify_intermediate_code : Flag<["-"], 
"fverify-intermediate-code">,
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
   HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fverify_machine_code : Flag<["-"], "fverify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of generated machine code">, 
Flags<[NoXarchOption]>;

mizvekov wrote:

Ops nevermind the separate fix, you beat me to it :)

https://github.com/llvm/llvm-project/pull/70282
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-25 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/70282

Present shortcomings are that this only works for non-LTO builds, and that this 
new pass doesn't work quite the same as the IR verification flag, as it runs 
between every machine pass and is thus much more expensive.

Though I recently discussed this with @aeubanks during the US devmtg and we 
think this is worthwhile as a first step.

>From 8015101a24e302fae53fe19683024d47e9ae4d8d Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 12:09:15 +0200
Subject: [PATCH] [Clang][Driver] Add new flags to control machine instruction
 verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 8 
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 26 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 42f20b9a9bb0410..80cebbe3210983f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -206,6 +206,13 @@ New Compiler Flags
   Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
   build times, it's disabled by default, unless your LLVM distribution itself 
is
   compiled with runtime checks enabled.
+* ``-fverify-machine-code`` and its complement ``-fno-verify-machine-code``.
+  Enable or disable the verification of the generated machine code.
+  Users can pass this to turn on extra verification to catch certain types of
+  compiler bugs at the cost of extra compile time.
+  This verifier adds a huge overhead to compile time, it's expected that build 
times
+  can double, so this is disabled by default.
+  This flag is currently limited to non-LTO builds.
 * ``-fkeep-system-includes`` modifies the behavior of the ``-E`` option,
   preserving ``#include`` directives for "system" headers instead of copying
   the preprocessed text to the output. This can greatly reduce the size of the
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c6b1903a32a0621..c190af69d1e1145 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1926,6 +1926,12 @@ def fverify_intermediate_code : Flag<["-"], 
"fverify-intermediate-code">,
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
   HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fverify_machine_code : Flag<["-"], "fverify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of generated machine code">, 
Flags<[NoXarchOption]>;
+def fno_verify_machine_code : Flag<["-"], "fno-verify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of generated machine code">, 
Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 601bbfb927746fc..6b7ae896863e4da 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5175,6 +5175,14 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 CmdArgs.push_back("-disable-llvm-verifier");
   }
 
+  // Enable the machine code verification pass. Note that this is force enabled
+  // elsewhere with LLVM_ENABLE_EXPENSIVE_CHECKS.
+  if (Args.hasFlag(options::OPT_fverify_machine_code,
+   options::OPT_fno_verify_machine_code, false)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-verify-machineinstrs");
+  }
+
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
options::OPT_fno_discard_value_names, !IsAssertBuild)) {
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index ebe8a0520bf0fca..e6bb6f80f00368b 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -525,6 +525,11 @@
 // CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
 // CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
 
+// RUN: %clang -### -S -fverify-machine-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-MACHINE-CODE %s
+// RUN: %clang -### -S -fno-verify-machine-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-MACHINE-CODE %s
+// CHECK-VERIFY-MACHINE-CODE: "-mllvm" "-verify-machineinstrs"
+// CHECK-NO-VERIFY-MACHINE-CODE-NOT: "-mllvm" "-verify-machineinstrs"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 

[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-25 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/70282

>From b2006f46ebfd1da17014cf6c577da4700c355d00 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 12:09:15 +0200
Subject: [PATCH] [Clang][Driver] Add new flags to control machine instruction
 verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 8 
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 26 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 42f20b9a9bb0410..80cebbe3210983f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -206,6 +206,13 @@ New Compiler Flags
   Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
   build times, it's disabled by default, unless your LLVM distribution itself 
is
   compiled with runtime checks enabled.
+* ``-fverify-machine-code`` and its complement ``-fno-verify-machine-code``.
+  Enable or disable the verification of the generated machine code.
+  Users can pass this to turn on extra verification to catch certain types of
+  compiler bugs at the cost of extra compile time.
+  This verifier adds a huge overhead to compile time, it's expected that build 
times
+  can double, so this is disabled by default.
+  This flag is currently limited to non-LTO builds.
 * ``-fkeep-system-includes`` modifies the behavior of the ``-E`` option,
   preserving ``#include`` directives for "system" headers instead of copying
   the preprocessed text to the output. This can greatly reduce the size of the
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2eb86caa6e6d40e..bda5312d016d231 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1925,6 +1925,12 @@ def fverify_intermediate_code : Flag<["-"], 
"fverify-intermediate-code">,
 def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
   Group, Visibility<[ClangOption, CLOption, DXCOption]>,
   HelpText<"Disable verification of LLVM IR">;
+def fverify_machine_code : Flag<["-"], "fverify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of generated machine code">;
+def fno_verify_machine_code : Flag<["-"], "fno-verify-machine-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of generated machine code">;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 601bbfb927746fc..6b7ae896863e4da 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5175,6 +5175,14 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 CmdArgs.push_back("-disable-llvm-verifier");
   }
 
+  // Enable the machine code verification pass. Note that this is force enabled
+  // elsewhere with LLVM_ENABLE_EXPENSIVE_CHECKS.
+  if (Args.hasFlag(options::OPT_fverify_machine_code,
+   options::OPT_fno_verify_machine_code, false)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-verify-machineinstrs");
+  }
+
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
options::OPT_fno_discard_value_names, !IsAssertBuild)) {
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index ebe8a0520bf0fca..e6bb6f80f00368b 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -525,6 +525,11 @@
 // CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
 // CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
 
+// RUN: %clang -### -S -fverify-machine-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-MACHINE-CODE %s
+// RUN: %clang -### -S -fno-verify-machine-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-MACHINE-CODE %s
+// CHECK-VERIFY-MACHINE-CODE: "-mllvm" "-verify-machineinstrs"
+// CHECK-NO-VERIFY-MACHINE-CODE-NOT: "-mllvm" "-verify-machineinstrs"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-23 Thread Matheus Izvekov via cfe-commits


@@ -153,6 +153,67 @@ Please run this, then file a bug with the instructions and 
reduced .bc file
 that bugpoint emits.  If something goes wrong with bugpoint, please submit
 the "foo.bc" file and the option that llc crashes with.
 
+LTO bugs
+---
+
+If you encounter a bug that leads to crashes in the LLVM LTO phase when using
+the `-flto` option, follow these steps to diagnose and report the issue:
+
+Compile your source file to a .bc (Bitcode) file with the following flags,
+in addition to your existing compilation options:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld" CXXFLAGS="-flto -fuse-ld=lld" 
LDFLAGS="-Wl,-plugin-opt=save-temps"
+
+These flags enable LTO and save temporary files generated during compilation
+for later analysis.
+
+On Windows, you should use lld-link as the linker. Adjust your compilation 
+flags as follows:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld-link" CXXFLAGS="-flto -fuse-ld=lld-link" 
LDFLAGS="-Wl,-plugin-opt=save-temps"

mizvekov wrote:

```suggestion
On Windows, you should be using lld-link as the linker. Adjust your compilation 
flags as follows:
* Add `/lldsavetemps` to the linker flags.
* When linking from the compiler driver, Add `/link /lldsavetemps` in order to 
forward that flag to the linker.

https://github.com/llvm/llvm-project/pull/68389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-23 Thread Matheus Izvekov via cfe-commits


@@ -153,6 +153,67 @@ Please run this, then file a bug with the instructions and 
reduced .bc file
 that bugpoint emits.  If something goes wrong with bugpoint, please submit
 the "foo.bc" file and the option that llc crashes with.
 
+LTO bugs
+---
+
+If you encounter a bug that leads to crashes in the LLVM LTO phase when using
+the `-flto` option, follow these steps to diagnose and report the issue:
+
+Compile your source file to a .bc (Bitcode) file with the following flags,
+in addition to your existing compilation options:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld" CXXFLAGS="-flto -fuse-ld=lld" 
LDFLAGS="-Wl,-plugin-opt=save-temps"
+
+These flags enable LTO and save temporary files generated during compilation
+for later analysis.
+
+On Windows, you should use lld-link as the linker. Adjust your compilation 
+flags as follows:
+
+.. code-block:: bash
+
+   export CFLAGS="-flto -fuse-ld=lld-link" CXXFLAGS="-flto -fuse-ld=lld-link" 
LDFLAGS="-Wl,-plugin-opt=save-temps"

mizvekov wrote:

```suggestion
On Windows, you should be using lld-link as the linker. Adjust your compilation 
flags as follows:
* Add `/lldsavetemps` to the linker flags.
* When linking from the compiler driver, Add `/link /lldsavetemps` in order to 
forward that flag to the linker.

https://github.com/llvm/llvm-project/pull/68389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-23 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/68389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-23 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/68389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control machine instruction verification (PR #70282)

2023-10-26 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

I don't disagree that if we stop at this step, then the flag doesn't buy much. 
But it would be worthwhile if we ever implemented LTO integration or 
implemented a lightweight machine verification which runs the pass 1 or 2 
times, which would work similarly to the IR verification flag.

So shall we put this MR to sleep until we have that, or otherwise abandon this 
effort?
Either way works for me.

https://github.com/llvm/llvm-project/pull/70282
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-09-19 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> It looks like the Itanium mangleTypeName() canonicalizes the type itself; 
> should the MSVC mangleTypeName do the same thing?

It's done on purpose:
`MicrosoftMangle.cpp`:
```cpp
void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
 QualifierMangleMode QMM) {
  // Don't use the canonical types.  MSVC includes things like 'const' on
  // pointer arguments to function pointers that canonicalization strips away.
```

https://github.com/llvm/llvm-project/pull/66816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-09-19 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/66816

Hashing the sugared type instead of the canonical type meant that
a simple example like this would always fail under MSVC:

```
static auto l() {}
int main() {
  auto a = l;
  a();
}
```
`clang --target=x86_64-pc-windows-msvc -fno-exceptions -fsanitize=function -g 
-O0 -fuse-ld=lld -o test.exe test.cc`

produces:
```
test.cc:4:3: runtime error: call to function l through pointer to incorrect 
function type 'void (*)()'
```

>From 20a7f3574d7931d908cb016968f488e769cb7007 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Tue, 19 Sep 2023 21:50:39 +0200
Subject: [PATCH 1/3] -fsanitize=function: Add a MSVC test case

---
 clang/test/CodeGen/ubsan-function.cpp | 21 +
 1 file changed, 13 insertions(+), 8 deletions(-)

diff --git a/clang/test/CodeGen/ubsan-function.cpp 
b/clang/test/CodeGen/ubsan-function.cpp
index 1c281c8544578fe..bc37a61c98ee3ae 100644
--- a/clang/test/CodeGen/ubsan-function.cpp
+++ b/clang/test/CodeGen/ubsan-function.cpp
@@ -1,12 +1,15 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,64
-// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,64
-// RUN: %clang_cc1 -triple aarch64_be-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,64
-// RUN: %clang_cc1 -triple arm-none-eabi -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,ARM,32
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,GNU,64
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,MSVC,64
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,GNU,64
+// RUN: %clang_cc1 -triple aarch64_be-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,GNU,64
+// RUN: %clang_cc1 -triple arm-none-eabi -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,ARM,GNU,32
 
-// CHECK: define{{.*}} void @_Z3funv() #0 !func_sanitize ![[FUNCSAN:.*]] {
+// GNU:  define{{.*}} void @_Z3funv() #0 !func_sanitize ![[FUNCSAN:.*]] {
+// MSVC: define{{.*}} void @"?fun@@YAXXZ"() #0 !func_sanitize ![[FUNCSAN:.*]] {
 void fun() {}
 
-// CHECK-LABEL: define{{.*}} void @_Z6callerPFvvE(ptr noundef %f)
+// GNU-LABEL:  define{{.*}} void @_Z6callerPFvvE(ptr noundef %f)
+// MSVC-LABEL: define{{.*}} void @"?caller@@YAXP6AXXZ@Z"(ptr noundef %f)
 // ARM:   ptrtoint ptr {{.*}} to i32, !nosanitize !5
 // ARM:   and i32 {{.*}}, -2, !nosanitize !5
 // ARM:   inttoptr i32 {{.*}} to ptr, !nosanitize !5
@@ -17,7 +20,8 @@ void fun() {}
 // CHECK: [[LABEL1]]:
 // CHECK: getelementptr <{ i32, i32 }>, ptr {{.*}}, i32 -1, i32 1, !nosanitize
 // CHECK: load i32, ptr {{.*}}, align {{.*}}, !nosanitize
-// CHECK: icmp eq i32 {{.*}}, 905068220, !nosanitize
+// GNU:   icmp eq i32 {{.*}}, 905068220, !nosanitize
+// MSVC:  icmp eq i32 {{.*}}, -1600339357, !nosanitize
 // CHECK: br i1 {{.*}}, label %[[LABEL3:.*]], label %[[LABEL2:[^,]*]], 
{{.*}}!nosanitize
 // CHECK: [[LABEL2]]:
 // 64:call void @__ubsan_handle_function_type_mismatch_abort(ptr @[[#]], 
i64 %[[#]]) #[[#]], !nosanitize
@@ -32,4 +36,5 @@ void fun() {}
 // CHECK-NEXT:   ret void
 void caller(void (*f)()) { f(); }
 
-// CHECK: ![[FUNCSAN]] = !{i32 -1056584962, i32 905068220}
+// GNU:  ![[FUNCSAN]] = !{i32 -1056584962, i32 905068220}
+// MSVC: ![[FUNCSAN]] = !{i32 -1056584962, i32 -1600339357}

>From 4fb0135c7c441633cd29e57772fab758d60ca16b Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Tue, 19 Sep 2023 22:15:42 +0200
Subject: [PATCH 2/3] -fsanitize=function: Add a (bugged) test case for a
 sugared function type

---
 clang/test/CodeGen/ubsan-function-sugared.cpp | 44 +++
 1 file changed, 44 insertions(+)
 create mode 100644 clang/test/CodeGen/ubsan-function-sugared.cpp

diff --git a/clang/test/CodeGen/ubsan-function-sugared.cpp 
b/clang/test/CodeGen/ubsan-function-sugared.cpp
new file mode 100644
index 000..238bf31f4aba6d1
--- /dev/null
+++ b/clang/test/CodeGen/ubsan-function-sugared.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,GNU,64
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -emit-llvm -o - %s 
-fsanitize=function -fno-sanitize-recover=all | FileCheck %s 
--check-prefixes=CHECK,MSVC,64
+// RUN: %clang_cc1 -triple aarch64-linux-gnu 

[clang] Improve sort mangled (PR #67066)

2023-09-21 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/67066

This is stacked on top of https://github.com/llvm/llvm-project/pull/66816
Disregard first commit.

>From 47bd926491f28f722c429f3ab4a993aa5d85d1b7 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Tue, 19 Sep 2023 22:21:25 +0200
Subject: [PATCH 1/2] -fsanitize=function: fix MSVC hashing to sugared type

Hashing the sugared type instead of the canonical type meant that
a simple example like this would always fail under MSVC:

```
static auto l() {}
int main() {
  auto a = l;
  a();
}
```
`clang --target=x86_64-pc-windows-msvc -fno-exceptions -fsanitize=function -g 
-O0 -fuse-ld=lld -o test.exe test.cc`

produces:
```
test.cc:4:3: runtime error: call to function l through pointer to incorrect 
function type 'void (*)()'
```
---
 clang/include/clang/AST/Mangle.h  | 4 ++--
 clang/lib/AST/Expr.cpp| 2 +-
 clang/lib/AST/ItaniumMangle.cpp   | 8 
 clang/lib/AST/MicrosoftMangle.cpp | 8 
 clang/lib/CodeGen/CGBlocks.cpp| 2 +-
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 2 +-
 clang/lib/CodeGen/CGVTables.cpp   | 5 +++--
 clang/lib/CodeGen/CodeGenFunction.cpp | 2 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 4 ++--
 clang/lib/CodeGen/CodeGenTBAA.cpp | 4 ++--
 clang/test/CodeGen/ubsan-function-sugared.cpp | 3 +--
 clang/unittests/AST/DeclTest.cpp  | 4 ++--
 12 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/clang/include/clang/AST/Mangle.h b/clang/include/clang/AST/Mangle.h
index c04bcc7f01cb4e6..e586b0cec43dfd6 100644
--- a/clang/include/clang/AST/Mangle.h
+++ b/clang/include/clang/AST/Mangle.h
@@ -178,8 +178,8 @@ class MangleContext {
   /// or type uniquing.
   /// TODO: Extend this to internal types by generating names that are unique
   /// across translation units so it can be used with LTO.
-  virtual void mangleTypeName(QualType T, raw_ostream &,
-  bool NormalizeIntegers = false) = 0;
+  virtual void mangleCanonicalTypeName(QualType T, raw_ostream &,
+   bool NormalizeIntegers = false) = 0;
 
   /// @}
 };
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 4f3837371b3fc5e..f94482206b738d5 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -659,7 +659,7 @@ std::string 
SYCLUniqueStableNameExpr::ComputeName(ASTContext ,
   std::string Buffer;
   Buffer.reserve(128);
   llvm::raw_string_ostream Out(Buffer);
-  Ctx->mangleTypeName(Ty, Out);
+  Ctx->mangleCanonicalTypeName(Ty, Out);
 
   return Out.str();
 }
diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 3bbc0a5767ff49d..87c3f233ddd7bfd 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -112,8 +112,8 @@ class ItaniumMangleContextImpl : public 
ItaniumMangleContext {
   void mangleCXXRTTI(QualType T, raw_ostream &) override;
   void mangleCXXRTTIName(QualType T, raw_ostream &,
  bool NormalizeIntegers) override;
-  void mangleTypeName(QualType T, raw_ostream &,
-  bool NormalizeIntegers) override;
+  void mangleCanonicalTypeName(QualType T, raw_ostream &,
+   bool NormalizeIntegers) override;
 
   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) 
override;
   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
@@ -7041,8 +7041,8 @@ void ItaniumMangleContextImpl::mangleCXXRTTIName(
   Mangler.mangleType(Ty);
 }
 
-void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream ,
-  bool NormalizeIntegers = false) {
+void ItaniumMangleContextImpl::mangleCanonicalTypeName(
+QualType Ty, raw_ostream , bool NormalizeIntegers = false) {
   mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
 }
 
diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 79175c79de96bf8..c1320cbdf0e6385 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -196,8 +196,8 @@ class MicrosoftMangleContextImpl : public 
MicrosoftMangleContext {
   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
  ArrayRef BasePath,
  raw_ostream ) override;
-  void mangleTypeName(QualType T, raw_ostream &,
-  bool NormalizeIntegers) override;
+  void mangleCanonicalTypeName(QualType T, raw_ostream &,
+   bool NormalizeIntegers) override;
   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
 raw_ostream &) override;
   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream ) override;
@@ -3838,13 +3838,13 @@ void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
   

[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-09-21 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-09-28 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/67751

Stacked, consider only last commit.

>From 7009ebf7f2016816b5cbb694e0611cd2a86d7cf1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 28 Sep 2023 22:38:59 +0200
Subject: [PATCH 1/2] [clang] implement common sugared type of inst-dependent
 DecltypeType

While a DecltypeType node itself is not uniqued, an
instantiation dependent DecltypeType will have a
DependentDecltypeType as an underlying type, which is uniqued.

In that case, there can be non-identical non-sugar DecltypeTypes nodes
which nonetheless represent the same type.

Fixes https://github.com/llvm/llvm-project/issues/67603
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/AST/ASTContext.cpp  |  9 -
 clang/test/SemaCXX/sugar-common-types.cpp | 11 +++
 3 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1d74c492845a6c3..09302040a3510b6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -266,6 +266,9 @@ Bug Fixes in This Version
   (`#64836 `_)
 - Clang now allows an ``_Atomic`` qualified integer in a switch statement. 
Fixes
   (`#65557 `_)
+- Fixes crash when trying to obtain the common sugared type of
+  `decltype(instantiation-dependent-expr)`.
+  Fixes (`#67603 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 57aaa05b1d81ddb..5ce0b54166e0255 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12705,7 +12705,6 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
 
 #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
 SUGAR_FREE_TYPE(Builtin)
-SUGAR_FREE_TYPE(Decltype)
 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
 SUGAR_FREE_TYPE(DependentBitInt)
 SUGAR_FREE_TYPE(Enum)
@@ -12935,6 +12934,14 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
TY->getTemplateName()),
 As, X->getCanonicalTypeInternal());
   }
+  case Type::Decltype: {
+const auto *DX = cast(X), *DY = cast(Y);
+assert(DX->isDependentType());
+assert(DY->isDependentType());
+assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
+// As Decltype is not uniqued, building a common type would be wasteful.
+return QualType(DX, 0);
+  }
   case Type::DependentName: {
 const auto *NX = cast(X),
*NY = cast(Y);
diff --git a/clang/test/SemaCXX/sugar-common-types.cpp 
b/clang/test/SemaCXX/sugar-common-types.cpp
index 4a8ff2addb66359..e1c7578a66b9cad 100644
--- a/clang/test/SemaCXX/sugar-common-types.cpp
+++ b/clang/test/SemaCXX/sugar-common-types.cpp
@@ -142,3 +142,14 @@ namespace PR61419 {
   extern const pair p;
   id t = false ? p.first : p.second;
 } // namespace PR61419
+
+namespace GH67603 {
+  template  using A = long;
+  template  void h() {
+using C = B;
+using D = B;
+N t = 0 ? A() : A();
+// expected-error@-1 {{rvalue of type 'A' (aka 'long')}}
+  }
+  template void h();
+} // namespace GH67603

>From b6f194c89bafad17e1dcc76b3a87d2330aac1c10 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 29 Sep 2023 00:49:16 +0200
Subject: [PATCH 2/2] [NFC][clang] change remaining context-dependent type
 nodes to ContextualFoldingSet

---
 clang/include/clang/AST/ASTContext.h | 24 ++
 clang/include/clang/AST/Type.h   | 62 ++---
 clang/lib/AST/ASTContext.cpp | 68 
 clang/lib/AST/Type.cpp   | 47 +--
 4 files changed, 90 insertions(+), 111 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 4ee32c76a95d8e3..8ad0514ee2ce227 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -195,20 +195,25 @@ class ASTContext : public RefCountedBase {
   ConstantArrayTypes;
   mutable llvm::FoldingSet IncompleteArrayTypes;
   mutable std::vector VariableArrayTypes;
-  mutable llvm::FoldingSet DependentSizedArrayTypes;
-  mutable llvm::FoldingSet
-DependentSizedExtVectorTypes;
-  mutable llvm::FoldingSet
+  mutable llvm::ContextualFoldingSet
+  DependentSizedArrayTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentSizedExtVectorTypes;
+  mutable llvm::ContextualFoldingSet
   DependentAddressSpaceTypes;
   mutable llvm::FoldingSet VectorTypes;
-  mutable llvm::FoldingSet DependentVectorTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentVectorTypes;
   mutable llvm::FoldingSet MatrixTypes;
-  mutable llvm::FoldingSet DependentSizedMatrixTypes;
+  mutable 

[clang] [clang] implement common sugared type of inst-dependent DecltypeType (PR #67739)

2023-09-28 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/67739

>From 7009ebf7f2016816b5cbb694e0611cd2a86d7cf1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 28 Sep 2023 22:38:59 +0200
Subject: [PATCH] [clang] implement common sugared type of inst-dependent
 DecltypeType

While a DecltypeType node itself is not uniqued, an
instantiation dependent DecltypeType will have a
DependentDecltypeType as an underlying type, which is uniqued.

In that case, there can be non-identical non-sugar DecltypeTypes nodes
which nonetheless represent the same type.

Fixes https://github.com/llvm/llvm-project/issues/67603
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/AST/ASTContext.cpp  |  9 -
 clang/test/SemaCXX/sugar-common-types.cpp | 11 +++
 3 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1d74c492845a6c3..09302040a3510b6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -266,6 +266,9 @@ Bug Fixes in This Version
   (`#64836 `_)
 - Clang now allows an ``_Atomic`` qualified integer in a switch statement. 
Fixes
   (`#65557 `_)
+- Fixes crash when trying to obtain the common sugared type of
+  `decltype(instantiation-dependent-expr)`.
+  Fixes (`#67603 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 57aaa05b1d81ddb..5ce0b54166e0255 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12705,7 +12705,6 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
 
 #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
 SUGAR_FREE_TYPE(Builtin)
-SUGAR_FREE_TYPE(Decltype)
 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
 SUGAR_FREE_TYPE(DependentBitInt)
 SUGAR_FREE_TYPE(Enum)
@@ -12935,6 +12934,14 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
TY->getTemplateName()),
 As, X->getCanonicalTypeInternal());
   }
+  case Type::Decltype: {
+const auto *DX = cast(X), *DY = cast(Y);
+assert(DX->isDependentType());
+assert(DY->isDependentType());
+assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
+// As Decltype is not uniqued, building a common type would be wasteful.
+return QualType(DX, 0);
+  }
   case Type::DependentName: {
 const auto *NX = cast(X),
*NY = cast(Y);
diff --git a/clang/test/SemaCXX/sugar-common-types.cpp 
b/clang/test/SemaCXX/sugar-common-types.cpp
index 4a8ff2addb66359..e1c7578a66b9cad 100644
--- a/clang/test/SemaCXX/sugar-common-types.cpp
+++ b/clang/test/SemaCXX/sugar-common-types.cpp
@@ -142,3 +142,14 @@ namespace PR61419 {
   extern const pair p;
   id t = false ? p.first : p.second;
 } // namespace PR61419
+
+namespace GH67603 {
+  template  using A = long;
+  template  void h() {
+using C = B;
+using D = B;
+N t = 0 ? A() : A();
+// expected-error@-1 {{rvalue of type 'A' (aka 'long')}}
+  }
+  template void h();
+} // namespace GH67603

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] implement common sugared type of inst-dependent DecltypeType (PR #67739)

2023-09-28 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/67739

While a DecltypeType node itself is not uniqued, an instantiation dependent 
DecltypeType will have a
DependentDecltypeType as an underlying type, which is uniqued.

In that case, there can be non-identical non-sugar DecltypeTypes nodes which 
nonetheless represent the same type.

Fixes https://github.com/llvm/llvm-project/issues/67603

>From e6c6a3868ac45f09ec3ddaa888b35ed759c28f33 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 28 Sep 2023 22:38:59 +0200
Subject: [PATCH] [clang] implement common sugared type of inst-dependent
 DecltypeType

While a DecltypeType node itself is not uniqued, an
instantiation dependent DecltypeType will have a
DependentDecltypeType as an underlying type, which is uniqued.

In that case, there can be non-identical non-sugar DecltypeTypes nodes
which nonetheless represent the same type.

Fixes https://github.com/llvm/llvm-project/issues/67603
---
 clang/lib/AST/ASTContext.cpp  |  9 -
 clang/test/SemaCXX/sugar-common-types.cpp | 11 +++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 57aaa05b1d81ddb..5ce0b54166e0255 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12705,7 +12705,6 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
 
 #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
 SUGAR_FREE_TYPE(Builtin)
-SUGAR_FREE_TYPE(Decltype)
 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
 SUGAR_FREE_TYPE(DependentBitInt)
 SUGAR_FREE_TYPE(Enum)
@@ -12935,6 +12934,14 @@ static QualType getCommonNonSugarTypeNode(ASTContext 
, const Type *X,
TY->getTemplateName()),
 As, X->getCanonicalTypeInternal());
   }
+  case Type::Decltype: {
+const auto *DX = cast(X), *DY = cast(Y);
+assert(DX->isDependentType());
+assert(DY->isDependentType());
+assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
+// As Decltype is not uniqued, building a common type would be wasteful.
+return QualType(DX, 0);
+  }
   case Type::DependentName: {
 const auto *NX = cast(X),
*NY = cast(Y);
diff --git a/clang/test/SemaCXX/sugar-common-types.cpp 
b/clang/test/SemaCXX/sugar-common-types.cpp
index 4a8ff2addb66359..e1c7578a66b9cad 100644
--- a/clang/test/SemaCXX/sugar-common-types.cpp
+++ b/clang/test/SemaCXX/sugar-common-types.cpp
@@ -142,3 +142,14 @@ namespace PR61419 {
   extern const pair p;
   id t = false ? p.first : p.second;
 } // namespace PR61419
+
+namespace GH67603 {
+  template  using A = long;
+  template  void h() {
+using C = B;
+using D = B;
+N t = 0 ? A() : A();
+// expected-error@-1 {{rvalue of type 'A' (aka 'long')}}
+  }
+  template void h();
+} // namespace GH67603

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] implement common sugared type of inst-dependent DecltypeType (PR #67739)

2023-09-28 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov closed 
https://github.com/llvm/llvm-project/pull/67739
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-09-29 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/67751
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-09-29 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/67751

>From 5919cbf2a91f1cff3e48ba10cd2e9f5d2f5023f0 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 29 Sep 2023 00:49:16 +0200
Subject: [PATCH] [NFC][clang] change remaining context-dependent type nodes to
 ContextualFoldingSet

---
 clang/include/clang/AST/ASTContext.h | 24 ++
 clang/include/clang/AST/Type.h   | 62 ++---
 clang/lib/AST/ASTContext.cpp | 68 
 clang/lib/AST/Type.cpp   | 47 +--
 4 files changed, 90 insertions(+), 111 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 4ee32c76a95d8e3..8ad0514ee2ce227 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -195,20 +195,25 @@ class ASTContext : public RefCountedBase {
   ConstantArrayTypes;
   mutable llvm::FoldingSet IncompleteArrayTypes;
   mutable std::vector VariableArrayTypes;
-  mutable llvm::FoldingSet DependentSizedArrayTypes;
-  mutable llvm::FoldingSet
-DependentSizedExtVectorTypes;
-  mutable llvm::FoldingSet
+  mutable llvm::ContextualFoldingSet
+  DependentSizedArrayTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentSizedExtVectorTypes;
+  mutable llvm::ContextualFoldingSet
   DependentAddressSpaceTypes;
   mutable llvm::FoldingSet VectorTypes;
-  mutable llvm::FoldingSet DependentVectorTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentVectorTypes;
   mutable llvm::FoldingSet MatrixTypes;
-  mutable llvm::FoldingSet DependentSizedMatrixTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentSizedMatrixTypes;
   mutable llvm::FoldingSet FunctionNoProtoTypes;
   mutable llvm::ContextualFoldingSet
 FunctionProtoTypes;
-  mutable llvm::FoldingSet DependentTypeOfExprTypes;
-  mutable llvm::FoldingSet DependentDecltypeTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentTypeOfExprTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentDecltypeTypes;
   mutable llvm::FoldingSet TemplateTypeParmTypes;
   mutable llvm::FoldingSet ObjCTypeParamTypes;
   mutable llvm::FoldingSet
@@ -238,7 +243,8 @@ class ASTContext : public RefCountedBase {
   mutable llvm::FoldingSet AttributedTypes;
   mutable llvm::FoldingSet PipeTypes;
   mutable llvm::FoldingSet BitIntTypes;
-  mutable llvm::FoldingSet DependentBitIntTypes;
+  mutable llvm::ContextualFoldingSet
+  DependentBitIntTypes;
   llvm::FoldingSet BTFTagAttributedTypes;
 
   mutable llvm::FoldingSet QualifiedTemplateNames;
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 4799f89db82fa7f..a78d8f60462b231 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -3289,8 +3289,6 @@ class VariableArrayType : public ArrayType {
 class DependentSizedArrayType : public ArrayType {
   friend class ASTContext; // ASTContext creates these.
 
-  const ASTContext 
-
   /// An assignment expression that will instantiate to the
   /// size of the array.
   ///
@@ -3301,8 +3299,8 @@ class DependentSizedArrayType : public ArrayType {
   /// The range spanned by the left and right array brackets.
   SourceRange Brackets;
 
-  DependentSizedArrayType(const ASTContext , QualType et, QualType can,
-  Expr *e, ArraySizeModifier sm, unsigned tq,
+  DependentSizedArrayType(QualType et, QualType can, Expr *e,
+  ArraySizeModifier sm, unsigned tq,
   SourceRange brackets);
 
 public:
@@ -3325,7 +3323,7 @@ class DependentSizedArrayType : public ArrayType {
 return T->getTypeClass() == DependentSizedArray;
   }
 
-  void Profile(llvm::FoldingSetNodeID ) {
+  void Profile(llvm::FoldingSetNodeID , const ASTContext ) {
 Profile(ID, Context, getElementType(),
 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
   }
@@ -3349,14 +3347,12 @@ class DependentSizedArrayType : public ArrayType {
 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
   friend class ASTContext;
 
-  const ASTContext 
   Expr *AddrSpaceExpr;
   QualType PointeeType;
   SourceLocation loc;
 
-  DependentAddressSpaceType(const ASTContext , QualType PointeeType,
-QualType can, Expr *AddrSpaceExpr,
-SourceLocation loc);
+  DependentAddressSpaceType(QualType PointeeType, QualType can,
+Expr *AddrSpaceExpr, SourceLocation loc);
 
 public:
   Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
@@ -3370,7 +3366,7 @@ class DependentAddressSpaceType : public Type, public 
llvm::FoldingSetNode {
 return T->getTypeClass() == DependentAddressSpace;
   }
 
-  void Profile(llvm::FoldingSetNodeID ) {
+  void Profile(llvm::FoldingSetNodeID , const ASTContext ) {
 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
   }
 
@@ -3391,7 

[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov closed 
https://github.com/llvm/llvm-project/pull/66816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/68015

This helps check clang generated good IR in the first place, as otherwise this 
can cause UB in subsequent passes, with the final verification pass not 
catching any issues.

This for example would have helped catch
https://github.com/llvm/llvm-project/issues/67937 earlier.

>From e728912a39421291d44f94c8304789710fe7bb67 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 2 Oct 2023 13:52:35 +0200
Subject: [PATCH] [clang][codegen] Add a verifier IR pass before any further
 passes.

This helps check clang generated good IR in the first place,
as otherwise this can cause UB in subsequent passes,
with the final verification pass not catching any issues.

This for example would have helped catch
https://github.com/llvm/llvm-project/issues/67937 earlier.
---
 clang/lib/CodeGen/BackendUtil.cpp   | 16 ++--
 clang/test/CodeGen/code-coverage.c  |  4 ++--
 clang/test/CodeGen/lto-newpm-pipeline.c | 10 ++
 3 files changed, 18 insertions(+), 12 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index b0fe8e03aa0f5f0..c386749a0c77620 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -923,6 +923,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  MPM.addPass(VerifierPass());
 
   if (!CodeGenOpts.DisableLLVMPasses) {
 // Map our optimization levels into one of the distinct levels used to
@@ -1020,21 +1022,23 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 }
 
 if (CodeGenOpts.FatLTO) {
-  MPM = PB.buildFatLTODefaultPipeline(Level, PrepareForThinLTO,
-  PrepareForThinLTO ||
-  shouldEmitRegularLTOSummary());
+  MPM.addPass(PB.buildFatLTODefaultPipeline(
+  Level, PrepareForThinLTO,
+  PrepareForThinLTO || shouldEmitRegularLTOSummary()));
 } else if (PrepareForThinLTO) {
-  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
 } else if (PrepareForLTO) {
-  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
 } else {
-  MPM = PB.buildPerModuleDefaultPipeline(Level);
+  MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
 }
   }
 
   // Add a verifier pass if requested. We don't have to do this if the action
   // requires code generation because there will already be a verifier pass in
   // the code-generation pipeline.
+  // Since we already added a verifier pass above, this
+  // might even not run the analysis, if previous passes caused no changes.
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
diff --git a/clang/test/CodeGen/code-coverage.c 
b/clang/test/CodeGen/code-coverage.c
index af02a6ddaef990a..d7994bab35d81a0 100644
--- a/clang/test/CodeGen/code-coverage.c
+++ b/clang/test/CodeGen/code-coverage.c
@@ -15,10 +15,10 @@
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null %s 2>&1 | FileCheck --check-prefix=NEWPM %s
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null -O3 %s 2>&1 | FileCheck --check-prefix=NEWPM-O3 %s
 
-// NEWPM-NOT: Running pass
+// NEWPM: Running pass: VerifierPass
 // NEWPM: Running pass: GCOVProfilerPass
 
-// NEWPM-O3-NOT: Running pass
+// NEWPM-O3: Running pass: VerifierPass
 // NEWPM-O3: Running pass: Annotation2MetadataPass
 // NEWPM-O3: Running pass: ForceFunctionAttrsPass
 // NEWPM-O3: Running pass: GCOVProfilerPass
diff --git a/clang/test/CodeGen/lto-newpm-pipeline.c 
b/clang/test/CodeGen/lto-newpm-pipeline.c
index 1aaa7d46f3ff06f..f58757efbf686f2 100644
--- a/clang/test/CodeGen/lto-newpm-pipeline.c
+++ b/clang/test/CodeGen/lto-newpm-pipeline.c
@@ -25,7 +25,9 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm-bc -o /dev/null 
-mllvm -verify-analysis-invalidation=0 -fdebug-pass-manager -flto=thin -Oz %s 
2>&1 | FileCheck %s \
 // RUN:   -check-prefix=CHECK-THIN-OPTIMIZED
 
-// CHECK-FULL-O0: Running pass: AlwaysInlinerPass
+// CHECK-FULL-O0: Running pass: VerifierPass
+// CHECK-FULL-O0-NEXT: Running analysis: VerifierAnalysis
+// CHECK-FULL-O0-NEXT: Running pass: AlwaysInlinerPass
 // CHECK-FULL-O0-NEXT: Running analysis: InnerAnalysisManagerProxy
 // CHECK-FULL-O0-NEXT: Running analysis: ProfileSummaryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: CoroConditionalWrapper
@@ -34,10 +36,11 @@
 // CHECK-FULL-O0-NEXT: Running pass: AnnotationRemarksPass
 // CHECK-FULL-O0-NEXT: Running analysis: TargetLibraryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: VerifierPass
-// CHECK-FULL-O0-NEXT: 

[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits


@@ -923,6 +923,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  MPM.addPass(VerifierPass());

mizvekov wrote:

Yeah, you are right, it does add some non-insignificant cost: 
http://llvm-compile-time-tracker.com/compare.php?from=e0cb340f8ef77e2fefa42a3d6f4bd9aab42ad660=e728912a39421291d44f94c8304789710fe7bb67=instructions:u

Though I believe these tests are all lightweight on Sema, don't use templates 
much, so the cost probably would not show as bad in the problematic case.

The docs encourage frontends to run the verifier before any optimizations: 
https://llvm.org/docs/Passes.html#verify-module-verifier

And this post 
https://discourse.llvm.org/t/should-clang-verify-ir-when-passing-a-llvm-ir-file/62926/3,
 though in a different context, does appear favorable towards the verifier, 
versus cost.

https://github.com/llvm/llvm-project/pull/68015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

@tru Would you agree to backport this fix to 17?

Strictly speaking there is an API change here, but I think it's a bit obscure 
and in any case, this change could catch misuse of it.

https://github.com/llvm/llvm-project/pull/66816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/67066

>From 44d43a8e7fa5b19671bc3f56f934dfb63a632aa4 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 21 Sep 2023 22:57:27 +0200
Subject: [PATCH] [NFC][Clang][CodeGen] Improve performance for vtable metadata
 generation

Mangle each AddressPoint once, instead of once per comparison.
---
 clang/lib/CodeGen/CGVTables.cpp | 54 ++---
 1 file changed, 22 insertions(+), 32 deletions(-)

diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index d782da2103b4c79..5ec38e0397bf4f7 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -24,6 +24,7 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include 
 #include 
+#include 
 
 using namespace clang;
 using namespace CodeGen;
@@ -1308,44 +1309,33 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
 
-  typedef std::pair AddressPoint;
+  struct AddressPoint {
+const CXXRecordDecl *Base;
+size_t Offset;
+std::string TypeName;
+bool operator<(const AddressPoint ) const {
+  int D = TypeName.compare(RHS.TypeName);
+  return D < 0 || (D == 0 && Offset < RHS.Offset);
+}
+  };
   std::vector AddressPoints;
-  for (auto & : VTLayout.getAddressPoints())
-AddressPoints.push_back(std::make_pair(
-AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
-AP.second.AddressPointIndex));
-
-  // Sort the address points for determinism.
-  // FIXME: It's more efficient to mangle the types before sorting.
-  llvm::sort(AddressPoints, [this](const AddressPoint ,
-   const AddressPoint ) {
-if ( == )
-  return false;
-
-std::string S1;
-llvm::raw_string_ostream O1(S1);
-getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP1.first->getTypeForDecl(), 0), O1);
-O1.flush();
-
-std::string S2;
-llvm::raw_string_ostream O2(S2);
+  for (auto & : VTLayout.getAddressPoints()) {
+AddressPoint N{AP.first.getBase(),
+   VTLayout.getVTableOffset(AP.second.VTableIndex) +
+   AP.second.AddressPointIndex};
+llvm::raw_string_ostream Stream(N.TypeName);
 getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP2.first->getTypeForDecl(), 0), O2);
-O2.flush();
-
-if (S1 < S2)
-  return true;
-if (S1 != S2)
-  return false;
+QualType(N.Base->getTypeForDecl(), 0), Stream);
+AddressPoints.push_back(std::move(N));
+  }
 
-return AP1.second < AP2.second;
-  });
+  // Sort the address points for determinism.
+  llvm::sort(AddressPoints);
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {
 // Create type metadata for the address point.
-AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
+AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
 
 // The class associated with each address point could also potentially be
 // used for indirect calls via a member function pointer, so we need to
@@ -1357,7 +1347,7 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
   llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
   Context.getMemberPointerType(
   Comps[I].getFunctionDecl()->getType(),
-  Context.getRecordType(AP.first).getTypePtr()));
+  Context.getRecordType(AP.Base).getTypePtr()));
   VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
 }
   }

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Yep, it's a regression from 16. This bug makes ubsan unusable for MSVC target 
in real world projects.

We could alternatively backport just the canonicalization, but not the rename, 
if that makes it better.

https://github.com/llvm/llvm-project/pull/66816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits


@@ -1020,21 +1022,23 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 }
 
 if (CodeGenOpts.FatLTO) {
-  MPM = PB.buildFatLTODefaultPipeline(Level, PrepareForThinLTO,
-  PrepareForThinLTO ||
-  shouldEmitRegularLTOSummary());
+  MPM.addPass(PB.buildFatLTODefaultPipeline(
+  Level, PrepareForThinLTO,
+  PrepareForThinLTO || shouldEmitRegularLTOSummary()));
 } else if (PrepareForThinLTO) {
-  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
 } else if (PrepareForLTO) {
-  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
 } else {
-  MPM = PB.buildPerModuleDefaultPipeline(Level);
+  MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
 }
   }
 
   // Add a verifier pass if requested. We don't have to do this if the action
   // requires code generation because there will already be a verifier pass in
   // the code-generation pipeline.
+  // Since we already added a verifier pass above, this
+  // might even not run the analysis, if previous passes caused no changes.

mizvekov wrote:

Yeah, that's what it says and is implemented here: 
https://github.com/llvm/llvm-project/blob/0b07b06effe5fdf779b75bb5ac6cf15e477cb0be/llvm/include/llvm/IR/PassManager.h#L772

And it matches what I see when running the pass-manager debugger on O0 vs O1 
builds, as you see on the changes affecting the 
`clang/test/CodeGen/lto-newpm-pipeline.c` test. You can see for O0 that the 
`VerifierPass` is executed a second time near the bottom, but that doesn't 
trigger a `VerifierAnalysis` run.

https://github.com/llvm/llvm-project/pull/68015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Weird, the commit in the MR has a description, but it lost the description when 
merging through the github interface.

https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e897014 - [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (#67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2023-10-03T03:23:34+02:00
New Revision: e8970141ec4326acb139789db01fb7c51538a4be

URL: 
https://github.com/llvm/llvm-project/commit/e8970141ec4326acb139789db01fb7c51538a4be
DIFF: 
https://github.com/llvm/llvm-project/commit/e8970141ec4326acb139789db01fb7c51538a4be.diff

LOG: [NFC][Clang][CodeGen] Improve performance for vtable metadata generation 
(#67066)

Mangle each AddressPoint once, instead of once per comparison.

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index d782da2103b4c79..c81b67ecf4fee0d 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -24,6 +24,7 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include 
 #include 
+#include 
 
 using namespace clang;
 using namespace CodeGen;
@@ -1308,44 +1309,34 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
 
-  typedef std::pair AddressPoint;
+  struct AddressPoint {
+const CXXRecordDecl *Base;
+size_t Offset;
+std::string TypeName;
+bool operator<(const AddressPoint ) const {
+  int D = TypeName.compare(RHS.TypeName);
+  return D < 0 || (D == 0 && Offset < RHS.Offset);
+}
+  };
   std::vector AddressPoints;
-  for (auto & : VTLayout.getAddressPoints())
-AddressPoints.push_back(std::make_pair(
-AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
-AP.second.AddressPointIndex));
-
-  // Sort the address points for determinism.
-  // FIXME: It's more efficient to mangle the types before sorting.
-  llvm::sort(AddressPoints, [this](const AddressPoint ,
-   const AddressPoint ) {
-if ( == )
-  return false;
-
-std::string S1;
-llvm::raw_string_ostream O1(S1);
-getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP1.first->getTypeForDecl(), 0), O1);
-O1.flush();
-
-std::string S2;
-llvm::raw_string_ostream O2(S2);
+  for (auto & : VTLayout.getAddressPoints()) {
+AddressPoint N{AP.first.getBase(),
+   VTLayout.getVTableOffset(AP.second.VTableIndex) +
+   AP.second.AddressPointIndex,
+   {}};
+llvm::raw_string_ostream Stream(N.TypeName);
 getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP2.first->getTypeForDecl(), 0), O2);
-O2.flush();
-
-if (S1 < S2)
-  return true;
-if (S1 != S2)
-  return false;
+QualType(N.Base->getTypeForDecl(), 0), Stream);
+AddressPoints.push_back(std::move(N));
+  }
 
-return AP1.second < AP2.second;
-  });
+  // Sort the address points for determinism.
+  llvm::sort(AddressPoints);
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {
 // Create type metadata for the address point.
-AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
+AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
 
 // The class associated with each address point could also potentially be
 // used for indirect calls via a member function pointer, so we need to
@@ -1357,7 +1348,7 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
   llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
   Context.getMemberPointerType(
   Comps[I].getFunctionDecl()->getType(),
-  Context.getRecordType(AP.first).getTypePtr()));
+  Context.getRecordType(AP.Base).getTypePtr()));
   VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
 }
   }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits


@@ -923,6 +923,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  MPM.addPass(VerifierPass());

mizvekov wrote:

There is actually just an option to disable it, it's otherwise on by default.
See this post for more details: 
https://discourse.llvm.org/t/rfc-running-llvm-verifier-right-out-of-codegen/73823/4

I have changed the current MR to also add the new pass under the same flag, as 
it's useful to allow folks to disable it, but it's otherwise going to be on for 
the majority of cases.

https://github.com/llvm/llvm-project/pull/68015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

@kstoimenov I believe you are supposed to notify the MR in case of reverts, 
otherwise I could have missed this if I wasn't awake.

I believe in this case the bot is misconfigured, it's using 
`-Werror,-Wmissing-field-initializers`, the 'error' is just a missing 
initializer, which I didn't add because I think it makes the intent clearer.

https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov deleted 
https://github.com/llvm/llvm-project/pull/68015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov closed 
https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68015

>From be5fab19a147c979c7e8afb421d157b194f4a125 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 2 Oct 2023 13:52:35 +0200
Subject: [PATCH] [clang][codegen] Add a verifier IR pass before any further
 passes.

This helps check clang generated good IR in the first place,
as otherwise this can cause UB in subsequent passes,
with the final verification pass not catching any issues.

This for example would have helped catch
https://github.com/llvm/llvm-project/issues/67937 earlier.
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +++--
 clang/test/CodeGen/code-coverage.c  |  4 ++--
 clang/test/CodeGen/lto-newpm-pipeline.c | 10 ++
 3 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index b0fe8e03aa0f5f0..d066819871dfde3 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -923,6 +923,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  if (CodeGenOpts.VerifyModule)
+MPM.addPass(VerifierPass());
 
   if (!CodeGenOpts.DisableLLVMPasses) {
 // Map our optimization levels into one of the distinct levels used to
@@ -1020,21 +1023,23 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 }
 
 if (CodeGenOpts.FatLTO) {
-  MPM = PB.buildFatLTODefaultPipeline(Level, PrepareForThinLTO,
-  PrepareForThinLTO ||
-  shouldEmitRegularLTOSummary());
+  MPM.addPass(PB.buildFatLTODefaultPipeline(
+  Level, PrepareForThinLTO,
+  PrepareForThinLTO || shouldEmitRegularLTOSummary()));
 } else if (PrepareForThinLTO) {
-  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
 } else if (PrepareForLTO) {
-  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
 } else {
-  MPM = PB.buildPerModuleDefaultPipeline(Level);
+  MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
 }
   }
 
   // Add a verifier pass if requested. We don't have to do this if the action
   // requires code generation because there will already be a verifier pass in
   // the code-generation pipeline.
+  // Since we already added a verifier pass above, this
+  // might even not run the analysis, if previous passes caused no changes.
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
diff --git a/clang/test/CodeGen/code-coverage.c 
b/clang/test/CodeGen/code-coverage.c
index af02a6ddaef990a..d7994bab35d81a0 100644
--- a/clang/test/CodeGen/code-coverage.c
+++ b/clang/test/CodeGen/code-coverage.c
@@ -15,10 +15,10 @@
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null %s 2>&1 | FileCheck --check-prefix=NEWPM %s
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null -O3 %s 2>&1 | FileCheck --check-prefix=NEWPM-O3 %s
 
-// NEWPM-NOT: Running pass
+// NEWPM: Running pass: VerifierPass
 // NEWPM: Running pass: GCOVProfilerPass
 
-// NEWPM-O3-NOT: Running pass
+// NEWPM-O3: Running pass: VerifierPass
 // NEWPM-O3: Running pass: Annotation2MetadataPass
 // NEWPM-O3: Running pass: ForceFunctionAttrsPass
 // NEWPM-O3: Running pass: GCOVProfilerPass
diff --git a/clang/test/CodeGen/lto-newpm-pipeline.c 
b/clang/test/CodeGen/lto-newpm-pipeline.c
index 1aaa7d46f3ff06f..f58757efbf686f2 100644
--- a/clang/test/CodeGen/lto-newpm-pipeline.c
+++ b/clang/test/CodeGen/lto-newpm-pipeline.c
@@ -25,7 +25,9 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm-bc -o /dev/null 
-mllvm -verify-analysis-invalidation=0 -fdebug-pass-manager -flto=thin -Oz %s 
2>&1 | FileCheck %s \
 // RUN:   -check-prefix=CHECK-THIN-OPTIMIZED
 
-// CHECK-FULL-O0: Running pass: AlwaysInlinerPass
+// CHECK-FULL-O0: Running pass: VerifierPass
+// CHECK-FULL-O0-NEXT: Running analysis: VerifierAnalysis
+// CHECK-FULL-O0-NEXT: Running pass: AlwaysInlinerPass
 // CHECK-FULL-O0-NEXT: Running analysis: InnerAnalysisManagerProxy
 // CHECK-FULL-O0-NEXT: Running analysis: ProfileSummaryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: CoroConditionalWrapper
@@ -34,10 +36,11 @@
 // CHECK-FULL-O0-NEXT: Running pass: AnnotationRemarksPass
 // CHECK-FULL-O0-NEXT: Running analysis: TargetLibraryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: VerifierPass
-// CHECK-FULL-O0-NEXT: Running analysis: VerifierAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: BitcodeWriterPass
 
-// CHECK-THIN-O0: Running pass: AlwaysInlinerPass
+// CHECK-THIN-O0: Running pass: VerifierPass
+// CHECK-THIN-O0-NEXT: Running analysis: 

[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-10-01 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Thanks for the review.

I think the change stands on itself, as we are avoiding storing one pointer per 
Type Node instance, for the cost of one extra pointer per ASTContext, which is 
negligible.

These type nodes we are changing here are old, at least as far back as 2008.
In 2010 this `ContextualFoldingSet` folding set was added in this commit: 
b9639aaed4ef98becf413b9d52680686f8f22ca1
To solve exactly this problem as you can see in the commit description.

But we never went back and updated the existing users. This patch does that.

https://github.com/llvm/llvm-project/pull/67751
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-10-01 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/67751
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-10-01 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/67751
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] -fsanitize=function: fix MSVC hashing to sugared type (PR #66816)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

@rnk Since @efriedma-quic seems to be unavailable, any objections we move 
forward and merge this, as is?

https://github.com/llvm/llvm-project/pull/66816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Qualify non-dependent types of a class template with the class declar… (PR #67566)

2023-09-27 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

CC @vgvassilev @pcanal @Sterling-Augustine 
As the removed workaround dates back to the initial implementation imported in 
0dd191a5c4bf27cc8a2b6033436b00f0cbdc4ce7 from Cling.

https://github.com/llvm/llvm-project/pull/67566
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Qualify non-dependent types of a class template with its declaration (PR #67566)

2023-09-27 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

It's recommended to avoid introducing pure clang-format changes mixed with 
other non-style changes.

The recommended way to avoid that is to run clang-format on the modified files 
on a separate commit, and then just merge that, no review required.

https://github.com/llvm/llvm-project/pull/67566
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov closed 
https://github.com/llvm/llvm-project/pull/68015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov closed 
https://github.com/llvm/llvm-project/pull/67751
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-03 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> Could you please send me a link which describes that process? I assume that 
> by MR you mean merge request? Thanks, Kirill
> […](#)
> On Mon, Oct 2, 2023 at 5:24 PM Matheus Izvekov ***@***.***> wrote: 
> @kstoimenov  I believe you are supposed to 
> notify the MR in case of reverts, otherwise I could have missed this if I 
> wasn't awake. I believe in this case the bot is misconfigured, it's using 
> -Werror,-Wmissing-field-initializers, the 'error' is just a missing 
> initializer, which I didn't add because I think it makes the intent clearer. 
> — Reply to this email directly, view it on GitHub <[#67066 
> (comment)](https://github.com/llvm/llvm-project/pull/67066#issuecomment-1743967544)>,
>  or unsubscribe 
> 
>  . You are receiving this because you were mentioned.Message ID: ***@***.***>
> -- Kirill Stoimenov | Software Engineer | ***@***.*** | +1- 650-253-6893

Sure.

https://github.com/llvm/llvm-project/blob/main/llvm/docs/DeveloperPolicy.rst#id62

See specifically the section about `What are the expectations around a 
revert?`, specifically fourth bullet.

But use your best judgement here: If you revert a commit without engaging the 
original author, he might have a hard time figuring out there was even a revert.
And also, you need to engage for other reasons as described in that section.

https://github.com/llvm/llvm-project/pull/67066
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CLang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/68172

None

>From 4aec8113bc23d361164f1e164c8e4e36a9eb0ad0 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..1e1433589ddd7c9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fdisable-llvm-verifier`` and it's complement 
``-fno-disable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..6911acb7420ec60 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fdisable_llvm_verifier : Flag<["-"], "fdisable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_disable_llvm_verifier : Flag<["-"], "fno-disable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Do not disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..1f1afee57ba4259 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fdisable_llvm_verifier,
+   options::OPT_fno_disable_llvm_verifier, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..f9882c2604cbb18 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fdisable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISABLE-LLVM-VERIFIER %s
+// RUN: %clang -### -S -fno-disable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISABLE-LLVM-VERIFIER %s
+// CHECK-DISABLE-LLVM-VERIFIER: "-disable-llvm-verifier"
+// CHECK-NO-DISABLE-LLVM-VERIFIER-NOT: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][CodeGen] Fix use of CXXThisValue with StrictVTablePointers (PR #68169)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/68169

When emitting non-virtual base initializers for the constructor prologue,
we would potentially use a re-laundered this pointer value from a
previous block, which subsequently would not dominate this use.

With this fix, we always launder the original CXXThisValue.

This fixes https://github.com/llvm/llvm-project/issues/67937


Note: First commit just adds the test, which will be fixed by the second 
commit. I will land the test separately after the first round.

>From 456b3d4e38fb80c599959d6b1ff5c93d94232394 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 02:34:31 +0200
Subject: [PATCH 1/2] [Clang][CodeGen][NFC] Add (broken) test case for GH67937

This adds a test case for yet unfixed 
https://github.com/llvm/llvm-project/issues/67937
---
 .../strict-vtable-pointers-GH67937.cpp| 29 +++
 1 file changed, 29 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp

diff --git a/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp 
b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
new file mode 100644
index 000..6fb1e68c288b181
--- /dev/null
+++ b/clang/test/CodeGenCXX/strict-vtable-pointers-GH67937.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 %s -I%S -triple=x86_64-pc-windows-msvc 
-fstrict-vtable-pointers -disable-llvm-passes -disable-llvm-verifier -O1 
-emit-llvm -o %t.ll
+// RUN: FileCheck %s < %t.ll
+// RUN: not llvm-as < %t.ll -o /dev/null 2>&1 | FileCheck %s 
--check-prefix=CHECK-VERIFIER
+
+struct A {
+  virtual ~A();
+};
+struct B : virtual A {};
+class C : B {};
+C foo;
+
+// FIXME: This is not supposed to generate invalid IR!
+// CHECK-VERIFIER: Instruction does not dominate all uses!
+// CHECK-VERIFIER-NEXT: %1 = call ptr @llvm.launder.invariant.group.p0(ptr 
%this1)
+// CHECK-VERIFIER-NEXT: %3 = call ptr @llvm.launder.invariant.group.p0(ptr %1)
+
+// CHECK-LABEL: define {{.*}} @"??0C@@QEAA@XZ"(ptr {{.*}} %this, i32 {{.*}} 
%is_most_derived)
+// CHECK: ctor.init_vbases:
+// CHECK-NEXT: %0 = getelementptr inbounds i8, ptr %this1, i64 0
+// CHECK-NEXT: store ptr @"??_8C@@7B@", ptr %0
+// CHECK-NEXT: %1 = call ptr @llvm.launder.invariant.group.p0(ptr %this1)
+// CHECK-NEXT: %2 = getelementptr inbounds i8, ptr %1, i64 8
+// CHECK-NEXT: %call = call noundef ptr @"??0A@@QEAA@XZ"(ptr {{.*}} %2) #2
+// CHECK-NEXT: br label %ctor.skip_vbases
+// CHECK-EMPTY:
+// CHECK-NEXT: ctor.skip_vbases:
+// FIXME: Should be using '%this1' instead of %1 below.
+// CHECK-NEXT: %3 = call ptr @llvm.launder.invariant.group.p0(ptr %1)
+// CHECK-NEXT: %call3 = call noundef ptr @"??0B@@QEAA@XZ"(ptr {{.*}} %3, i32 
noundef 0) #2

>From 4073aca154fe55e56b0025509ce85690eba061df Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 02:40:25 +0200
Subject: [PATCH 2/2] [Clang][CodeGen] Fix use of CXXThisValue with
 StrictVTablePointers

When emitting non-virtual base initializers for the constructor prologue,
we would potentially use a re-laundered this pointer value from a
previous block, which subsequently would not dominate this use.

With this fix, we always launder the original CXXThisValue.

This fixes https://github.com/llvm/llvm-project/issues/67937
---
 clang/lib/CodeGen/CGClass.cpp |  7 +++
 .../CodeGenCXX/strict-vtable-pointers-GH67937.cpp | 11 ++-
 2 files changed, 5 insertions(+), 13 deletions(-)

diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index 57a424c6f176c47..d18f186ce5b4157 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -28,6 +28,7 @@
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Metadata.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "llvm/Transforms/Utils/SanitizerStats.h"
 #include 
 
@@ -1291,10 +1292,10 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 assert(BaseCtorContinueBB);
   }
 
-  llvm::Value *const OldThis = CXXThisValue;
   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
 if (!ConstructVBases)
   continue;
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1311,7 +1312,7 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
   // Then, non-virtual base initializers.
   for (; B != E && (*B)->isBaseInitializer(); B++) {
 assert(!(*B)->isBaseVirtual());
-
+SaveAndRestore ThisRAII(CXXThisValue);
 if (CGM.getCodeGenOpts().StrictVTablePointers &&
 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
 isInitializerOfDynamicClass(*B))
@@ -1319,8 +1320,6 @@ void CodeGenFunction::EmitCtorPrologue(const 
CXXConstructorDecl *CD,
 EmitBaseInitializer(*this, ClassDecl, *B);
   }
 
-  CXXThisValue = 

[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/68172
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68172

>From ee49cd2bddc21be68f73fca7cb344150cd7ad7a6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..4e8487d3386e21c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fenable-llvm-verifier`` and it's complement ``-fdisable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..ee464de14f7740b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fenable_llvm_verifier : Flag<["-"], "fenable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fdisable_llvm_verifier : Flag<["-"], "fdisable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..11abc2cdf34d6a7 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fdisable_llvm_verifier,
+   options::OPT_fenable_llvm_verifier, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..e0764cf0b76830f 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fenable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-ENABLE-LLVM-VERIFIER %s
+// RUN: %clang -### -S -fdisable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISABLE-LLVM-VERIFIER %s
+// CHECK-ENABLE-LLVM-VERIFIER-NOT: "-disable-llvm-verifier"
+// CHECK-DISABLE-LLVM-VERIFIER: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68172

>From 8a0226386732cea374558a38475c7d629c84ef28 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65bd5c8300ea387..fd4b16a9202e188 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fenable-llvm-verifier`` and it's complement ``-fdisable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..99df825620582bb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..4af3ed2dd88ea65 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
+   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..ebe8a0520bf0fca 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fverify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-INTERMEDIATE-CODE %s
+// RUN: %clang -### -S -fno-verify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-INTERMEDIATE-CODE %s
+// CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
+// CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68172

>From 634c0f8ea4acd0694d89c3e2d278e6bcb78b923f Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [Clang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65bd5c8300ea387..804c0fc2e235c77 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,13 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fverify-intermediate-code`` and it's complement 
``-fno-verify-intermediate-code``.
+  Enables or disables verification of the generated LLVM IR.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..99df825620582bb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..4af3ed2dd88ea65 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
+   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..ebe8a0520bf0fca 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fverify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-INTERMEDIATE-CODE %s
+// RUN: %clang -### -S -fno-verify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-INTERMEDIATE-CODE %s
+// CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
+// CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Index] Use canonical function parameter types in USRs (PR #68222)

2023-10-04 Thread Matheus Izvekov via cfe-commits


@@ -265,10 +265,13 @@ void USRGenerator::VisitFunctionDecl(const FunctionDecl 
*D) {
 Out << '>';
   }
 
+  QualType CanonicalType = D->getType().getCanonicalType();
   // Mangle in type information for the arguments.
-  for (auto *PD : D->parameters()) {
-Out << '#';
-VisitType(PD->getType());
+  if (auto *FPT = CanonicalType->getAs()) {

mizvekov wrote:

I believe you can const qualify this, otherwise LGTM.

https://github.com/llvm/llvm-project/pull/68222
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Index] Use canonical function parameter types in USRs (PR #68222)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov approved this pull request.


https://github.com/llvm/llvm-project/pull/68222
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits


@@ -146,6 +146,13 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fverify-intermediate-code`` and it's complement 
``-fno-verify-intermediate-code``.
+  Enables or disables verification of the generated LLVM IR.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.

mizvekov wrote:

FWIW, I am proposing this recommendation based on these numbers: 
https://llvm-compile-time-tracker.com/compare.php?from=634c0f8ea4acd0694d89c3e2d278e6bcb78b923f=49da7e1de6348f1c67a952e9cfea93abe920c4d5=instructions:u

It 'feels' to me like to me that cost is high enough that we shouldn't force 
enable it for simplicity, not even make it opt-out, because will take folks by 
surprise, but it's not really high enough that I wouldn't feel comfortable 
strongly recommending they try it.

https://github.com/llvm/llvm-project/pull/68172
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/68172
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68172

>From a5414db5e14cb40d062e54e780293cabc432197a Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [Clang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6f410c48bd1ffe9..62f939b54d3dd14 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,13 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fverify-intermediate-code`` and it's complement 
``-fno-verify-intermediate-code``.
+  Enables or disables verification of the generated LLVM IR.
+  Users can pass this to turn on extra verification to catch certain types of
+  compiler bugs at the cost of extra compile time.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 7f7024b4ddb50c1..08dd7c6d1bb67ff 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1909,6 +1909,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index fc3615245000109..c74f6ff447261dc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
+   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..ebe8a0520bf0fca 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fverify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-INTERMEDIATE-CODE %s
+// RUN: %clang -### -S -fno-verify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-INTERMEDIATE-CODE %s
+// CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
+// CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits


@@ -146,6 +146,13 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fverify-intermediate-code`` and it's complement 
``-fno-verify-intermediate-code``.
+  Enables or disables verification of the generated LLVM IR.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.

mizvekov wrote:

Okay, sounds good, I just implemented these changes to the document :)

https://github.com/llvm/llvm-project/pull/68172
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   6   >