[PATCH] D128112: [NFC] clang: Implement tests for PR56099

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov created this revision.
Herald added a project: All.
mizvekov updated this revision to Diff 438084.
mizvekov added a comment.
mizvekov published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

.


Signed-off-by: Matheus Izvekov 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128112

Files:
  clang/test/AST/ast-dump-template-decls.cpp


Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -127,3 +127,38 @@
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
 // CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent depth 0 index 0
 } // namespace PR55886
+
+namespace PR56099 {
+template  struct Y;
+template  using Z = Y;
+template  struct foo {
+  template  using bind = Z;
+};
+using t1 = foo::bind;
+// CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'Y' sugar Y
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+
+template  struct D {
+  template  using B = int(int (*...p)(T, U));
+};
+using t2 = D::B;
+// CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'B' sugar 
alias B
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (int (*)(float, int), int 
(*)(char, short))' cdecl
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (float, int)' cdecl
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent 
contains_unexpanded_pack depth 1 index 0 pack
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (char, short)' cdecl
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent 
contains_unexpanded_pack depth 1 index 0 pack
+} // namespace PR56099


Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -127,3 +127,38 @@
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
 // CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent depth 0 index 0
 } // namespace PR55886
+
+namespace PR56099 {
+template  struct Y;
+template  using Z = Y;
+template  struct foo {
+  template  using bind = Z;
+};
+using t1 = foo::bind;
+// CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'Y' sugar Y
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack
+
+template  struct D {
+  template  using B = int(int (*...p)(T, U));
+};
+using t2 = D::B;
+// CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'B' sugar alias B
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (int (*)(float, int), int (*)(char, short))' cdecl
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (float, int)' cdecl
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent contains_unexpanded_pack depth 0 index 0 pack
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent contains_unexpanded_pack depth 1 index 0 pack
+// CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (char, short)' cdecl
+// CHECK:  

[PATCH] D128113: Clang: fix AST representation of expanded template arguments.

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov created this revision.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
mizvekov updated this revision to Diff 438089.
mizvekov added a comment.
mizvekov published this revision for review.
mizvekov added reviewers: rsmith, v.g.vassilev.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

.


When expanding template argument packs, clang does not synthesize 
TemplateTypeParmTypes for the SubstTemplateTypeParmTypes which correspond to 
the argument's position in the expanded form.

Fixes PR56099.

Signed-off-by: Matheus Izvekov 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128113

Files:
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/AST/ast-dump-template-decls.cpp


Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -137,13 +137,13 @@
 using t1 = foo::bind;
 // CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'Y' sugar Y
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-0' dependent 
depth 0 index 0
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-1' dependent 
depth 0 index 1
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-2' dependent 
depth 0 index 2
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-3' dependent 
depth 0 index 3
 
 template  struct D {
   template  using B = int(int (*...p)(T, U));
@@ -153,12 +153,12 @@
 // CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (int (*)(float, int), int 
(*)(char, short))' cdecl
 // CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (float, int)' cdecl
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-0' dependent 
depth 0 index 0
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent 
contains_unexpanded_pack depth 1 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-1-0' dependent 
depth 1 index 0
 // CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (char, short)' cdecl
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent 
contains_unexpanded_pack depth 0 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-0-1' dependent 
depth 0 index 1
 // CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent 
contains_unexpanded_pack depth 1 index 0 pack
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'type-parameter-1-1' dependent 
depth 1 index 1
 } // namespace PR56099
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1839,9 +1839,18 @@
 
 QualType Replacement = Arg.getAsType();
 
-// TODO: only do this uniquing once, at the start of instantiation.
-QualType Result
-  = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
+QualType Result;
+if (T->isParameterPack()) {
+  QualType NewT = getSema().Context.getTemplateTypeParmType(
+  T->getDepth(),
+  T->getIndex() + getSema().ArgumentPackSubstitutionIndex, false);
+  Result = getSema().Context.getSubstTemplateTypeParmType(
+  cast(NewT), Replacement);
+} else {
+  // TODO: only do this uniquing once, at the start of instantiation.
+  Result = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
+}
+
 SubstTemplateTypeParmTypeLoc NewTL
   = TLB.push(Result);
 NewTL.setNameLoc(TL.getNameLoc());
@@ -1879,11 +1888,14 @@
 
   TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
   Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
-  QualType Result = Arg.getAsType();
 
-  Result = getSema().Context.getSubstTemplateTypeParmType(
-  

[PATCH] D113107: Support of expression granularity for _Float16.

2022-06-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:491
 
+- Support for ``AVX512-FP16`` instructions has been added.
+- Support for ``_Float16`` type has been added.

This line doesn't need anymore.



Comment at: clang/lib/Basic/Targets/X86.cpp:242
   HasAVX512FP16 = true;
   HasFloat16 = true;
+  HasLegalHalfType = true;

`HasFloat16 = true` can be removed. `+avx512fp16` implies `+avx512f` thus 
`SSELevel >= SSE2`



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:896
+
+ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E) {
+  if (auto *BinOp = dyn_cast(E->IgnoreParens())) {

rjmccall wrote:
> zahiraam wrote:
> > rjmccall wrote:
> > > `EmitPromoted` should take the promotion type.
> > > 
> > > You are missing the logic in this file which handles *unpromoted* 
> > > emission (where you have a binary operator but the context wants an 
> > > unpromoted value) by recognizing that you need to do a promoted operation 
> > > and then truncate.
> > Sorry but not sure what you mean here. A case where we don't want any 
> > promotion would be:
> > 
> > float _Complex add(float _Complex a, float _Complex b) {
> >   return a + b;
> > }
> > 
> > In this case, getPromotionType would return the null type and EmitBinOps 
> > would just go through the  "older" control path where there is no promotion.
> > Unless I misunderstood your comment?
> > 
> > 
> I'm talking about the unpromoted emission path for an operation that we want 
> to *internally* promote.  So like your example but using `_Float16` — we want 
> to emit the binary `+` as a `float` operation, but the context needs an 
> unpromoted value because it's going to be returned.
> 
> The promoted emission path (the various `EmitPromoted` methods) represents a 
> request by the caller to produce a result that doesn't match the formal type 
> of the expression.  The normal emission path `Visit` etc.) represents a 
> request by the caller to produce a result normally, i.e. one that matches the 
> formal type.  In general, we always start in the latter because arbitrary 
> contexts always expect a value of the formal type; it's only these recursive 
> calls within promoted emitters that contextually want a promoted value.
> 
> In your current patch, you're entering the promoted path by special-casing 
> one context that frequently terminates promoted emission: 
> `EmitComplexExprIntoLValue`, which is used for things like assignment.  
> That's not the right way to handle it, though.  Instead, you should do like I 
> asked you to do with the scalar emitter, which is to recognize in the normal 
> emission path for a promotable operation (like binary `+`) that you need to 
> promote the operation and then unpromote the result.  Then things like 
> `EmitComplexExprIntoLValue` will continue to simply enter the normal path 
> because that's the kind of value they need, and the promotion logic will do 
> the right thing from there to ensure we don't emit a `_Float16` operation in 
> LLVM IR.
> 
> Incidentally, I thought of another context that you ought to do promotion 
> for: when we're converting a promotable value to a larger floating-point 
> type, we should presumably convert the promoted value directly rather than 
> truncating it to the unpromoted type before the conversion.
I'm not familiar with the FE details, but I understand the background is just 
to promote expressions that have more than one operation. So I agree with 
@zahiraam, and
> to ensure we don't emit a _Float16 operation in LLVM IR
is not what we expected here.

`_Float16` is a ABI type for which a target supported has to lower any 
`_Float16` operations in LLVM IR. See what we have done on X86 backend by 
D107082.

That said, a single `a + b` can be and should be emitted as `%c = fadd half %a, 
%b`.



Comment at: clang/test/CodeGen/X86/Float16-arithmetic.c:11-15
+  // CHECK: fpext half {{.*}} to float
+  // CHECK: load half, ptr {{.*}}
+  // CHECK: fpext half {{.*}} to float
+  // CHECK: fadd float {{.*}}, {{.*}}
+  // CHECK: fptrunc float {{.*}} to half

So what we expected is emitting `fadd half {{.*}}, {{.*}}` only. The same for 
mul and div.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113107/new/

https://reviews.llvm.org/D113107

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


[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/openbsd.c:133
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"

It's useful to check other values like the `-m` emulation and the dynamic 
linker.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

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


[PATCH] D128095: clang: fix checking parameter packs for expansion

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov created this revision.
Herald added a project: All.
mizvekov updated this revision to Diff 438073.
mizvekov retitled this revision from "clang: fix pack substitution scope in 
function params" to "clang: fix checking parameter packs for expansion.".
mizvekov edited the summary of this revision.
mizvekov added a comment.
Herald added a subscriber: kristof.beyls.
mizvekov retitled this revision from "clang: fix checking parameter packs for 
expansion." to "clang: fix checking parameter packs for expansion".
mizvekov published this revision for review.
mizvekov added reviewers: rsmith, v.g.vassilev.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

.


CollectUnexpandedParameterPacksVisitor and CheckParameterPacksForExpansion
should analyze SubstTemplateTypeParmPackType for unexpanded packs as
well.

Fixes PR56094.

Signed-off-by: Matheus Izvekov 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128095

Files:
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/SemaInternal.h
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateVariadic.cpp
  clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp

Index: clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
+++ clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
@@ -469,3 +469,14 @@
   bar(b);
 }
 }
+
+namespace pr56094 {
+template  struct D {
+  template  using B = int(int (*...p)(T, U));
+  // expected-error@-1 {{pack expansion contains parameter packs 'T' and 'U' that have different lengths (1 vs. 2)}}
+  template  D(B *);
+  // expected-note@-1 {{in instantiation of template type alias 'B' requested here}}
+};
+using t1 = D::B;
+// expected-note@-1 {{in instantiation of template class 'pr56094::D' requested here}}
+} // namespace pr56094
Index: clang/lib/Sema/SemaTemplateVariadic.cpp
===
--- clang/lib/Sema/SemaTemplateVariadic.cpp
+++ clang/lib/Sema/SemaTemplateVariadic.cpp
@@ -52,6 +52,10 @@
 
   Unexpanded.push_back({ND, Loc});
 }
+void addUnexpanded(const SubstTemplateTypeParmPackType *T,
+   SourceLocation Loc = SourceLocation()) {
+  Unexpanded.push_back({T, Loc});
+}
 void addUnexpanded(const TemplateTypeParmType *T,
SourceLocation Loc = SourceLocation()) {
   if (T->getDepth() < DepthLimit)
@@ -88,6 +92,11 @@
   return true;
 }
 
+bool VisitSubstTemplateTypeParmPackType(SubstTemplateTypeParmPackType *T) {
+  addUnexpanded(T);
+  return true;
+}
+
 /// Record occurrences of function and non-type template
 /// parameter packs in an expression.
 bool VisitDeclRefExpr(DeclRefExpr *E) {
@@ -306,7 +315,8 @@
   auto *TTPD = dyn_cast(LocalPack);
   return TTPD && TTPD->getTypeForDecl() == TTPT;
 }
-return declaresSameEntity(Pack.first.get(), LocalPack);
+return declaresSameEntity(Pack.first.get(),
+  LocalPack);
   };
   if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack))
 LambdaParamPackReferences.push_back(Pack);
@@ -358,7 +368,7 @@
   = Unexpanded[I].first.dyn_cast())
   Name = TTP->getIdentifier();
 else
-  Name = Unexpanded[I].first.get()->getIdentifier();
+  Name = Unexpanded[I].first.get()->getIdentifier();
 
 if (Name && NamesKnown.insert(Name).second)
   Names.push_back(Name);
@@ -421,7 +431,7 @@
   llvm::SmallPtrSet ParmSet(Parms.begin(), Parms.end());
   SmallVector UnexpandedParms;
   for (auto Parm : Unexpanded)
-if (ParmSet.contains(Parm.first.dyn_cast()))
+if (ParmSet.contains(Parm.first.dyn_cast()))
   UnexpandedParms.push_back(Parm);
   if (UnexpandedParms.empty())
 return false;
@@ -681,42 +691,45 @@
 // Compute the depth and index for this parameter pack.
 unsigned Depth = 0, Index = 0;
 IdentifierInfo *Name;
-bool IsVarDeclPack = false;
+unsigned NewPackSize;
+bool NotPack = true;
 
-if (const TemplateTypeParmType *TTP =
+if (const auto *TTP =
 ParmPack.first.dyn_cast()) {
   Depth = TTP->getDepth();
   Index = TTP->getIndex();
   Name = TTP->getIdentifier();
+} else if (const auto *STP =
+   ParmPack.first
+   .dyn_cast()) {
+  NewPackSize = STP->getNumArgs();
+  Name = STP->getIdentifier();
+  NotPack = false;
 } else {
-  NamedDecl *ND = ParmPack.first.get();
-  if (isa(ND))
-IsVarDeclPack = true;
-  else
+  const auto *ND = ParmPack.first.get();
+  if (isa(ND)) {
+// Figure out whether we're instantiating to an argument pack or not.
+using DeclArgumentPack = LocalInstantiationScope::DeclArgumentPack;
+llvm::PointerUnion *Instantiation =
+

[PATCH] D125936: [Sema] Relax an assertion in BuildStmtExpr

2022-06-17 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8fc3d719eee7: Stop wrapping GCCAsmStmts inside StmtExprs to 
destruct temporaries (authored by ahatanak).

Changed prior to commit:
  https://reviews.llvm.org/D125936?vs=437796=438076#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125936/new/

https://reviews.llvm.org/D125936

Files:
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/CodeGenCXX/asm.cpp
  clang/test/CodeGenObjC/asm.m
  clang/test/SemaTemplate/instantiate-expr-1.cpp

Index: clang/test/SemaTemplate/instantiate-expr-1.cpp
===
--- clang/test/SemaTemplate/instantiate-expr-1.cpp
+++ clang/test/SemaTemplate/instantiate-expr-1.cpp
@@ -190,3 +190,19 @@
 test_asm_tied(1.f); // expected-note {{instantiation of}}
   }
 }
+
+namespace TestAsmCleanup {
+struct S {
+  operator int() const { return 1; }
+  ~S();
+};
+
+template 
+void foo() {
+  __asm__ __volatile__("%[i]"
+   :
+   : [i] "r"(-S()));
+}
+
+void test() { foo(); }
+} // namespace TestAsmCleanup
Index: clang/test/CodeGenObjC/asm.m
===
--- /dev/null
+++ clang/test/CodeGenObjC/asm.m
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fblocks -fobjc-arc -emit-llvm -o - %s | FileCheck %s
+
+// CHECK: %[[STRUCT_A:.*]] = type { ptr }
+
+typedef struct {
+  id f;
+} A;
+
+id a;
+
+// Check that the compound literal is destructed at the end of the enclosing scope.
+
+// CHECK-LABEL: define void @foo0()
+// CHECK: %[[_COMPOUNDLITERAL:.*]] = alloca %[[STRUCT_A]], align 8
+// CHECK: getelementptr inbounds %[[STRUCT_A]], ptr %[[_COMPOUNDLITERAL]], i32 0, i32 0
+// CHECK: %[[F1:.*]] = getelementptr inbounds %[[STRUCT_A]], ptr %[[_COMPOUNDLITERAL]], i32 0, i32 0
+// CHECK: %[[V2:.*]] = load ptr, ptr %[[F1]], align 8
+// CHECK: call void asm sideeffect "", "r,~{dirflag},~{fpsr},~{flags}"(ptr %[[V2]])
+// CHECK: call void asm sideeffect "",
+// CHECK: call void @__destructor_8_s0(ptr %[[_COMPOUNDLITERAL]])
+
+void foo0() {
+  asm("" : : "r"(((A){a}).f) );
+  asm("");
+}
Index: clang/test/CodeGenCXX/asm.cpp
===
--- clang/test/CodeGenCXX/asm.cpp
+++ clang/test/CodeGenCXX/asm.cpp
@@ -1,4 +1,6 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple i386-unknown-unknown -fblocks -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: %[[STRUCT_A:.*]] = type { i8 }
 
 struct A
 {
@@ -12,3 +14,39 @@
 asm("" : : "r"(foo(a)) ); // rdar://8540491
 // CHECK: call void @_ZN1AD1Ev
 }
+
+namespace TestTemplate {
+// Check that the temporary is destructed after the first asm statement.
+
+// CHECK: define {{.*}}void @_ZN12TestTemplate4foo0IvEEvR1A(
+// CHECK: %[[AGG_TMP:.*]] = alloca %[[STRUCT_A]],
+// CHECK: %[[CALL:.*]] = call noundef i32 @_Z3foo1A({{.*}}%[[AGG_TMP]])
+// CHECK: call void asm sideeffect "", "r,~{dirflag},~{fpsr},~{flags}"(i32 %[[CALL]])
+// CHECK: call void @_ZN1AD1Ev({{.*}}%[[AGG_TMP]])
+// CHECK: call void asm sideeffect "",
+
+template 
+void foo0(A ) {
+  asm("" : : "r"(foo(a)) );
+  asm("");
+}
+
+void test0(A ) { foo0(a); }
+
+// Check that the block capture is destructed at the end of the enclosing scope.
+
+// CHECK: define {{.*}}void @_ZN12TestTemplate4foo1IvEEv1A(
+// CHECK: %[[BLOCK:.*]] = alloca <{ ptr, i32, i32, ptr, ptr, %[[STRUCT_A]] }>, align 4
+// CHECK: %[[BLOCK_CAPTURED:.*]] = getelementptr inbounds <{ ptr, i32, i32, ptr, ptr, %[[STRUCT_A]] }>, ptr %[[BLOCK]], i32 0, i32 5
+// CHECK: call void asm sideeffect "", "r,~{dirflag},~{fpsr},~{flags}"(i32 %{{.*}})
+// CHECK: call void asm sideeffect "", "~{dirflag},~{fpsr},~{flags}"()
+// CHECK: call void @_ZN1AD1Ev({{.*}} %[[BLOCK_CAPTURED]])
+
+template 
+void foo1(A a) {
+  asm("" : : "r"(^{ (void)a; return 0; }()));
+  asm("");
+}
+
+void test1(A ) { foo1(a); }
+} // namespace TestTemplate
Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -733,6 +733,9 @@
   }
   if (NS->isAsmGoto())
 setFunctionHasBranchIntoScope();
+
+  CleanupVarDeclMarking();
+  DiscardCleanupsInEvaluationContext();
   return NS;
 }
 
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -325,7 +325,6 @@
 ProhibitAttributes(GNUAttrs);
 bool msAsm = false;
 Res = ParseAsmStatement(msAsm);
-Res = Actions.ActOnFinishFullStmt(Res.get());
 if (msAsm) return Res;
 SemiError = "asm";
 break;
Index: clang/lib/CodeGen/CGStmt.cpp

[clang] 8fc3d71 - Stop wrapping GCCAsmStmts inside StmtExprs to destruct temporaries

2022-06-17 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-06-17T17:28:00-07:00
New Revision: 8fc3d719eee7ab41641506cbdc59f3ade0eb36e4

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

LOG: Stop wrapping GCCAsmStmts inside StmtExprs to destruct temporaries

Instead, just pop the cleanups at the end of the asm statement.

This fixes an assertion failure in BuildStmtExpr. It also fixes a bug
where blocks and C compound literals were destructed at the end of the
asm statement instead of at the end of the enclosing scope.

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

Added: 
clang/test/CodeGenObjC/asm.m

Modified: 
clang/lib/CodeGen/CGStmt.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaStmtAsm.cpp
clang/test/CodeGenCXX/asm.cpp
clang/test/SemaTemplate/instantiate-expr-1.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 2412c91d16fb..f3564eb78707 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -2289,6 +2289,9 @@ static void UpdateAsmCallInst(llvm::CallBase , 
bool HasSideEffect,
 }
 
 void CodeGenFunction::EmitAsmStmt(const AsmStmt ) {
+  // Pop all cleanup blocks at the end of the asm statement.
+  CodeGenFunction::RunCleanupsScope Cleanups(*this);
+
   // Assemble the final asm string.
   std::string AsmString = S.generateAsmString(getContext());
 

diff  --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp
index f43e5b4c8922..1f6c74aeae7e 100644
--- a/clang/lib/Parse/ParseStmt.cpp
+++ b/clang/lib/Parse/ParseStmt.cpp
@@ -325,7 +325,6 @@ StmtResult 
Parser::ParseStatementOrDeclarationAfterAttributes(
 ProhibitAttributes(GNUAttrs);
 bool msAsm = false;
 Res = ParseAsmStatement(msAsm);
-Res = Actions.ActOnFinishFullStmt(Res.get());
 if (msAsm) return Res;
 SemiError = "asm";
 break;

diff  --git a/clang/lib/Sema/SemaStmtAsm.cpp b/clang/lib/Sema/SemaStmtAsm.cpp
index c147d26b2dff..1aa71fa75946 100644
--- a/clang/lib/Sema/SemaStmtAsm.cpp
+++ b/clang/lib/Sema/SemaStmtAsm.cpp
@@ -733,6 +733,9 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, 
bool IsSimple,
   }
   if (NS->isAsmGoto())
 setFunctionHasBranchIntoScope();
+
+  CleanupVarDeclMarking();
+  DiscardCleanupsInEvaluationContext();
   return NS;
 }
 

diff  --git a/clang/test/CodeGenCXX/asm.cpp b/clang/test/CodeGenCXX/asm.cpp
index 3b745a7336f2..bc639a2be587 100644
--- a/clang/test/CodeGenCXX/asm.cpp
+++ b/clang/test/CodeGenCXX/asm.cpp
@@ -1,4 +1,6 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck 
%s
+// RUN: %clang_cc1 -triple i386-unknown-unknown -fblocks -emit-llvm %s -o - | 
FileCheck %s
+
+// CHECK: %[[STRUCT_A:.*]] = type { i8 }
 
 struct A
 {
@@ -12,3 +14,39 @@ void bar(A )
 asm("" : : "r"(foo(a)) ); // rdar://8540491
 // CHECK: call void @_ZN1AD1Ev
 }
+
+namespace TestTemplate {
+// Check that the temporary is destructed after the first asm statement.
+
+// CHECK: define {{.*}}void @_ZN12TestTemplate4foo0IvEEvR1A(
+// CHECK: %[[AGG_TMP:.*]] = alloca %[[STRUCT_A]],
+// CHECK: %[[CALL:.*]] = call noundef i32 @_Z3foo1A({{.*}}%[[AGG_TMP]])
+// CHECK: call void asm sideeffect "", "r,~{dirflag},~{fpsr},~{flags}"(i32 
%[[CALL]])
+// CHECK: call void @_ZN1AD1Ev({{.*}}%[[AGG_TMP]])
+// CHECK: call void asm sideeffect "",
+
+template 
+void foo0(A ) {
+  asm("" : : "r"(foo(a)) );
+  asm("");
+}
+
+void test0(A ) { foo0(a); }
+
+// Check that the block capture is destructed at the end of the enclosing 
scope.
+
+// CHECK: define {{.*}}void @_ZN12TestTemplate4foo1IvEEv1A(
+// CHECK: %[[BLOCK:.*]] = alloca <{ ptr, i32, i32, ptr, ptr, %[[STRUCT_A]] }>, 
align 4
+// CHECK: %[[BLOCK_CAPTURED:.*]] = getelementptr inbounds <{ ptr, i32, i32, 
ptr, ptr, %[[STRUCT_A]] }>, ptr %[[BLOCK]], i32 0, i32 5
+// CHECK: call void asm sideeffect "", "r,~{dirflag},~{fpsr},~{flags}"(i32 
%{{.*}})
+// CHECK: call void asm sideeffect "", "~{dirflag},~{fpsr},~{flags}"()
+// CHECK: call void @_ZN1AD1Ev({{.*}} %[[BLOCK_CAPTURED]])
+
+template 
+void foo1(A a) {
+  asm("" : : "r"(^{ (void)a; return 0; }()));
+  asm("");
+}
+
+void test1(A ) { foo1(a); }
+} // namespace TestTemplate

diff  --git a/clang/test/CodeGenObjC/asm.m b/clang/test/CodeGenObjC/asm.m
new file mode 100644
index ..6901416f028b
--- /dev/null
+++ b/clang/test/CodeGenObjC/asm.m
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fblocks -fobjc-arc 
-emit-llvm -o - %s | FileCheck %s
+
+// CHECK: %[[STRUCT_A:.*]] = type { ptr }
+
+typedef struct {
+  id f;
+} A;
+
+id a;
+
+// Check that the compound literal is destructed at the end of the enclosing 
scope.
+
+// CHECK-LABEL: define void @foo0()
+// CHECK: %[[_COMPOUNDLITERAL:.*]] = alloca %[[STRUCT_A]], align 8
+// CHECK: 

[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Brad Smith via Phabricator via cfe-commits
brad updated this revision to Diff 438075.
brad added a comment.

Fix the test.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

Files:
  clang/lib/Driver/ToolChains/OpenBSD.cpp
  clang/test/Driver/openbsd.c


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,8 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,8 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127207: [flang][driver] Fix support for `-x`

2022-06-17 Thread Sunho Kim via Phabricator via cfe-commits
sunho added a comment.

Hi! I'm not exactly sure what's going on. But, seems like build is failing 
here? https://lab.llvm.org/buildbot/#/builders/177/builds/5571


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127207/new/

https://reviews.llvm.org/D127207

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


[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Brad Smith via Phabricator via cfe-commits
brad updated this revision to Diff 438071.
brad added a comment.

Minus the new white space.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

Files:
  clang/lib/Driver/ToolChains/OpenBSD.cpp
  clang/test/Driver/openbsd.c


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,8 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,8 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Brad Smith via Phabricator via cfe-commits
brad updated this revision to Diff 438070.
brad added a comment.

Add a test.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

Files:
  clang/lib/Driver/ToolChains/OpenBSD.cpp
  clang/test/Driver/openbsd.c


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,12 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
+
+
+
+
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());


Index: clang/test/Driver/openbsd.c
===
--- clang/test/Driver/openbsd.c
+++ clang/test/Driver/openbsd.c
@@ -126,3 +126,12 @@
 // RUN: FileCheck -check-prefix=UNWIND-TABLES %s
 // UNWIND-TABLES: "-funwind-tables=2"
 // NO-UNWIND-TABLES-NOT: "-funwind-tables=2"
+
+// Check that the -X flag is passed to the linker on riscv64
+// RUN: %clang --target=riscv64-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RISCV64-FLAGS %s
+// CHECK-RISCV64-FLAGS: "-X"
+
+
+
+
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-06-17 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

In D123319#3517966 , @dblaikie wrote:

> In D123319#3506745 , @shafik wrote:
>
>> 
>
> What does the linkage name do for your use case? Which cases are missing 
> linkage names/where do they go missing?
>
>> I am happy to consider other approaches as well to solving lookup for local 
>> lambdas for D105564 . Let me know what you 
>> think.
>
> Why does the return type help perform lookup? What kind of lookup?
>
> (again, my take is that "auto" return types probably shouldn't be described 
> at all - we should just not describe functions where we don't know their 
> return types because they're not very useful to know about (overload 
> resolution, yes, but then you can't call them anyway) - but that's a broader 
> argument to make/change to make)

IIUC, the motivating problem is (@shafik please correct me if this isn't it) 
this:

  $ cat /tmp/lambda.cpp 
  #include 
  int main() {
auto f = [](){ printf("hi from lambda\n"); return 1;} ;
f();
f();
return f();
  }
  $ clang++ -g /tmp/lambda.cpp -o /tmp/a.out
  $ lldb /tmp/a.out
  (lldb) b 5
  (lldb) r
  (lldb) p f()
  hi from lambda
  (lldb) p auto val = f()
  error: expression failed to parse:
  error: :1:6: variable has incomplete type 'void'
  auto val = f()
   ^

LLDB can't determine the return type of the lambda, because it has trouble 
matching up the abstract specification (with the `auto` return type) with the 
concrete definition (with the `int` return type):

  $ dwarfdump --name "operator()" /tmp/a.out.dSYM -p -c
  /tmp/a.out.dSYM/Contents/Resources/DWARF/a.out:   file format Mach-O arm64
  
  0x000b: DW_TAG_compile_unit
DW_AT_producer  ("Apple clang version 13.1.6 
(clang-1316.0.21.2)")
DW_AT_language  (DW_LANG_C_plus_plus_14)
DW_AT_name  ("/tmp/lambda.cpp")
DW_AT_LLVM_sysroot  
("/Library/Developer/CommandLineTools/SDKs/MacOSX13.0.sdk")
DW_AT_APPLE_sdk ("MacOSX13.0.sdk")
DW_AT_stmt_list (0x)
DW_AT_comp_dir  ("/Volumes/Data/swift")
DW_AT_low_pc(0x00013f28)
DW_AT_high_pc   (0x00013f98)
  
  0x07c6:   DW_TAG_subprogram
  DW_AT_low_pc  (0x00013f28)
  DW_AT_high_pc (0x00013f6c)
  DW_AT_frame_base  (DW_OP_reg29 W29)
  DW_AT_name("main")
  DW_AT_decl_file   ("/tmp/lambda.cpp")
  DW_AT_decl_line   (2)
  DW_AT_type(0x029f "int")
  DW_AT_external(true)
  
  0x07ed: DW_TAG_class_type
DW_AT_calling_convention(DW_CC_pass_by_value)
DW_AT_byte_size (0x01)
DW_AT_decl_file ("/tmp/lambda.cpp")
DW_AT_decl_line (3)
  
  0x07f2:   DW_TAG_subprogram
  DW_AT_name("operator()")
  DW_AT_decl_file   ("/tmp/lambda.cpp")
  DW_AT_decl_line   (3)
  DW_AT_type(0x0806 "auto")
  DW_AT_declaration (true)
  DW_AT_accessibility   (DW_ACCESS_public)
  
  0x07fe: DW_TAG_formal_parameter
DW_AT_type  (0x080b "const class *")
DW_AT_artificial(true)
  
  0x0803: NULL
  
  0x000b: DW_TAG_compile_unit
DW_AT_producer  ("Apple clang version 13.1.6 
(clang-1316.0.21.2)")
DW_AT_language  (DW_LANG_C_plus_plus_14)
DW_AT_name  ("/tmp/lambda.cpp")
DW_AT_LLVM_sysroot  
("/Library/Developer/CommandLineTools/SDKs/MacOSX13.0.sdk")
DW_AT_APPLE_sdk ("MacOSX13.0.sdk")
DW_AT_stmt_list (0x)
DW_AT_comp_dir  ("/Volumes/Data/swift")
DW_AT_low_pc(0x00013f28)
DW_AT_high_pc   (0x00013f98)
  
  0x0815:   DW_TAG_subprogram
  DW_AT_low_pc  (0x00013f6c)
  DW_AT_high_pc (0x00013f98)
  DW_AT_frame_base  (DW_OP_reg29 W29)
  DW_AT_object_pointer  (0x0834)
  DW_AT_type(0x029f "int")
  DW_AT_linkage_name("_ZZ4mainENK3$_0clEv")
  DW_AT_specification   (0x07f2 "operator()")
  
  0x0834: DW_TAG_formal_parameter
DW_AT_location  (DW_OP_breg31 WSP+8)
DW_AT_name  ("this")
DW_AT_type  (0x0841 "const class *")
DW_AT_artificial(true)
  
  0x0840: NULL


Repository:
  rG LLVM Github 

[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Brad Smith via Phabricator via cfe-commits
brad added a comment.

I will add a test.




Comment at: clang/lib/Driver/ToolChains/OpenBSD.cpp:159
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");

MaskRay wrote:
> isRISCV
> 
> If OpenBSD gets riscv32, it'd need -X, too.
There is no interest in further 32-bit archs.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

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


[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

Please add a test.




Comment at: clang/lib/Driver/ToolChains/OpenBSD.cpp:159
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");

isRISCV

If OpenBSD gets riscv32, it'd need -X, too.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128109/new/

https://reviews.llvm.org/D128109

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


[PATCH] D128064: [Static Analyzer] Small array binding policy

2022-06-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Another magic number around these parts is 4, which is our loop iteration 
budget. If an array is initialized by a loop with unknown bounds, it'll have 4 
bindings. So I think it makes sense to reduce the default to 4 just because 
weird things may start happening above this threshold.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128064/new/

https://reviews.llvm.org/D128064

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


[PATCH] D128109: [Driver] Pass -X to ld for riscv64-openbsd

2022-06-17 Thread Brad Smith via Phabricator via cfe-commits
brad created this revision.
brad added a reviewer: MaskRay.
brad added a project: clang.
Herald added subscribers: sunshaoce, VincentWu, luke957, StephenFan, vkmr, 
evandro, sameer.abuasal, s.egerton, Jim, benna, psnobl, PkmX, rogfer01, 
shiva0217, kito-cheng, simoncook, krytarowski, arichardson.
Herald added a project: All.
brad requested review of this revision.
Herald added subscribers: pcwang-thead, eopXD.

Noticing https://reviews.llvm.org/D127826, add support for OpenBSD which uses 
lld on riscv64.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128109

Files:
  clang/lib/Driver/ToolChains/OpenBSD.cpp


Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());


Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
===
--- clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -156,6 +156,9 @@
   if (Args.hasArg(options::OPT_nopie) || Args.hasArg(options::OPT_pg))
 CmdArgs.push_back("-nopie");
 
+  if (ToolChain.getArch() == llvm::Triple::riscv64)
+CmdArgs.push_back("-X");
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128103: Adds AST Matcher for ObjCStringLiteral

2022-06-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Matcher tests are written as unittests in `unittests/ASTMatchers`, I don't 
think you need to make an entire new check for that hmmm.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128103/new/

https://reviews.llvm.org/D128103

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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/compilation_database_multiarch.c:15
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF

jansvoboda11 wrote:
> MaskRay wrote:
> > CHECK-EMPTY can match EOF.
> It can, but it's not really strict. It will match an empty line, but that 
> might be followed by some non-empty lines, which I'd like this test to 
> explicitly disallow.
OK. I think `CHECk-NOT: {{.}}` works as well once the last byte before \n is 
matched.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128098/new/

https://reviews.llvm.org/D128098

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


[PATCH] D127142: [HIP] Link with clang_rt.builtins

2022-06-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D127142#3592207 , @yaxunl wrote:

> In D127142#3590874 , @yaxunl wrote:
>
>> In D127142#3571260 , @MaskRay 
>> wrote:
>>
>>> In D127142#3570290 , @yaxunl 
>>> wrote:
>>>
 If I use --rtlib=compiler-rt, does that also requires 
 --unwindlib=unwindlib ?
>>>
>>> No. --unwindlib=libunwind requires --rtlib=compiler-rt. --rtlib=compiler-rt 
>>> is compatible with both --unwindlib=libgcc and --unwindlib=libunwind.
>>
>> If only use -rtlib=compiler-rt without changing unwind lib, I will get 
>> missing symbol:
>>
>> [2022-06-16T20:05:28.644Z] ld.lld: error: undefined symbol: _Unwind_Resume
>>
>> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>>
>> [2022-06-16T20:05:28.644Z] >>>   
>> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(generate_skipahead_file())
>>
>> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>>
>> [2022-06-16T20:05:28.644Z] >>>   
>> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(main)
>>
>> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>>
>> [2022-06-16T20:05:28.644Z] >>>   
>> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(std::function> bool&)> reduce::ReduceOpFn2(miopenReduceTensorOp_t))
>>
>> [2022-06-16T20:05:28.644Z] >>> referenced 1246 more times
>>
>> [2022-06-16T20:05:28.644Z]
>>
>> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
>> undefined reference to _Unwind_Resume [--no-allow-shlib-undefined]
>>
>> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
>> undefined reference to _Unwind_Backtrace [--no-allow-shlib-undefined]
>>
>> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
>> undefined reference to _Unwind_GetIP [--no-allow-shlib-undefined]
>>
>> [2022-06-16T20:05:28.644Z] clang-15: error: linker command failed with exit 
>> code 1 (use -v to see invocation)
>
> If I use --rtlib=compiler-rt, do I have to explicitly add --unwindlib=libgcc 
> or --unwindlib=libunwind? I suspect the linker is not linking the unwind 
> library when -rtlib=compiler-rt is specified.

Either is fine.

If --rtlib=libgcc, --unwindlib must be libgcc (platform defaults to libgcc on 
Linux).

--rtlib and --unwindlib are orthogonal. To use libunwind, specify --unwindlib.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127142/new/

https://reviews.llvm.org/D127142

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


[PATCH] D128103: Adds AST Matcher for ObjCStringLiteral

2022-06-17 Thread Rashmi Mudduluru via Phabricator via cfe-commits
t-rasmud created this revision.
t-rasmud added reviewers: NoQ, usama54321.
Herald added subscribers: carlosgalvezp, mgorny.
Herald added a project: All.
t-rasmud requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128103

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MatchObjcStringLiteralCheck.cpp
  clang-tools-extra/clang-tidy/misc/MatchObjcStringLiteralCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/match-objc-string-literal.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-match-objc-string-literal.m
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp

Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -548,6 +548,7 @@
   REGISTER_MATCHER(stmt);
   REGISTER_MATCHER(stmtExpr);
   REGISTER_MATCHER(stringLiteral);
+  REGISTER_MATCHER(objCStringLiteral);
   REGISTER_MATCHER(substNonTypeTemplateParmExpr);
   REGISTER_MATCHER(substTemplateTypeParmType);
   REGISTER_MATCHER(switchCase);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -917,6 +917,7 @@
 const internal::VariadicDynCastAllOfMatcher
 cxxBoolLiteral;
 const internal::VariadicDynCastAllOfMatcher stringLiteral;
+const internal::VariadicDynCastAllOfMatcher objCStringLiteral;
 const internal::VariadicDynCastAllOfMatcher
 characterLiteral;
 const internal::VariadicDynCastAllOfMatcher
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -1515,6 +1515,9 @@
 extern const internal::VariadicDynCastAllOfMatcher
 objcMessageExpr;
 
+extern const internal::VariadicDynCastAllOfMatcher
+objCStringLiteral;
+
 /// Matches Objective-C interface declarations.
 ///
 /// Example matches Foo
Index: clang-tools-extra/test/clang-tidy/checkers/misc-match-objc-string-literal.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-match-objc-string-literal.m
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s misc-match-objc-string-literal %t
+@interface NSObject
+@end
+
+@interface NSString
+@end
+
+@interface Test : NSObject
++ (void)someFunction:(NSString *)Desc;
+@end
+
+@implementation Test
++ (void)someFunction:(NSString *)Desc {
+return;
+}
+- (void) foo {
+[Test someFunction:@"Ola!"];
+}
+@end
Index: clang-tools-extra/docs/clang-tidy/checks/misc/match-objc-string-literal.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc/match-objc-string-literal.rst
@@ -0,0 +1,6 @@
+.. title:: clang-tidy - misc-match-objc-string-literal
+
+misc-match-objc-string-literal
+==
+
+FIXME: Matches all ObjCStringLiteral types.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -123,6 +123,11 @@
Warns when the code is unwrapping a `std::optional`, `absl::optional`,
or `base::Optional` object without assuring that it contains a value.
 
+- New :doc:`misc-match-objc-string-literal
+  ` check.
+
+  Matches ObjCStringLiteral type.
+
 - New :doc:`modernize-macro-to-enum
   ` check.
 
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "DefinitionsInHeadersCheck.h"
+#include "MatchObjcStringLiteralCheck.h"
 #include "MisleadingBidirectional.h"
 #include "MisleadingIdentifier.h"
 #include "MisplacedConstCheck.h"
@@ -35,6 +36,8 @@
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
 "misc-definitions-in-headers");
+CheckFactories.registerCheck(
+"misc-match-objc-string-literal");
 CheckFactories.registerCheck(
 "misc-misleading-bidirectional");
 CheckFactories.registerCheck(
Index: clang-tools-extra/clang-tidy/misc/MatchObjcStringLiteralCheck.h

[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-06-17 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D123319#3546535 , @dblaikie wrote:

> In D123319#3532811 , @dblaikie 
> wrote:
>
>> Ping
>
> @aprantl thoughts on this?

Ping


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123319/new/

https://reviews.llvm.org/D123319

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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128098/new/

https://reviews.llvm.org/D128098

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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG92c6ffa14cde: [clang][driver] Ensure we dont 
accumulate entries in -MJ files (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128098/new/

https://reviews.llvm.org/D128098

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/compilation_database_multiarch.c


Index: clang/test/Driver/compilation_database_multiarch.c
===
--- clang/test/Driver/compilation_database_multiarch.c
+++ clang/test/Driver/compilation_database_multiarch.c
@@ -2,7 +2,14 @@
 
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+
+// Let's run that again and verify we're not accumulating redundant entries in 
the same file.
+//
+// RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+// RUN: echo EOF >> %t/compilation_database.json
+
 // RUN: FileCheck --input-file=%t/compilation_database.json %s
 
 // CHECK:  { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_X86_64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_X86_64]]", {{.*}} 
"--target=x86_64-apple-macosx12.0.0"]},
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -1314,6 +1314,10 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Remove existing compilation database so that each job can append to it.
+  if (Arg *A = Args.getLastArg(options::OPT_MJ))
+llvm::sys::fs::remove(A->getValue());
+
   // Setting up the jobs for some precompile cases depends on whether we are
   // treating them as PCH, implicit modules or C++20 ones.
   // TODO: inferring the mode like this seems fragile (it meets the objective


Index: clang/test/Driver/compilation_database_multiarch.c
===
--- clang/test/Driver/compilation_database_multiarch.c
+++ clang/test/Driver/compilation_database_multiarch.c
@@ -2,7 +2,14 @@
 
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch x86_64 -MJ %t/compilation_database.json
+
+// Let's run that again and verify we're not accumulating redundant entries in the same file.
+//
+// RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch x86_64 -MJ %t/compilation_database.json
+// RUN: echo EOF >> %t/compilation_database.json
+
 // RUN: FileCheck --input-file=%t/compilation_database.json %s
 
 // CHECK:  { "directory": "{{.*}}", "file": "{{.*}}", "output": "[[OUTPUT_X86_64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_X86_64]]", {{.*}} "--target=x86_64-apple-macosx12.0.0"]},
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": "[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} "--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -1314,6 +1314,10 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Remove existing compilation database so that each job can append to it.
+  if (Arg *A = Args.getLastArg(options::OPT_MJ))
+llvm::sys::fs::remove(A->getValue());
+
   // Setting up the jobs for some precompile cases depends on whether we are
   // treating them as PCH, implicit modules or C++20 ones.
   // TODO: inferring the mode like this seems fragile (it meets the objective
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 92c6ffa - [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-06-18T00:00:43+02:00
New Revision: 92c6ffa14cdeb3edd50b46d30c830698705db9f5

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

LOG: [clang][driver] Ensure we don't accumulate entries in -MJ files

Previously, each job would overwrite the -MJ file. This didn't quite work for 
Clang invocations with multiple architectures, which got fixed in D121997 by 
always appending to the -MJ file. That's not correct either, since the file 
would grow indefinitely on subsequent Clang invocations. This patch ensures the 
driver always removes the file before jobs fill it in by appending.

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/compilation_database_multiarch.c

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 7b6e442d7801a..cbde26668b78c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1314,6 +1314,10 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Remove existing compilation database so that each job can append to it.
+  if (Arg *A = Args.getLastArg(options::OPT_MJ))
+llvm::sys::fs::remove(A->getValue());
+
   // Setting up the jobs for some precompile cases depends on whether we are
   // treating them as PCH, implicit modules or C++20 ones.
   // TODO: inferring the mode like this seems fragile (it meets the objective

diff  --git a/clang/test/Driver/compilation_database_multiarch.c 
b/clang/test/Driver/compilation_database_multiarch.c
index 86401503aa17c..8ea3a457f11cc 100644
--- a/clang/test/Driver/compilation_database_multiarch.c
+++ b/clang/test/Driver/compilation_database_multiarch.c
@@ -2,7 +2,14 @@
 
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+
+// Let's run that again and verify we're not accumulating redundant entries in 
the same file.
+//
+// RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+// RUN: echo EOF >> %t/compilation_database.json
+
 // RUN: FileCheck --input-file=%t/compilation_database.json %s
 
 // CHECK:  { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_X86_64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_X86_64]]", {{.*}} 
"--target=x86_64-apple-macosx12.0.0"]},
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF



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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Thanks for the review!




Comment at: clang/test/Driver/compilation_database_multiarch.c:15
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF

MaskRay wrote:
> CHECK-EMPTY can match EOF.
It can, but it's not really strict. It will match an empty line, but that might 
be followed by some non-empty lines, which I'd like this test to explicitly 
disallow.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128098/new/

https://reviews.llvm.org/D128098

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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: StephenFan.

LGTM.




Comment at: clang/test/Driver/compilation_database_multiarch.c:15
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF

CHECK-EMPTY can match EOF.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128098/new/

https://reviews.llvm.org/D128098

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


[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-06-17 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added inline comments.



Comment at: clang/cmake/caches/Fuchsia-stage2.cmake:124
 set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
-set(RUNTIMES_${target}_LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
 set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")

phosek wrote:
> ldionne wrote:
> > phosek wrote:
> > > ldionne wrote:
> > > > ldionne wrote:
> > > > > phosek wrote:
> > > > > > ldionne wrote:
> > > > > > > phosek wrote:
> > > > > > > > ldionne wrote:
> > > > > > > > > Note that I am removing these options here because I don't 
> > > > > > > > > think they are required -- since we specify 
> > > > > > > > > `LIBCXXABI_ENABLE_SHARED=OFF`, there is no shared libc++abi 
> > > > > > > > > to link against, so we should already be linking against 
> > > > > > > > > `libc++abi.a` regardless of this change.
> > > > > > > > This option was set to merge `libc++abi.a` into `libc++.a` so 
> > > > > > > > to achieve the same effect, presumably we would need to set 
> > > > > > > > `-DLIBCXX_CXX_ABI=libcxxabi-objects`?
> > > > > > > I agree this is suspicious, but why is there no 
> > > > > > > `LIBCXX_STATICALLY_LINK_ABI_IN_SHARED_LIBRARY` specified here 
> > > > > > > then? I can add `-DLIBCXX_CXX_ABI=libcxxabi-objects`, I just want 
> > > > > > > to make sure we both understand what's going on.
> > > > > > This is intentional. We are merging `libc++abi.a` into `libc++.a` 
> > > > > > but we ship `libc++abi.so` and `libc++.so` as separate (and use the 
> > > > > > generated linker script to pull in `libc++abi.so` when you pass 
> > > > > > `-lc++` to linker). I'd be fine merging `libc++abi.so` into 
> > > > > > `libc++.so` as well, but we'll need to figure out a transition plan 
> > > > > > since there are several places in our build right now that expect 
> > > > > > `libc++abi.so` to exist. We cannot land this change as is because 
> > > > > > that would break the `-static-libstdc++` use case, since Clang 
> > > > > > driver only passes `-lc++` to the linker and not `-lc++abi` and 
> > > > > > there's nothing that would pull `libc++abi.a` in.
> > > > > I see, so to summarize, basically you want to use `libcxxabi-objects` 
> > > > > for the static `libc++.a`, but `libcxxabi` for the dynamic 
> > > > > `libc++.so`. This change as currently laid out does not permit that 
> > > > > to happen, since `libcxxabi-objects` implies that the objects are 
> > > > > merged both in the static and in the shared library. I guess we could 
> > > > > introduce a new `libcxxabi-objects-static` option, however that would 
> > > > > be kind of strange. We can either do that, or wait for you to stop 
> > > > > relying on `libc++abi.so` existing and switch to `libcxxabi-objects` 
> > > > > wholesale for Fuchsia. WDYT?
> > > > Gentle ping. It would be nice to land this in one form or another. If 
> > > > you don't think Fuchsia can stop relying on `libc++abi.so` being there, 
> > > > I could add yet another `libcxxabi-objects-static` -- I still feel like 
> > > > that's better than the status quo.
> > > We discussed this on our team and we don't have any issues switching 
> > > towards combined `libc++.so`, we just need to figure out a transition 
> > > plan. Let me test this change locally to see if landing this as is will 
> > > break anything.
> > Gentle ping -- did you get any time to investigate this?
> I did and we are currently hitting a failure related to our libunwind usage. 
> I have created D127528 which should address it. 
Thanks! Since this has been landed, does it mean we can move forward with this 
patch?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125683/new/

https://reviews.llvm.org/D125683

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


[PATCH] D127991: [clang-repl] Remove memory leak of ASTContext/TargetMachine.

2022-06-17 Thread Sunho Kim via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7bc00ce5cd41: [clang-repl] Remove memory leak of 
ASTContext/TargetMachine. (authored by sunho).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127991/new/

https://reviews.llvm.org/D127991

Files:
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/Interpreter.cpp


Index: clang/lib/Interpreter/Interpreter.cpp
===
--- clang/lib/Interpreter/Interpreter.cpp
+++ clang/lib/Interpreter/Interpreter.cpp
@@ -116,6 +116,9 @@
   // times, reusing the same AST.
   Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
 
+  Clang->getFrontendOpts().DisableFree = false;
+  Clang->getCodeGenOpts().DisableFree = false;
+
   return std::move(Clang);
 }
 
Index: clang/lib/Interpreter/IncrementalParser.cpp
===
--- clang/lib/Interpreter/IncrementalParser.cpp
+++ clang/lib/Interpreter/IncrementalParser.cpp
@@ -134,7 +134,10 @@
   P->Initialize();
 }
 
-IncrementalParser::~IncrementalParser() { Act->FinalizeAction(); }
+IncrementalParser::~IncrementalParser() {
+  P.reset();
+  Act->FinalizeAction();
+}
 
 llvm::Expected
 IncrementalParser::ParseOrWrapTopLevelDecl() {


Index: clang/lib/Interpreter/Interpreter.cpp
===
--- clang/lib/Interpreter/Interpreter.cpp
+++ clang/lib/Interpreter/Interpreter.cpp
@@ -116,6 +116,9 @@
   // times, reusing the same AST.
   Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
 
+  Clang->getFrontendOpts().DisableFree = false;
+  Clang->getCodeGenOpts().DisableFree = false;
+
   return std::move(Clang);
 }
 
Index: clang/lib/Interpreter/IncrementalParser.cpp
===
--- clang/lib/Interpreter/IncrementalParser.cpp
+++ clang/lib/Interpreter/IncrementalParser.cpp
@@ -134,7 +134,10 @@
   P->Initialize();
 }
 
-IncrementalParser::~IncrementalParser() { Act->FinalizeAction(); }
+IncrementalParser::~IncrementalParser() {
+  P.reset();
+  Act->FinalizeAction();
+}
 
 llvm::Expected
 IncrementalParser::ParseOrWrapTopLevelDecl() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7bc00ce - [clang-repl] Remove memory leak of ASTContext/TargetMachine.

2022-06-17 Thread Sunho Kim via cfe-commits

Author: Sunho Kim
Date: 2022-06-18T06:36:25+09:00
New Revision: 7bc00ce5cd41aad5fd0775f58c8e85a0a8d9ee56

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

LOG: [clang-repl] Remove memory leak of ASTContext/TargetMachine.

Removes memory leak of ASTContext and TargetMachine. When DisableFree is turned 
on, it intentionally leaks these instances as they can be trivially 
deallocated. This patch turns this off and delete Parser instance early so that 
they will not reference dangling pargma headers.

Asan shouldn't detect these as leaks normally, since burypointer is called for 
them. But, every invocation of incremental parser createa an additional leak of 
TargetMachine. If there are many invocations within a single test case, we 
easily reach number of leaks exceeding kGraveYardMaxSize (which is 12) and 
leaks start to get reported by asan buildbots.

Reviewed By: v.g.vassilev

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

Added: 


Modified: 
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/Interpreter.cpp

Removed: 




diff  --git a/clang/lib/Interpreter/IncrementalParser.cpp 
b/clang/lib/Interpreter/IncrementalParser.cpp
index 0f1ef3233a2a1..e5712303cbbb2 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -134,7 +134,10 @@ 
IncrementalParser::IncrementalParser(std::unique_ptr Instance,
   P->Initialize();
 }
 
-IncrementalParser::~IncrementalParser() { Act->FinalizeAction(); }
+IncrementalParser::~IncrementalParser() {
+  P.reset();
+  Act->FinalizeAction();
+}
 
 llvm::Expected
 IncrementalParser::ParseOrWrapTopLevelDecl() {

diff  --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 470c9c289a749..564b24efebdd0 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -116,6 +116,9 @@ CreateCI(const llvm::opt::ArgStringList ) {
   // times, reusing the same AST.
   Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
 
+  Clang->getFrontendOpts().DisableFree = false;
+  Clang->getCodeGenOpts().DisableFree = false;
+
   return std::move(Clang);
 }
 



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


[PATCH] D128031: Don't emit `-Wnullability-completeness` warnings on `weak` Objective-C properties.

2022-06-17 Thread Michael Wyman via Phabricator via cfe-commits
mwyman added a comment.

Created Github issue to track: https://github.com/llvm/llvm-project/issues/56096


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128031/new/

https://reviews.llvm.org/D128031

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


[PATCH] D128098: [clang][driver] Ensure we don't accumulate entries in -MJ files

2022-06-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: egorzhdan.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Previously, each job would overwrite the -MJ file. This didn't quite work for 
Clang invocations with multiple architectures, which got fixed in D121997 
 by always appending to the -MJ file. That's 
not correct either, since the file would grow indefinitely on subsequent Clang 
invocations. This patch ensures the driver always removes the file before jobs 
fill it in by appending.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128098

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/compilation_database_multiarch.c


Index: clang/test/Driver/compilation_database_multiarch.c
===
--- clang/test/Driver/compilation_database_multiarch.c
+++ clang/test/Driver/compilation_database_multiarch.c
@@ -2,7 +2,14 @@
 
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+
+// Let's run that again and verify we're not accumulating redundant entries in 
the same file.
+//
+// RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch 
x86_64 -MJ %t/compilation_database.json
+// RUN: echo EOF >> %t/compilation_database.json
+
 // RUN: FileCheck --input-file=%t/compilation_database.json %s
 
 // CHECK:  { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_X86_64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_X86_64]]", {{.*}} 
"--target=x86_64-apple-macosx12.0.0"]},
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": 
"[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} 
"--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -1314,6 +1314,10 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Remove existing compilation database so that each job can append to it.
+  if (Arg *A = Args.getLastArg(options::OPT_MJ))
+llvm::sys::fs::remove(A->getValue());
+
   // Setting up the jobs for some precompile cases depends on whether we are
   // treating them as PCH, implicit modules or C++20 ones.
   // TODO: inferring the mode like this seems fragile (it meets the objective


Index: clang/test/Driver/compilation_database_multiarch.c
===
--- clang/test/Driver/compilation_database_multiarch.c
+++ clang/test/Driver/compilation_database_multiarch.c
@@ -2,7 +2,14 @@
 
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch x86_64 -MJ %t/compilation_database.json
+
+// Let's run that again and verify we're not accumulating redundant entries in the same file.
+//
+// RUN: %clang -fdriver-only -o %t/out %s -mtargetos=macos12 -arch arm64 -arch x86_64 -MJ %t/compilation_database.json
+// RUN: echo EOF >> %t/compilation_database.json
+
 // RUN: FileCheck --input-file=%t/compilation_database.json %s
 
 // CHECK:  { "directory": "{{.*}}", "file": "{{.*}}", "output": "[[OUTPUT_X86_64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_X86_64]]", {{.*}} "--target=x86_64-apple-macosx12.0.0"]},
 // CHECK-NEXT: { "directory": "{{.*}}", "file": "{{.*}}", "output": "[[OUTPUT_ARM64:.*]]", "arguments": [{{.*}}, "-o", "[[OUTPUT_ARM64]]", {{.*}} "--target=arm64-apple-macosx12.0.0"]},
+// CHECK-NEXT: EOF
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -1314,6 +1314,10 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Remove existing compilation database so that each job can append to it.
+  if (Arg *A = Args.getLastArg(options::OPT_MJ))
+llvm::sys::fs::remove(A->getValue());
+
   // Setting up the jobs for some precompile cases depends on whether we are
   // treating them as PCH, implicit modules or C++20 ones.
   // TODO: inferring the mode like this seems fragile (it meets the objective
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126061: [clang] Reject non-declaration C++11 attributes on declarations

2022-06-17 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Fix for compile time regression submitted for review at 
https://reviews.llvm.org/D128097


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126061/new/

https://reviews.llvm.org/D126061

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


[PATCH] D128097: [Clang] Fix compile time regression caused by D126061.

2022-06-17 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

As noted by @nikic, D126061  causes a compile 
time regression of about
0.5% on -O0 builds:

http://llvm-compile-time-tracker.com/compare.php?from=7acc88be0312c721bc082ed9934e381d297f4707=8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb=instructions

This happens because, in a number of places, D126061 
 creates an
additional local variable of type `ParsedAttributes`. In the large
majority of cases, no attributes are added to this `ParsedAttributes`,
but it turns out that creating an empty `ParsedAttributes`, then
destroying it is a relatively expensive operation.

The reason for this is because `AttributePool` uses a `TinyPtrVector` as
its underlying vector class, and the technique that `TinyPtrVector`
employs to achieve its extreme memory frugality makes the `begin()` and
`end()` member functions relatively slow. The `ParsedAttributes`
destructor iterates over the attributes in its `AttributePool`, and this
is a relatively expensive operation because `TinyPtrVector`'s `begin()` and
`end()` are relatively slow.

The fix for this is to replace `TinyPtrVector` in `ParsedAttributes` and
`AttributePool` with `SmallVector`. `ParsedAttributes` and
`AttributePool` objects are only ever allocated on the stack (they're
not part of the AST), and only a small number of these objects are live
at any given time, so they don't need the extreme memory frugality of
`TinyPtrVector`.

I've confirmed with valgrind that this patch does not increase heap
memory usage, and it actually makes compiles slightly faster than they
were before D126061 .

Here are instruction count measurements (obtained with callgrind)
running `clang -c MultiSource/Applications/JM/lencod/parsetcommon.c`
(a file from llvm-test-suite that exhibited a particularly large
compile-time regression):

7acc88be0312c721bc082ed9934e381d297f4707 

(baseline one commit before D126061  landed)
102,280,068 instructions

8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb 

(the patch that landed D126061 )
103,289,454 instructions
(+0.99% relative to baseline)

This patch applied onto
8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb 

101,117,584 instructions
(-1.14% relative to baseline)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128097

Files:
  clang/include/clang/Sema/ParsedAttr.h


Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -21,7 +21,6 @@
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Registry.h"
 #include "llvm/Support/VersionTuple.h"
@@ -783,7 +782,7 @@
   friend class AttributeFactory;
   friend class ParsedAttributes;
   AttributeFactory 
-  llvm::TinyPtrVector Attrs;
+  llvm::SmallVector Attrs;
 
   void *allocate(size_t size) {
 return Factory.allocate(size);
@@ -908,7 +907,7 @@
 };
 
 class ParsedAttributesView {
-  using VecTy = llvm::TinyPtrVector;
+  using VecTy = llvm::SmallVector;
   using SizeType = decltype(std::declval().size());
 
 public:


Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -21,7 +21,6 @@
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Registry.h"
 #include "llvm/Support/VersionTuple.h"
@@ -783,7 +782,7 @@
   friend class AttributeFactory;
   friend class ParsedAttributes;
   AttributeFactory 
-  llvm::TinyPtrVector Attrs;
+  llvm::SmallVector Attrs;
 
   void *allocate(size_t size) {
 return Factory.allocate(size);
@@ -908,7 +907,7 @@
 };
 
 class ParsedAttributesView {
-  using VecTy = llvm::TinyPtrVector;
+  using VecTy = llvm::SmallVector;
   using SizeType = decltype(std::declval().size());
 
 public:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126061: [clang] Reject non-declaration C++11 attributes on declarations

2022-06-17 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

In D126061#3585681 , @nikic wrote:

> FYI this change had a measurable effect on compile-time 
> (http://llvm-compile-time-tracker.com/compare.php?from=7acc88be0312c721bc082ed9934e381d297f4707=8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb=instructions),
>  about 0.5% regression for `O0` builds. Not sure if that's expected.

I've found the reason for this slowdown, and a fix.

In a number of places, this patch adds additional local variables of type 
`ParsedAttributes`, typically because we need to keep track of declaration and 
decl-specifier-seq attributes in two separate `ParsedAttribute` lists where 
previously we were putting them in the same list. Note that in the vast 
majority of cases, these `ParsedAttributes` lists are empty.

I would have assumed that creating an empty `ParsedAttributes`, potentially 
iterating over it, then destroying it, is cheap. However, this is not true for 
`ParsedAttributes` because it uses a `TinyPtrVector` as the underlying 
container. The same is true for the `AttributePool` that `ParsedAttributes` 
contains.

`TinyPtrVector` is amazingly memory-frugal in that it consumes only a single 
pointer worth of memory if the vector contains zero or one elements. However, 
this comes at a cost: `begin()` and `end()` on this container are relatively 
expensive. As a result, iterating over an empty `TinyPtrVector`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126061/new/

https://reviews.llvm.org/D126061

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


[PATCH] D126907: Deferred Concept Instantiation Implementation Take 2

2022-06-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Made good progress today, but got trapped down the CheckDeducedArgs path for 
quite a bit longer with partial specializations.  I have all of the crashes I 
know of 'fixed', but have a few tests that still fail for unknown reasons.  
Because of that, i don't have anything I can really upload, so I'll have to do 
so mid-next-week.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126907/new/

https://reviews.llvm.org/D126907

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


[PATCH] D127593: [clang] Fix trivially copyable for copy constructor and copy assignment operator

2022-06-17 Thread Javier Alvarez via Phabricator via cfe-commits
Javier-varez added a comment.

Thanks for taking care of this Roy and helping me out through the process!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127593/new/

https://reviews.llvm.org/D127593

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


[PATCH] D128083: [C++20] Correctly handle constexpr/consteval explicitly defaulted special member instantiation behavior

2022-06-17 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/AST/DeclCXX.cpp:1315-1316
 !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
   // The standard requires any in-class initializer to be a constant
   // expression. We consider this to be a defect.
+  data().DefaultedDefaultConstructorIsConstexpr =

Incidentally: this was fixed in DR1361, a long time ago. We can remove this 
comment.



Comment at: clang/lib/AST/DeclCXX.cpp:1319
+  isa(this)
+  ? hasConstexprDefaultConstructor()
+  : false;

Shouldn't this be looking in the class template itself? It doesn't seem correct 
to use things like `this->hasConstexprDefaultConstructor()` from here, because 
we've not finished gathering the data that contributes to that function's 
return value yet.

That said... I don't think that changing 
`DefaultedDefaultConstructorIsConstexpr` can work here. Keep in mind that a 
class can have more than one default constructor, and in C++20 onwards can even 
have more than one defaulted default constructor. This flag needs to apply to 
all of them, and only some subset of them might have been declared as 
`constexpr` in the template from which they are instantiated. So this flag 
should be answering the question, "is a defaulted default constructor 
*implicitly* constexpr?", and any callers that are assuming that it means "will 
this particular defaulted default constructor be constexpr?" should be changed 
to take into account whether the default constructor is explicitly declared as 
constexpr.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:7555-7556
+  //   expression.
+  if (!Constexpr && isa(RD))
+Constexpr = MD->isConstexpr();
+

It would be clearer and more in line with the wording to ask if `MD` is 
instantiated here, rather than to ask if the class is being instantiated 
(though the two are presumably equivalent because you can't instantiate a 
constructor template to form a special member function).



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:7576
 //   would be.
 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
   ? ConstexprSpecKind::Consteval

I think we'll now treat instantiated constructors and non-instantiated ones 
differently here:

```
#ifdef TEMPLATE
template
#endif
struct S {
  constexpr S() = default;
  TypeWithThrowingConstructor x;
};
```

In the templated case, the instantiation's constructor will be constexpr, but 
in the non-template case it won't be. That doesn't seem consistent. It would be 
cleaner and would probably require fewer special cases if we treated both cases 
the same: if you specify `constexpr`, you get a constexpr function, always, but 
we'll generate an error message if the function is non-templated and wouldn't 
have been implicitly constexpr.



Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:774
+  T data;
+  consteval default_ctor() = default; // expected-note {{non-constexpr 
constructor 'foo' cannot be used in a constant expression}}
+};

This diagnostic demonstrates that we're not doing the proper checking here: we 
do attempt to call a constexpr constructor that doesn't satisfy the constexpr 
requirements, even though we're not supposed to. IIRC we try to hand-wave our 
way to conformance here by saying that all of the things that cause a constexpr 
constructor to fail to satisfy the constexpr requirements would also cause 
evaluation to fail, but it'd be worth double-checking that (in particular: what 
happens if the class has a virtual base class?).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128083/new/

https://reviews.llvm.org/D128083

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


[PATCH] D119296: KCFI sanitizer

2022-06-17 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen updated this revision to Diff 438010.
samitolvanen added a comment.

Rebased after ToT member function name changes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119296/new/

https://reviews.llvm.org/D119296

Files:
  clang/docs/ControlFlowIntegrity.rst
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/Sanitizers.def
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/test/CodeGen/kcfi.c
  clang/test/Driver/fsanitize.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/CodeGen/GlobalISel/CallLowering.h
  llvm/include/llvm/CodeGen/TargetLowering.h
  llvm/include/llvm/IR/InstrTypes.h
  llvm/include/llvm/IR/LLVMContext.h
  llvm/include/llvm/MC/MCObjectFileInfo.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/GlobalISel/CallLowering.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/IR/LLVMContext.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/MC/MCObjectFileInfo.cpp
  llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
  llvm/lib/Target/AArch64/AArch64FastISel.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.h
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/lib/Target/X86/X86ExpandPseudo.cpp
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrCompiler.td
  llvm/lib/Target/X86/X86InstrControl.td
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86MCInstLower.cpp
  llvm/lib/Target/X86/X86TargetMachine.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/test/Bitcode/operand-bundles-bc-analyzer.ll
  llvm/test/CodeGen/AArch64/kcfi-bti.ll
  llvm/test/CodeGen/AArch64/kcfi.ll
  llvm/test/CodeGen/X86/O0-pipeline.ll
  llvm/test/CodeGen/X86/kcfi.ll
  llvm/test/CodeGen/X86/opt-pipeline.ll
  llvm/test/Transforms/InstCombine/kcfi-operand-bundles.ll
  llvm/test/Transforms/TailCallElim/kcfi-bundle.ll
  llvm/test/Verifier/kcfi-operand-bundles.ll

Index: llvm/test/Verifier/kcfi-operand-bundles.ll
===
--- /dev/null
+++ llvm/test/Verifier/kcfi-operand-bundles.ll
@@ -0,0 +1,16 @@
+; RUN: not opt -verify < %s 2>&1 | FileCheck %s
+
+define void @test_kcfi_bundle(i64 %arg0, i32 %arg1, void()* %arg2) {
+; CHECK: Multiple kcfi operand bundles
+; CHECK-NEXT: call void %arg2() [ "kcfi"(i32 42), "kcfi"(i32 42) ]
+  call void %arg2() [ "kcfi"(i32 42), "kcfi"(i32 42) ]
+
+; CHECK: Kcfi bundle operand must be an i32 constant
+; CHECK-NEXT: call void %arg2() [ "kcfi"(i64 42) ]
+  call void %arg2() [ "kcfi"(i64 42) ]
+
+; CHECK-NOT: call
+  call void %arg2() [ "kcfi"(i32 42) ] ; OK
+  call void %arg2() [ "kcfi"(i32 42) ] ; OK
+  ret void
+}
Index: llvm/test/Transforms/TailCallElim/kcfi-bundle.ll
===
--- /dev/null
+++ llvm/test/Transforms/TailCallElim/kcfi-bundle.ll
@@ -0,0 +1,10 @@
+; RUN: opt < %s -tailcallelim -verify-dom-info -S | FileCheck %s
+; Check that the "kcfi" operand bundle doesn't prevent tail calls.
+
+define i64 @f_1(i64 %x, i64(i64)* %f_0) {
+; CHECK-LABEL: @f_1(
+entry:
+; CHECK: tail call i64 %f_0(i64 %x) [ "kcfi"(i32 42) ]
+  %tmp = call i64 %f_0(i64 %x) [ "kcfi"(i32 42) ]
+  ret i64 0
+}
Index: llvm/test/Transforms/InstCombine/kcfi-operand-bundles.ll
===
--- /dev/null
+++ llvm/test/Transforms/InstCombine/kcfi-operand-bundles.ll
@@ -0,0 +1,25 @@
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+define void @f1() #0 prefix i32 10 {
+  ret void
+}
+
+declare void @f2() #0 prefix i32 11
+
+; CHECK-LABEL: define void @g(ptr noundef %x) #0
+define void @g(ptr noundef %x) #0 {
+  ; CHECK: call void %x() [ "kcfi"(i32 10) ]
+  call void %x() [ "kcfi"(i32 10) ]
+
+  ; COM: Must drop the kcfi operand bundle from direct calls.
+  ; CHECK: call void @f1()
+  ; CHECK-NOT: [ "kcfi"(i32 10) ]
+  call void @f1() [ "kcfi"(i32 10) ]
+
+  ; CHECK: call void @f2()
+  ; CHECK-NOT: [ "kcfi"(i32 10) ]
+  call void @f2() [ "kcfi"(i32 10) ]
+  ret void
+}
+
+attributes #0 = { "kcfi-target" }
Index: llvm/test/CodeGen/X86/opt-pipeline.ll
===
--- llvm/test/CodeGen/X86/opt-pipeline.ll
+++ llvm/test/CodeGen/X86/opt-pipeline.ll
@@ -206,6 +206,7 @@
 ; CHECK-NEXT:   Check CFA 

[PATCH] D113107: Support of expression granularity for _Float16.

2022-06-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:896
+
+ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E) {
+  if (auto *BinOp = dyn_cast(E->IgnoreParens())) {

zahiraam wrote:
> rjmccall wrote:
> > `EmitPromoted` should take the promotion type.
> > 
> > You are missing the logic in this file which handles *unpromoted* emission 
> > (where you have a binary operator but the context wants an unpromoted 
> > value) by recognizing that you need to do a promoted operation and then 
> > truncate.
> Sorry but not sure what you mean here. A case where we don't want any 
> promotion would be:
> 
> float _Complex add(float _Complex a, float _Complex b) {
>   return a + b;
> }
> 
> In this case, getPromotionType would return the null type and EmitBinOps 
> would just go through the  "older" control path where there is no promotion.
> Unless I misunderstood your comment?
> 
> 
I'm talking about the unpromoted emission path for an operation that we want to 
*internally* promote.  So like your example but using `_Float16` — we want to 
emit the binary `+` as a `float` operation, but the context needs an unpromoted 
value because it's going to be returned.

The promoted emission path (the various `EmitPromoted` methods) represents a 
request by the caller to produce a result that doesn't match the formal type of 
the expression.  The normal emission path `Visit` etc.) represents a request by 
the caller to produce a result normally, i.e. one that matches the formal type. 
 In general, we always start in the latter because arbitrary contexts always 
expect a value of the formal type; it's only these recursive calls within 
promoted emitters that contextually want a promoted value.

In your current patch, you're entering the promoted path by special-casing one 
context that frequently terminates promoted emission: 
`EmitComplexExprIntoLValue`, which is used for things like assignment.  That's 
not the right way to handle it, though.  Instead, you should do like I asked 
you to do with the scalar emitter, which is to recognize in the normal emission 
path for a promotable operation (like binary `+`) that you need to promote the 
operation and then unpromote the result.  Then things like 
`EmitComplexExprIntoLValue` will continue to simply enter the normal path 
because that's the kind of value they need, and the promotion logic will do the 
right thing from there to ensure we don't emit a `_Float16` operation in LLVM 
IR.

Incidentally, I thought of another context that you ought to do promotion for: 
when we're converting a promotable value to a larger floating-point type, we 
should presumably convert the promoted value directly rather than truncating it 
to the unpromoted type before the conversion.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113107/new/

https://reviews.llvm.org/D113107

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


[PATCH] D127976: [IR] Move vector.insert/vector.extract out of experimental namespace

2022-06-17 Thread Diego Caballero via Phabricator via cfe-commits
dcaballe added subscribers: jsetoain, dcaballe.
dcaballe added a comment.

Hey Bradley! Thanks for pinging us about this upcoming change! Something that 
my colleague @jsetoain mentioned is that these vector insert/extract intrinsics 
can also work on fixed-length only vectors. However, the documentation and 
slightly tend to suggest that they should specifically be used to 
insert/extract fixed-length vectors into/out of scalable one. Perhaps 
clarifying that they can be used on fixed-length only vectors and adding an 
example for that case would be very helpful. Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127976/new/

https://reviews.llvm.org/D127976

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


[PATCH] D128090: [Clang][OpenMP] Process multi-arch compilation options given via -march

2022-06-17 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 438004.
saiislam added a comment.

clang-formatted.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128090/new/

https://reviews.llvm.org/D128090

Files:
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -722,6 +722,38 @@
   return RT;
 }
 
+bool Driver::GetTargetInfoFromMArch(
+Compilation , llvm::StringMap> ) {
+  StringRef OpenMPTargetArch;
+  for (Arg *A : C.getInputArgs()) {
+if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
+  StringRef OpenMPTargetTriple = StringRef(A->getValue(0));
+  llvm::Triple TargetTriple(OpenMPTargetTriple);
+
+  for (auto *V : A->getValues()) {
+StringRef VStr = StringRef(V);
+if (VStr.startswith("-march=") || VStr.startswith("--march=")) {
+  OpenMPTargetArch = VStr.split('=').second;
+  CudaArch Arch = StringToCudaArch(StringRef(OpenMPTargetArch));
+  if (Arch == CudaArch::UNKNOWN) {
+C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch)
+<< OpenMPTargetArch;
+C.setContainsError();
+return false;
+  }
+
+  if (!OpenMPTargetTriple.empty() && !OpenMPTargetArch.empty()) {
+DerivedArchs[OpenMPTargetTriple].insert(OpenMPTargetArch);
+  }
+}
+A->claim();
+  }
+}
+  }
+
+  return true;
+}
+
 void Driver::CreateOffloadingDeviceToolChains(Compilation ,
   InputList ) {
 
@@ -812,6 +844,10 @@
 << OpenMPTargets->getAsString(C.getInputArgs());
 return;
   }
+  // Process legacy option -fopenmp-targets -Xopenmp-target and -march
+  auto status = GetTargetInfoFromMArch(C, DerivedArchs);
+  if (!status)
+return;
   llvm::copy(OpenMPTargets->getValues(), 
std::back_inserter(OpenMPTriples));
 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
!IsHIP && !IsCuda) {
Index: clang/include/clang/Driver/Driver.h
===
--- clang/include/clang/Driver/Driver.h
+++ clang/include/clang/Driver/Driver.h
@@ -412,6 +412,11 @@
   /// current compilation. Also, update the host tool chain kind accordingly.
   void CreateOffloadingDeviceToolChains(Compilation , InputList );
 
+  /// GetTargetInfoFromMArch - extract sub-architecture from -march flag used
+  /// with -fopenmp-targets and -Xopenmp-target options.
+  bool GetTargetInfoFromMArch(
+  Compilation , llvm::StringMap> 
);
+
   /// BuildCompilation - Construct a compilation object for a command
   /// line argument vector.
   ///


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -722,6 +722,38 @@
   return RT;
 }
 
+bool Driver::GetTargetInfoFromMArch(
+Compilation , llvm::StringMap> ) {
+  StringRef OpenMPTargetArch;
+  for (Arg *A : C.getInputArgs()) {
+if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
+  StringRef OpenMPTargetTriple = StringRef(A->getValue(0));
+  llvm::Triple TargetTriple(OpenMPTargetTriple);
+
+  for (auto *V : A->getValues()) {
+StringRef VStr = StringRef(V);
+if (VStr.startswith("-march=") || VStr.startswith("--march=")) {
+  OpenMPTargetArch = VStr.split('=').second;
+  CudaArch Arch = StringToCudaArch(StringRef(OpenMPTargetArch));
+  if (Arch == CudaArch::UNKNOWN) {
+C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch)
+<< OpenMPTargetArch;
+C.setContainsError();
+return false;
+  }
+
+  if (!OpenMPTargetTriple.empty() && !OpenMPTargetArch.empty()) {
+DerivedArchs[OpenMPTargetTriple].insert(OpenMPTargetArch);
+  }
+}
+A->claim();
+  }
+}
+  }
+
+  return true;
+}
+
 void Driver::CreateOffloadingDeviceToolChains(Compilation ,
   InputList ) {
 
@@ -812,6 +844,10 @@
 << OpenMPTargets->getAsString(C.getInputArgs());
 return;
   }
+  // Process legacy option -fopenmp-targets -Xopenmp-target and -march
+  auto status = GetTargetInfoFromMArch(C, DerivedArchs);
+  if (!status)
+return;
   llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
!IsHIP && !IsCuda) {
Index: clang/include/clang/Driver/Driver.h
===
--- clang/include/clang/Driver/Driver.h
+++ clang/include/clang/Driver/Driver.h
@@ -412,6 +412,11 @@
   /// 

[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

jackhong12 wrote:
> jackhong12 wrote:
> > HazardyKnusperkeks wrote:
> > > Unknown is everything, until some type is assigned. This way it should be 
> > > clearer.
> > > 
> > > Also put that check above the other one and add the `r_brace` back.
> > There are other problems. Clang-format will split the input into multiple 
> > lines first. For instance, `struct {\n int n;\n} &={};` will be 
> > separated as `struct {`, `int n;` and `} &={};`. It only handles the 
> > relation in the line. When declaring a struct variable, the value of 
> > `MatchingParen` will always be NULL instead of pointing to the last left 
> > brace. So it will not enter that branch in this case.
> ```
> if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
> PrevToken->MatchingParen) {
>   if (PrevToken->MatchingParen->is(TT_RecordLBrace))
> return TT_PointerOrReference;
>   else
> return TT_BinaryOperator;
> }
> ```
> How about this way? Although the branch of TT_PointerOrReference will not be 
> taken, it's clearer for reading.
Then I think I would prefer a comment which explains the logic instead of 
adding dead (and thus untested) code.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127873/new/

https://reviews.llvm.org/D127873

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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Nice work adding the capability to the dump script.




Comment at: clang/docs/ClangFormatStyleOptions.rst:4264
+and opening parentheses.
+14
+

This seems to be not entirely correct yet. :)



Comment at: clang/include/clang/Format/Format.h:3504
+enum AfterPlacementOperatorStyle : int8_t {
+  /// Never add space after ``new/delete`` operators and before ``(``.
+  /// \code





Comment at: clang/lib/Format/TokenAnnotator.cpp:3396
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&

omarahmed wrote:
> MyDeveloperDay wrote:
> > shouldn't the very first part of this be? 
> > 
> > 
> > ```
> > if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
> > FormatStyle::SpaceBeforeParensCustom::APO_Leave)
> > {
> > 
> > 
> > 
> > }
> > ```
> > 
> > i.e. don't we want a zero change if someone says "Leave"
> The current code logic, when we do not enter this suggested condition, will 
> switch to [this 
> condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580).
>  And will not leave the code as it is, but will change it.
> 
> I have thought of getting rid of this condition entirely, but it handles the 
> default situation suggested here, not only for cpp but for other languages 
> like js:
> >>As I understand, the default behavior for when the user didn't use 
> >>`SBPO_Custom` is to add a space in placement operators based on [this 
> >>issue](https://github.com/llvm/llvm-project/issues/54703). And, at the same 
> >>time, the default behavior should be `APO_Never` when we have `SBPO_Custom` 
> >>so that we handle other code that depends on that. the existing tests 
> >>confirm this understanding. So, the current logic was added based on this 
> >>understanding.
> 
> I tried to add an extra condition to [this 
> condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580)
>  to support the main logic that we are pursuing. so that it would be like 
> that:
> ```
> if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
> FormatStyle::SpaceBeforeParensCustom::APO_Leave && Left.isOneOf(tok::kw_new, 
> tok::kw_delete))
> ```
> But that wouldn't fix the leave situation, as it will be also at the end, 
> reach [this 
> part](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3598)
>  which will  
> ```
> return false
> ``` 
> and force no space.
> 
> I think all of that was raised because all current 
> "SpaceBeforeParanthesesOptions" are either true or false and this is the only 
> enum
> 
> However, I completely agree with this logic which is to begin our checking 
> for leave. But I think we should refactor all the 
> "spaceBeforeParenthesesOptions" conditions to handle this and do that after 
> all the options have been transformed to enums.
> 
`SpaceBeforeParensOptions` should always be expanded, regardless of 
`SpaceBeforeParens`, as far as I remember. `SpaceBeforeParens` is only for the 
one configuring clang-format, the code that formats should always and only 
check `SpaceBeforeParensOptions`.



Comment at: clang/unittests/Format/FormatTest.cpp:10145
+   "int *c = new(p) int(3);\n"
+   "int *d = delete(p) int(3);\n"
+   "  }\n"

Can this be valid code? If not we don't need to assert on how it is formatted, 
only that it doesn't crash.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127270/new/

https://reviews.llvm.org/D127270

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


[PATCH] D128090: [Clang][OpenMP] Process multi-arch compilation options given via -march

2022-06-17 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam created this revision.
saiislam added reviewers: jdoerfert, JonChesterfield, jhuber6, yaxunl.
Herald added a subscriber: guansong.
Herald added a project: All.
saiislam requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, MaskRay.
Herald added a project: clang.

Subarchitectures for multi-file compilation specified using -fopenmp-targets,
-Xopenmp-target, and -march were not getting added to the
 map `KnownArchs`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128090

Files:
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -722,6 +722,37 @@
   return RT;
 }
 
+bool Driver::GetTargetInfoFromMArch(Compilation , 
llvm::StringMap> ) {
+  StringRef OpenMPTargetArch;
+  for (Arg *A : C.getInputArgs()) {
+if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
+  StringRef OpenMPTargetTriple = StringRef(A->getValue(0));
+  llvm::Triple TargetTriple(OpenMPTargetTriple);
+
+  for (auto *V : A->getValues()) {
+StringRef VStr = StringRef(V);
+if (VStr.startswith("-march=") || VStr.startswith("--march=")) {
+  OpenMPTargetArch = VStr.split('=').second;
+  CudaArch Arch = StringToCudaArch(StringRef(OpenMPTargetArch));
+  if (Arch == CudaArch::UNKNOWN) {
+C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch)
+<< OpenMPTargetArch;
+C.setContainsError();
+return false;
+  }
+
+  if (!OpenMPTargetTriple.empty() && !OpenMPTargetArch.empty()) {
+DerivedArchs[OpenMPTargetTriple].insert(OpenMPTargetArch);
+  }
+}
+A->claim();
+  }
+}
+  }
+
+  return true;
+}
+
 void Driver::CreateOffloadingDeviceToolChains(Compilation ,
   InputList ) {
 
@@ -812,6 +843,10 @@
 << OpenMPTargets->getAsString(C.getInputArgs());
 return;
   }
+  // Process legacy option -fopenmp-targets -Xopenmp-target and -march
+  auto status = GetTargetInfoFromMArch(C, DerivedArchs);
+  if (!status)
+return;
   llvm::copy(OpenMPTargets->getValues(), 
std::back_inserter(OpenMPTriples));
 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
!IsHIP && !IsCuda) {
Index: clang/include/clang/Driver/Driver.h
===
--- clang/include/clang/Driver/Driver.h
+++ clang/include/clang/Driver/Driver.h
@@ -412,6 +412,10 @@
   /// current compilation. Also, update the host tool chain kind accordingly.
   void CreateOffloadingDeviceToolChains(Compilation , InputList );
 
+  /// GetTargetInfoFromMArch - extract sub-architecture from -march flag used
+  /// with -fopenmp-targets and -Xopenmp-target options.
+  bool GetTargetInfoFromMArch(Compilation , 
llvm::StringMap> );
+
   /// BuildCompilation - Construct a compilation object for a command
   /// line argument vector.
   ///


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -722,6 +722,37 @@
   return RT;
 }
 
+bool Driver::GetTargetInfoFromMArch(Compilation , llvm::StringMap> ) {
+  StringRef OpenMPTargetArch;
+  for (Arg *A : C.getInputArgs()) {
+if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
+  StringRef OpenMPTargetTriple = StringRef(A->getValue(0));
+  llvm::Triple TargetTriple(OpenMPTargetTriple);
+
+  for (auto *V : A->getValues()) {
+StringRef VStr = StringRef(V);
+if (VStr.startswith("-march=") || VStr.startswith("--march=")) {
+  OpenMPTargetArch = VStr.split('=').second;
+  CudaArch Arch = StringToCudaArch(StringRef(OpenMPTargetArch));
+  if (Arch == CudaArch::UNKNOWN) {
+C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch)
+<< OpenMPTargetArch;
+C.setContainsError();
+return false;
+  }
+
+  if (!OpenMPTargetTriple.empty() && !OpenMPTargetArch.empty()) {
+DerivedArchs[OpenMPTargetTriple].insert(OpenMPTargetArch);
+  }
+}
+A->claim();
+  }
+}
+  }
+
+  return true;
+}
+
 void Driver::CreateOffloadingDeviceToolChains(Compilation ,
   InputList ) {
 
@@ -812,6 +843,10 @@
 << OpenMPTargets->getAsString(C.getInputArgs());
 return;
   }
+  // Process legacy option -fopenmp-targets -Xopenmp-target and -march
+  auto status = GetTargetInfoFromMArch(C, DerivedArchs);
+  if (!status)
+return;
   llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
 } else if 

[PATCH] D125936: [Sema] Relax an assertion in BuildStmtExpr

2022-06-17 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.

Okay, LGTM then


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125936/new/

https://reviews.llvm.org/D125936

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


[PATCH] D128083: [C++20] Correctly handle constexpr/consteval explicitly defaulted special member instantiation behavior

2022-06-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: rsmith, erichkeane, clang-language-wg, jyknight.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a project: clang.

When instantiating a class template, if the primary class template special 
member function declaration was declared `constexpr` or `consteval`, the 
instantiation is also considered to be a consteval function even if the 
instantiation would not be valid to use in a constant expression 
(http://eel.is/c++draft/dcl.constexpr#7). However, when instantiating such a 
class, we were incorrectly saying the special member was not a constexpr 
function when a base class or member variable would cause the instantiation to 
not be usable in a constant expression. This addresses the issue by falling 
back to the primary declaration of the explicitly defaulted special member 
function.

This caused some unexpected test failures with friend declaration checking, but 
the standard is quite unclear on what's expected there. We also have existing 
bugs in that particular area (https://godbolt.org/z/cPKGvx746). I raised some 
questions on the Core reflectors about what is expected and put a FIXME into 
the test to make it clear that's unresolved.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128083

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp

Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -766,3 +766,55 @@
   static_assert(c == 8);
 }
 }
+
+namespace DefaultedTemp {
+template 
+struct default_ctor {
+  T data;
+  consteval default_ctor() = default; // expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+};
+
+template 
+struct copy {
+  T data;
+
+  consteval copy(const copy &) = default;// expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+  consteval copy =(const copy &) = default; // expected-note {{non-constexpr function 'operator=' cannot be used in a constant expression}}
+  copy() = default;
+};
+
+template 
+struct move {
+  T data;
+
+  consteval move(move &&) = default;// expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+  consteval move =(move &&) = default; // expected-note {{non-constexpr function 'operator=' cannot be used in a constant expression}}
+  move() = default;
+};
+
+struct foo {
+  foo() {}// expected-note {{declared here}}
+  foo(const foo &) {} // expected-note {{declared here}}
+  foo(foo &&) {}  // expected-note {{declared here}}
+
+  foo& operator=(const foo &) { return *this; } // expected-note {{declared here}}
+  foo& operator=(foo &&) { return *this; }  // expected-note {{declared here}}
+};
+
+void func() {
+  default_ctor fail0; // expected-error {{call to consteval function 'DefaultedTemp::default_ctor::default_ctor' is not a constant expression}} \
+  expected-note {{in call to 'default_ctor()'}}
+
+  copy good0;
+  copy fail1{good0}; // expected-error {{call to consteval function 'DefaultedTemp::copy::copy' is not a constant expression}} \
+ expected-note {{in call to 'copy(good0)'}}
+  fail1 = good0;  // expected-error {{call to consteval function 'DefaultedTemp::copy::operator=' is not a constant expression}} \
+ expected-note {{in call to '>operator=(good0)'}}
+
+  move good1;
+  move fail2{static_cast&&>(good1)}; // expected-error {{call to consteval function 'DefaultedTemp::move::move' is not a constant expression}} \
+   expected-note {{in call to 'move(good1)'}}
+  fail2 = static_cast&&>(good1);  // expected-error {{call to consteval function 'DefaultedTemp::move::operator=' is not a constant expression}} \
+   expected-note {{in call to '>operator=(good1)'}}
+}
+} // namespace DefaultedTemp
Index: clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
===
--- clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
+++ clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
@@ -44,18 +44,20 @@
 }
 
 template struct S : T {
-  constexpr S() = default;
-  constexpr S(const S&) = default;
-  constexpr S(S&&) = default;
+  constexpr S() = default; // expected-note {{previous declaration is here}}
+  constexpr S(const S&) = default; // expected-note {{previous declaration is here}}
+  constexpr S(S&&) = default;  // expected-note {{previous declaration is here}}
 };
 struct lit { constexpr lit() {} };
 S s_lit; // ok
 S 

[clang] f9e4964 - Revert "wip"

2022-06-17 Thread Chris Bieneman via cfe-commits

Author: Chris Bieneman
Date: 2022-06-17T13:36:53-05:00
New Revision: f9e49644f4875ba1807781b1224b3136fefe38e9

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

LOG: Revert "wip"

This reverts commit 0dd243fa8a4ec98d6cabbad16e6b485a093c6dea.

I accidentally pushed this! Oops!

Added: 


Modified: 
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Headers/hlsl/hlsl_basic_types.h
clang/lib/Sema/CMakeLists.txt

Removed: 
clang/include/clang/Sema/HLSLExternalSemaSource.h
clang/lib/Sema/HLSLExternalSemaSource.cpp
clang/test/SemaHLSL/BuiltIns/vectors.hlsl



diff  --git a/clang/include/clang/Sema/HLSLExternalSemaSource.h 
b/clang/include/clang/Sema/HLSLExternalSemaSource.h
deleted file mode 100644
index 23dd02ef611e3..0
--- a/clang/include/clang/Sema/HLSLExternalSemaSource.h
+++ /dev/null
@@ -1,45 +0,0 @@
-//===--- HLSLExternalSemaSource.h - HLSL Sema Source *- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file defines the HLSLExternalSemaSource interface.
-//
-//===--===//
-#ifndef CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
-#define CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
-
-#include "clang/Sema/ExternalSemaSource.h"
-
-namespace clang {
-class NamespaceDecl;
-class Sema;
-
-class HLSLExternalSemaSource : public ExternalSemaSource {
-  static char ID;
-
-  Sema *SemaPtr = nullptr;
-  NamespaceDecl *HLSLNamespace;
-
-  void defineHLSLVectorAlias();
-public:
-  ~HLSLExternalSemaSource() override;
-
-  /// Initialize the semantic source with the Sema instance
-  /// being used to perform semantic analysis on the abstract syntax
-  /// tree.
-  void InitializeSema(Sema ) override;
-
-  /// Inform the semantic consumer that Sema is no longer available.
-  void ForgetSema() override {
-SemaPtr = nullptr;
-  }
-
-};
-
-} // namespace clang
-
-#endif // CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 4a141e6200030..6b1f6364b13c3 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -24,7 +24,6 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Parse/ParseAST.h"
-#include "clang/Sema/HLSLExternalSemaSource.h"
 #include "clang/Serialization/ASTDeserializationListener.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/GlobalModuleIndex.h"
@@ -1015,13 +1014,6 @@ bool FrontendAction::BeginSourceFile(CompilerInstance 
,
 CI.getASTContext().setExternalSource(Override);
   }
 
-  // Setup HLSL External Sema Source
-  if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
-IntrusiveRefCntPtr HLSLSema(
-new HLSLExternalSemaSource());
-CI.getASTContext().setExternalSource(HLSLSema);
-  }
-
   FailureCleanup.release();
   return true;
 }

diff  --git a/clang/lib/Headers/hlsl/hlsl_basic_types.h 
b/clang/lib/Headers/hlsl/hlsl_basic_types.h
index e68715f1a6a45..2069990f5c06c 100644
--- a/clang/lib/Headers/hlsl/hlsl_basic_types.h
+++ b/clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -27,38 +27,38 @@ typedef long int64_t;
 // built-in vector data types:
 
 #ifdef __HLSL_ENABLE_16_BIT
-typedef vector int16_t2;
-typedef vector int16_t3;
-typedef vector int16_t4;
-typedef vector uint16_t2;
-typedef vector uint16_t3;
-typedef vector uint16_t4;
+typedef int16_t int16_t2 __attribute__((ext_vector_type(2)));
+typedef int16_t int16_t3 __attribute__((ext_vector_type(3)));
+typedef int16_t int16_t4 __attribute__((ext_vector_type(4)));
+typedef uint16_t uint16_t2 __attribute__((ext_vector_type(2)));
+typedef uint16_t uint16_t3 __attribute__((ext_vector_type(3)));
+typedef uint16_t uint16_t4 __attribute__((ext_vector_type(4)));
 #endif
 
-typedef vector int2;
-typedef vector int3;
-typedef vector int4;
-typedef vector uint2;
-typedef vector uint3;
-typedef vector uint4;
-typedef vector int64_t2;
-typedef vector int64_t3;
-typedef vector int64_t4;
-typedef vector uint64_t2;
-typedef vector uint64_t3;
-typedef vector uint64_t4;
+typedef int int2 __attribute__((ext_vector_type(2)));
+typedef int int3 __attribute__((ext_vector_type(3)));
+typedef int int4 __attribute__((ext_vector_type(4)));
+typedef uint uint2 __attribute__((ext_vector_type(2)));
+typedef uint uint3 __attribute__((ext_vector_type(3)));
+typedef uint uint4 __attribute__((ext_vector_type(4)));
+typedef int64_t int64_t2 __attribute__((ext_vector_type(2)));
+typedef 

[clang] 0dd243f - wip

2022-06-17 Thread Chris Bieneman via cfe-commits

Author: Chris Bieneman
Date: 2022-06-17T13:34:21-05:00
New Revision: 0dd243fa8a4ec98d6cabbad16e6b485a093c6dea

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

LOG: wip

Added: 
clang/include/clang/Sema/HLSLExternalSemaSource.h
clang/lib/Sema/HLSLExternalSemaSource.cpp
clang/test/SemaHLSL/BuiltIns/vectors.hlsl

Modified: 
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Headers/hlsl/hlsl_basic_types.h
clang/lib/Sema/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Sema/HLSLExternalSemaSource.h 
b/clang/include/clang/Sema/HLSLExternalSemaSource.h
new file mode 100644
index 0..23dd02ef611e3
--- /dev/null
+++ b/clang/include/clang/Sema/HLSLExternalSemaSource.h
@@ -0,0 +1,45 @@
+//===--- HLSLExternalSemaSource.h - HLSL Sema Source *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the HLSLExternalSemaSource interface.
+//
+//===--===//
+#ifndef CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
+#define CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
+
+#include "clang/Sema/ExternalSemaSource.h"
+
+namespace clang {
+class NamespaceDecl;
+class Sema;
+
+class HLSLExternalSemaSource : public ExternalSemaSource {
+  static char ID;
+
+  Sema *SemaPtr = nullptr;
+  NamespaceDecl *HLSLNamespace;
+
+  void defineHLSLVectorAlias();
+public:
+  ~HLSLExternalSemaSource() override;
+
+  /// Initialize the semantic source with the Sema instance
+  /// being used to perform semantic analysis on the abstract syntax
+  /// tree.
+  void InitializeSema(Sema ) override;
+
+  /// Inform the semantic consumer that Sema is no longer available.
+  void ForgetSema() override {
+SemaPtr = nullptr;
+  }
+
+};
+
+} // namespace clang
+
+#endif // CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 6b1f6364b13c3..4a141e6200030 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Parse/ParseAST.h"
+#include "clang/Sema/HLSLExternalSemaSource.h"
 #include "clang/Serialization/ASTDeserializationListener.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/GlobalModuleIndex.h"
@@ -1014,6 +1015,13 @@ bool FrontendAction::BeginSourceFile(CompilerInstance 
,
 CI.getASTContext().setExternalSource(Override);
   }
 
+  // Setup HLSL External Sema Source
+  if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
+IntrusiveRefCntPtr HLSLSema(
+new HLSLExternalSemaSource());
+CI.getASTContext().setExternalSource(HLSLSema);
+  }
+
   FailureCleanup.release();
   return true;
 }

diff  --git a/clang/lib/Headers/hlsl/hlsl_basic_types.h 
b/clang/lib/Headers/hlsl/hlsl_basic_types.h
index 2069990f5c06c..e68715f1a6a45 100644
--- a/clang/lib/Headers/hlsl/hlsl_basic_types.h
+++ b/clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -27,38 +27,38 @@ typedef long int64_t;
 // built-in vector data types:
 
 #ifdef __HLSL_ENABLE_16_BIT
-typedef int16_t int16_t2 __attribute__((ext_vector_type(2)));
-typedef int16_t int16_t3 __attribute__((ext_vector_type(3)));
-typedef int16_t int16_t4 __attribute__((ext_vector_type(4)));
-typedef uint16_t uint16_t2 __attribute__((ext_vector_type(2)));
-typedef uint16_t uint16_t3 __attribute__((ext_vector_type(3)));
-typedef uint16_t uint16_t4 __attribute__((ext_vector_type(4)));
+typedef vector int16_t2;
+typedef vector int16_t3;
+typedef vector int16_t4;
+typedef vector uint16_t2;
+typedef vector uint16_t3;
+typedef vector uint16_t4;
 #endif
 
-typedef int int2 __attribute__((ext_vector_type(2)));
-typedef int int3 __attribute__((ext_vector_type(3)));
-typedef int int4 __attribute__((ext_vector_type(4)));
-typedef uint uint2 __attribute__((ext_vector_type(2)));
-typedef uint uint3 __attribute__((ext_vector_type(3)));
-typedef uint uint4 __attribute__((ext_vector_type(4)));
-typedef int64_t int64_t2 __attribute__((ext_vector_type(2)));
-typedef int64_t int64_t3 __attribute__((ext_vector_type(3)));
-typedef int64_t int64_t4 __attribute__((ext_vector_type(4)));
-typedef uint64_t uint64_t2 __attribute__((ext_vector_type(2)));
-typedef uint64_t uint64_t3 __attribute__((ext_vector_type(3)));
-typedef uint64_t uint64_t4 __attribute__((ext_vector_type(4)));
+typedef vector int2;
+typedef vector int3;
+typedef vector int4;
+typedef vector uint2;
+typedef 

[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed updated this revision to Diff 437980.
omarahmed added a comment.

Add Parse check


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127270/new/

https://reviews.llvm.org/D127270

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10130,6 +10130,42 @@
 "void delete(link p);\n",
 format("void new (link p);\n"
"void delete (link p);\n"));
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "int *d = delete(p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "int *d = delete (p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave;
+  EXPECT_EQ("new (buf) int;", format("new (buf) int;", AfterPlacementOperator));
+  EXPECT_EQ("new(buf) int;", format("new(buf) int;", AfterPlacementOperator));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
@@ -20308,6 +20344,24 @@
   SpaceBeforeParens,
   FormatStyle::SBPO_ControlStatementsExceptControlMacros);
 
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  Style.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Never",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Always",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Always);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Leave",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+
   Style.ColumnLimit = 123;
   FormatStyle BaseStyle = getLLVMStyle();
   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3393,6 +3393,18 @@
 if (Left.is(TT_IfMacro))
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore()))
+return true;
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 if (Left.is(tok::semi))
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -936,6 +936,7 @@
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", 

[PATCH] D127923: [Diagnostics] Accept newline and format diag opts on first line

2022-06-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:99-103
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else
+OutStr = (PD->getShortDescription() + WarningMsg).str();

scott.linder wrote:
> It's frustrating that `std::string::insert` doesn't follow the pattern of 
> `npos==end-of-string`, but I'd still suggest only doing the actual 
> insert/append once
Or to be more precise, I would try to only have one piece of code doing the 
insert/append


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127923/new/

https://reviews.llvm.org/D127923

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


[PATCH] D127923: [Diagnostics] Accept newline and format diag opts on first line

2022-06-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added a comment.

Thank you for the patch! I will leave it to others with more knowledge of the 
history of diagnostics to comment on whether the premise is acceptable, but I 
have a few technical comments




Comment at: clang/lib/Frontend/TextDiagnosticPrinter.cpp:119-135
+  // If the diagnostic message is formatted into multiple lines, split the
+  // first line and feed it into printDiagnosticOptions so that we print the
+  // options only on the first line instead of the last line.
+  SmallString<100> InitStr;
+  size_t NewlinePos = OutStr.find_first_of('\n');
+  if (NewlinePos != StringRef::npos) {
+for (size_t I = 0; I != NewlinePos; ++I)

Nit: I'd remove the `if`s and just use the behavior of `slice(npos, ...)` 
returning the empty string

I also would reword "split the first line and feed it into 
printDiagnosticOptions", as it could be interpreted as meaning the first line 
is an input to `printDiagnosticOptions`



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:99-103
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else
+OutStr = (PD->getShortDescription() + WarningMsg).str();

It's frustrating that `std::string::insert` doesn't follow the pattern of 
`npos==end-of-string`, but I'd still suggest only doing the actual 
insert/append once



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:100
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);

I believe they are guaranteed to be equivalent, but this should be 
`StringRef::npos` or you should allocate the `std::string` sooner



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:101
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else

I think you incur an extra copy assignment here, as the `insert` returns an 
lvalue-reference


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127923/new/

https://reviews.llvm.org/D127923

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


[PATCH] D127643: [Static Analyzer] Structured bindings to data members

2022-06-17 Thread Domján Dániel via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe77ac66b8c1c: [Static Analyzer] Structured binding to data 
members (authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127643/new/

https://reviews.llvm.org/D127643

Files:
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/uninit-structured-binding-struct.cpp

Index: clang/test/Analysis/uninit-structured-binding-struct.cpp
===
--- /dev/null
+++ clang/test/Analysis/uninit-structured-binding-struct.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -std=c++17 -verify %s
+
+void clang_analyzer_eval(bool);
+
+struct s {
+  int a;
+  int b;
+};
+
+void a(void) {
+  s tst;
+
+  auto [i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void b(void) {
+  s tst;
+  tst.a = 1;
+
+  auto [i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void c(void) {
+  s tst;
+
+  auto &[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void d(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  i = 2;
+  clang_analyzer_eval(tst.a == 2); // expected-warning{{TRUE}}
+
+  int y = j; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void e(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+
+  tst.b = 2;
+  clang_analyzer_eval(j == 2); // expected-warning{{TRUE}}
+}
+
+void f(void) {
+  s tst;
+
+  auto &&[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void g(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &&[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+struct s2 {
+  int a = 1;
+  int b = 2;
+};
+
+struct s3 {
+  s x;
+  s2 y;
+};
+
+void h(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto [i, j] = tst;
+
+  // FIXME: These should be undefined, but we have to fix
+  // reading undefined from lazy compound values first.
+  clang_analyzer_eval(i.a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(i.b); // expected-warning{{UNKNOWN}}
+
+  clang_analyzer_eval(j.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
+
+void i(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto &[i, j] = tst;
+  j.a = 3;
+
+  clang_analyzer_eval(tst.y.a == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(tst.y.b == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2591,9 +2591,22 @@
 // operator&.
 return;
   }
-  if (isa(D)) {
-// FIXME: proper support for bound declarations.
-// For now, let's just prevent crashing.
+  if (const auto *BD = dyn_cast(D)) {
+const auto *DD = cast(BD->getDecomposedDecl());
+
+if (const auto *ME = dyn_cast(BD->getBinding())) {
+  const auto *Field = cast(ME->getMemberDecl());
+
+  SVal Base = state->getLValue(DD, LCtx);
+  if (DD->getType()->isReferenceType()) {
+Base = state->getSVal(Base.getAsRegion());
+  }
+
+  SVal V = state->getLValue(Field, Base);
+
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+}
+
 return;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e77ac66 - [Static Analyzer] Structured binding to data members

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T19:50:10+02:00
New Revision: e77ac66b8c1cf4f09f931d37749ed258f122d708

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

LOG: [Static Analyzer] Structured binding to data members

Introducing structured binding to data members.

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

Added: 
clang/test/Analysis/uninit-structured-binding-struct.cpp

Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index a0c7dda896ef2..6ba19d52488c7 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2591,9 +2591,22 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
 // operator&.
 return;
   }
-  if (isa(D)) {
-// FIXME: proper support for bound declarations.
-// For now, let's just prevent crashing.
+  if (const auto *BD = dyn_cast(D)) {
+const auto *DD = cast(BD->getDecomposedDecl());
+
+if (const auto *ME = dyn_cast(BD->getBinding())) {
+  const auto *Field = cast(ME->getMemberDecl());
+
+  SVal Base = state->getLValue(DD, LCtx);
+  if (DD->getType()->isReferenceType()) {
+Base = state->getSVal(Base.getAsRegion());
+  }
+
+  SVal V = state->getLValue(Field, Base);
+
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+}
+
 return;
   }
 

diff  --git a/clang/test/Analysis/uninit-structured-binding-struct.cpp 
b/clang/test/Analysis/uninit-structured-binding-struct.cpp
new file mode 100644
index 0..fec82c0d8589d
--- /dev/null
+++ b/clang/test/Analysis/uninit-structured-binding-struct.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-std=c++17 -verify %s
+
+void clang_analyzer_eval(bool);
+
+struct s {
+  int a;
+  int b;
+};
+
+void a(void) {
+  s tst;
+
+  auto [i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void b(void) {
+  s tst;
+  tst.a = 1;
+
+  auto [i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+void c(void) {
+  s tst;
+
+  auto &[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void d(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  i = 2;
+  clang_analyzer_eval(tst.a == 2); // expected-warning{{TRUE}}
+
+  int y = j; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void e(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+
+  tst.b = 2;
+  clang_analyzer_eval(j == 2); // expected-warning{{TRUE}}
+}
+
+void f(void) {
+  s tst;
+
+  auto &&[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void g(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &&[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+struct s2 {
+  int a = 1;
+  int b = 2;
+};
+
+struct s3 {
+  s x;
+  s2 y;
+};
+
+void h(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto [i, j] = tst;
+
+  // FIXME: These should be undefined, but we have to fix
+  // reading undefined from lazy compound values first.
+  clang_analyzer_eval(i.a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(i.b); // expected-warning{{UNKNOWN}}
+
+  clang_analyzer_eval(j.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
+
+void i(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto &[i, j] = tst;
+  j.a = 3;
+
+  clang_analyzer_eval(tst.y.a == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(tst.y.b == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}



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


[PATCH] D128048: Add a new clang option "-ftime-trace-path"

2022-06-17 Thread Jamie Schmeiser via Phabricator via cfe-commits
jamieschmeiser requested changes to this revision.
jamieschmeiser added a comment.
This revision now requires changes to proceed.

This is a good start.  You should mention in the summary that when -c is not 
specified, the compiler is invoked with -o pointing at /tmp so the .json file 
will currently be placed there, which is confusing.




Comment at: clang/include/clang/Driver/Options.td:2832
+def ftime_trace_path : Joined<["-"], "ftime-trace-path=">, Group,
+  HelpText<"Path which stores the output files of time profiler">,
+  Flags<[CC1Option, CoreOption]>,

which specifies the output files for -ftime-trace



Comment at: clang/tools/driver/cc1_main.cpp:259
+
Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(

What happens if the path specified does not exist?  This needs to be handled 
(if it isn't) and needs a lit test for this situation also.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128048/new/

https://reviews.llvm.org/D128048

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


[PATCH] D128013: [clang][dataflow] Add support for comma binary operator

2022-06-17 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGba53906ceff1: [clang][dataflow] Add support for comma binary 
operator (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128013/new/

https://reviews.llvm.org/D128013

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int  = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int  = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ba53906 - [clang][dataflow] Add support for comma binary operator

2022-06-17 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-06-17T17:48:21Z
New Revision: ba53906ceff1e7979cac37ff6fdc27e976fc169a

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

LOG: [clang][dataflow] Add support for comma binary operator

Add support for comma binary operator.

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

Reviewed-by: ymandel, xazax.hun

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index a56e277f7962f..befd3c6263114 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@ class TransferVisitor : public 
ConstStmtVisitor {
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index e3c97367b17ca..ab51bf2196b79 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@ TEST_F(TransferTest, 
StructuredBindingAssignFromStructIntMembersToInts) {
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int  = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace



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


[PATCH] D127277: [clang][analyzer] Fix StdLibraryFunctionsChecker 'mkdir' return value.

2022-06-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

It feels like the parent revision is not correct.
Land it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127277/new/

https://reviews.llvm.org/D127277

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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed added a comment.

As I understand, the default behavior for when the user didn't use 
`SBPO_Custom` is to add a space in placement operators based on this issue 
. And, at the same time, the 
default behavior should be `APO_Never` when we have `SBPO_Custom` so that we 
handle other code that depends on that. the existing tests confirm this 
understanding. So, the current logic was added based on this understanding.




Comment at: clang/lib/Format/TokenAnnotator.cpp:3396
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&

MyDeveloperDay wrote:
> shouldn't the very first part of this be? 
> 
> 
> ```
> if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
> FormatStyle::SpaceBeforeParensCustom::APO_Leave)
> {
> 
> 
> 
> }
> ```
> 
> i.e. don't we want a zero change if someone says "Leave"
The current code logic, when we do not enter this suggested condition, will 
switch to [this 
condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580).
 And will not leave the code as it is, but will change it.

I have thought of getting rid of this condition entirely, but it handles the 
default situation suggested here, not only for cpp but for other languages like 
js:
>>As I understand, the default behavior for when the user didn't use 
>>`SBPO_Custom` is to add a space in placement operators based on [this 
>>issue](https://github.com/llvm/llvm-project/issues/54703). And, at the same 
>>time, the default behavior should be `APO_Never` when we have `SBPO_Custom` 
>>so that we handle other code that depends on that. the existing tests confirm 
>>this understanding. So, the current logic was added based on this 
>>understanding.

I tried to add an extra condition to [this 
condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580)
 to support the main logic that we are pursuing. so that it would be like that:
```
if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
FormatStyle::SpaceBeforeParensCustom::APO_Leave && Left.isOneOf(tok::kw_new, 
tok::kw_delete))
```
But that wouldn't fix the leave situation, as it will be also at the end, reach 
[this 
part](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3598)
 which will  
```
return false
``` 
and force no space.

I think all of that was raised because all current 
"SpaceBeforeParanthesesOptions" are either true or false and this is the only 
enum

However, I completely agree with this logic which is to begin our checking for 
leave. But I think we should refactor all the "spaceBeforeParenthesesOptions" 
conditions to handle this and do that after all the options have been 
transformed to enums.



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127270/new/

https://reviews.llvm.org/D127270

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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed updated this revision to Diff 437966.
omarahmed marked an inline comment as not done.
omarahmed added a comment.

Refactor the tests and add new parsing logic for nested enums in 
dump_format_style.py


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127270/new/

https://reviews.llvm.org/D127270

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10130,6 +10130,42 @@
 "void delete(link p);\n",
 format("void new (link p);\n"
"void delete (link p);\n"));
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "int *d = delete(p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "int *d = delete (p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave;
+  EXPECT_EQ("new (buf) int;", format("new (buf) int;", AfterPlacementOperator));
+  EXPECT_EQ("new(buf) int;", format("new(buf) int;", AfterPlacementOperator));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3393,6 +3393,18 @@
 if (Left.is(TT_IfMacro))
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore()))
+return true;
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 if (Left.is(tok::semi))
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -936,6 +936,7 @@
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
 IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
+IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
 IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
 IO.mapOptional("AfterRequiresInExpression",
Spacing.AfterRequiresInExpression);
@@ -944,6 +945,22 @@
   }
 };
 
+template <>
+struct MappingTraits<
+FormatStyle::SpaceBeforeParensCustom::AfterPlacementOperatorStyle> {
+  static void
+  mapping(IO ,
+  FormatStyle::SpaceBeforeParensCustom::AfterPlacementOperatorStyle
+  ) {
+IO.enumCase(Value, "Always",
+FormatStyle::SpaceBeforeParensCustom::APO_Always);
+IO.enumCase(Value, "Never",
+FormatStyle::SpaceBeforeParensCustom::APO_Never);
+IO.enumCase(Value, "Leave",
+FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+  }
+};
+
 template <> struct MappingTraits {
   static void mapping(IO , 

[PATCH] D113107: Support of expression granularity for _Float16.

2022-06-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam marked 2 inline comments as done.
zahiraam added inline comments.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:896
+
+ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E) {
+  if (auto *BinOp = dyn_cast(E->IgnoreParens())) {

rjmccall wrote:
> `EmitPromoted` should take the promotion type.
> 
> You are missing the logic in this file which handles *unpromoted* emission 
> (where you have a binary operator but the context wants an unpromoted value) 
> by recognizing that you need to do a promoted operation and then truncate.
Sorry but not sure what you mean here. A case where we don't want any promotion 
would be:

float _Complex add(float _Complex a, float _Complex b) {
  return a + b;
}

In this case, getPromotionType would return the null type and EmitBinOps would 
just go through the  "older" control path where there is no promotion.
Unless I misunderstood your comment?




CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113107/new/

https://reviews.llvm.org/D113107

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


[PATCH] D128072: [clang-tidy] Organize test files into subdirectories by module (NFC)

2022-06-17 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood created this revision.
LegalizeAdulthood added reviewers: njames93, aaron.ballman.
LegalizeAdulthood added a project: clang-tools-extra.
Herald added subscribers: bzcheeseman, carlosgalvezp, abrachet, lebedev.ri, 
jdoerfert, arphaman, zzheng, kbarton, xazax.hun, nemanjai.
Herald added a reviewer: lebedev.ri.
Herald added a reviewer: lebedev.ri.
Herald added a project: All.
LegalizeAdulthood requested review of this revision.
Herald added a subscriber: aheejin.

Eliminate clutter by reorganizing the Lit test files for clang-tidy:

- Move checkers/-* to checkers//*.
- Move module specific inputs from Inputs to /Inputs.  Remove any 
module prefix from the file or subdirectory name as they are no longer needed.
- Introduce a Lit substitution %clang_tidy_headers for the system headers in 
checkers/Inputs/Headers and use this throughout.  This avoids referencing 
system headers through a relative path to the parent directory and makes it 
clear that these fake system headers are shared among all modules.
- Update add_new_check.py to follow the above conventions when creating the 
boiler plate test files for a new check.
- Update Contributing.rst to describe per-module Inputs directory and fix link 
to test source code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128072

Files:
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/docs/clang-tidy/Contributing.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/external-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/flags/internal-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/strings/internal-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/time/time.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/Verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/kernel.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/other_Verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/otherdir/vhdl.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/otherthing.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/dir/kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/kernel.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/verilog.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/vhdl.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some_kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/somedir/verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/thing.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/KERNEL.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/VHDL.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/vERILOG.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/verilog.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl.CL
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl_number_two.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-not-null-terminated-result/not-null-terminated-result-c.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-not-null-terminated-result/not-null-terminated-result-cxx.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-reserved-identifier/system/system-header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-reserved-identifier/user-header.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/google-namespaces.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/gtest-typed-test.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/gtest.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/nosuite/gtest/gtest-typed-test.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/nosuite/gtest/gtest.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/llvmlibc/resource/include/stdatomic.h
  

[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

jackhong12 wrote:
> HazardyKnusperkeks wrote:
> > Unknown is everything, until some type is assigned. This way it should be 
> > clearer.
> > 
> > Also put that check above the other one and add the `r_brace` back.
> There are other problems. Clang-format will split the input into multiple 
> lines first. For instance, `struct {\n int n;\n} &={};` will be separated 
> as `struct {`, `int n;` and `} &={};`. It only handles the relation in 
> the line. When declaring a struct variable, the value of `MatchingParen` will 
> always be NULL instead of pointing to the last left brace. So it will not 
> enter that branch in this case.
```
if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
PrevToken->MatchingParen) {
  if (PrevToken->MatchingParen->is(TT_RecordLBrace))
return TT_PointerOrReference;
  else
return TT_BinaryOperator;
}
```
How about this way? Although the branch of TT_PointerOrReference will not be 
taken, it's clearer for reading.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127873/new/

https://reviews.llvm.org/D127873

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


[PATCH] D126973: [clang][dataflow] Relax assumption that `AggregateStorageLocations` correspond to struct type.

2022-06-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel abandoned this revision.
ymandel added a comment.

In D126973#3592537 , @xazax.hun wrote:

> With properties moved up in the hierarchy this could be abandoned now, right?

Yes, I think that would be best. Thanks for the reminder!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126973/new/

https://reviews.llvm.org/D126973

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


[PATCH] D126973: [clang][dataflow] Relax assumption that `AggregateStorageLocations` correspond to struct type.

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.
Herald added a subscriber: martong.

With properties moved up in the hierarchy this could be abandoned now, right?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126973/new/

https://reviews.llvm.org/D126973

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


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

HazardyKnusperkeks wrote:
> Unknown is everything, until some type is assigned. This way it should be 
> clearer.
> 
> Also put that check above the other one and add the `r_brace` back.
There are other problems. Clang-format will split the input into multiple lines 
first. For instance, `struct {\n int n;\n} &={};` will be separated as 
`struct {`, `int n;` and `} &={};`. It only handles the relation in the 
line. When declaring a struct variable, the value of `MatchingParen` will 
always be NULL instead of pointing to the last left brace. So it will not enter 
that branch in this case.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127873/new/

https://reviews.llvm.org/D127873

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


[PATCH] D127898: [clang][dataflow] Find unsafe locs after fixpoint

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:66
+  SourceLocations Locs;
+  for (const CFGBlock *Block : Context->getCFG()) {
+// Skip blocks that were not evaluated.

While doing yet another iteration after we reached the fixed point is a valid 
approach, many analyses have a monotonic property when it comes to emitting 
diagnostics. In this case, when the analysis discovered that an optional access 
is unsafe in one of the iterations I would not expect it to become safe in 
subsequent iterations. In most of the cases this makes collecting diagnostics 
eagerly a viable option and saves us from doing one more traversal of the CFG. 
On the other hand, we need to be careful to not to emit duplicate diagnostics.

I wonder whether, from a user point of view, not having to do one more 
iteration is a more ergonomic interface. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127898/new/

https://reviews.llvm.org/D127898

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


[PATCH] D127509: Prefer `getCurrentFileOrBufferName` in `FrontendAction::EndSourceFile`

2022-06-17 Thread Yuki Okushi via Phabricator via cfe-commits
JohnTitor added a comment.

I've re-triggered it several times but it shows the same failure, maybe they're 
valid?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127509/new/

https://reviews.llvm.org/D127509

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


[PATCH] D127313: [libc++] Implement P0618R0 (Deprecating )

2022-06-17 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik updated this revision to Diff 437951.
philnik added a comment.

- Try to fix CI


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127313/new/

https://reviews.llvm.org/D127313

Files:
  libcxx/docs/ReleaseNotes.rst
  libcxx/docs/Status/Cxx17Papers.csv
  libcxx/include/codecvt
  libcxx/include/locale
  libcxx/src/locale.cpp
  
libcxx/test/libcxx/localization/locales/locale.convenience/conversions/conversions.string/ctor_move.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_mode.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_always_noconv.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_unshift.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_always_noconv.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_unshift.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_always_noconv.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_length.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_unshift.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/ctor.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/overflow.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/pbackfail.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/rdbuf.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/seekoff.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/test.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/underflow.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/converted.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_codecvt.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_codecvt_state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_copy.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_err_string.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/from_bytes.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/to_bytes.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/types.pass.cpp
  libcxx/test/support/platform_support.h

Index: libcxx/test/support/platform_support.h
===
--- libcxx/test/support/platform_support.h
+++ libcxx/test/support/platform_support.h
@@ -14,6 +14,8 @@
 #ifndef PLATFORM_SUPPORT_H
 #define PLATFORM_SUPPORT_H
 
+#include "test_macros.h"
+
 // locale names
 #define LOCALE_en_US   "en_US"
 #define LOCALE_en_US_UTF_8 "en_US.UTF-8"
@@ -92,8 +94,11 @@
 inline
 std::wstring get_wide_temp_file_name()
 {
+TEST_DIAGNOSTIC_PUSH

[PATCH] D128064: [Static Analyzer] Small array binding policy

2022-06-17 Thread Domján Dániel via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG92bf652d4074: [Static Analyzer] Small array binding policy 
(authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D128064?vs=437912=437950#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128064/new/

https://reviews.llvm.org/D128064

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/analyzer-config.c

Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -114,6 +114,7 @@
 // CHECK-NEXT: osx.NumberObjectConversion:Pedantic = false
 // CHECK-NEXT: osx.cocoa.RetainCount:TrackNSCFStartParam = false
 // CHECK-NEXT: prune-paths = true
+// CHECK-NEXT: region-store-small-array-limit = 5
 // CHECK-NEXT: region-store-small-struct-limit = 2
 // CHECK-NEXT: report-in-main-source-file = false
 // CHECK-NEXT: serialize-stats = false
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -345,6 +345,16 @@
   /// To disable all small-struct-dependent behavior, set the option to "0".
   unsigned SmallStructLimit;
 
+  /// The largest number of element an array can have and still be
+  /// considered "small".
+  ///
+  /// This is currently used to decide whether or not it is worth "forcing" a
+  /// LazyCompoundVal on bind.
+  ///
+  /// This is controlled by 'region-store-small-struct-limit' option.
+  /// To disable all small-struct-dependent behavior, set the option to "0".
+  unsigned SmallArrayLimit;
+
   /// A helper used to populate the work list with the given set of
   /// regions.
   void populateWorkList(InvalidateRegionsWorker ,
@@ -354,10 +364,11 @@
 public:
   RegionStoreManager(ProgramStateManager )
   : StoreManager(mgr), RBFactory(mgr.getAllocator()),
-CBFactory(mgr.getAllocator()), SmallStructLimit(0) {
+CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) {
 ExprEngine  = StateMgr.getOwningEngine();
 AnalyzerOptions  = Eng.getAnalysisManager().options;
 SmallStructLimit = Options.RegionStoreSmallStructLimit;
+SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
   }
 
   /// setImplicitDefaultValue - Set the default binding for the provided
@@ -487,6 +498,11 @@
   RegionBindingsRef bindVector(RegionBindingsConstRef B,
const TypedValueRegion* R, SVal V);
 
+  Optional tryBindSmallArray(RegionBindingsConstRef B,
+const TypedValueRegion *R,
+const ArrayType *AT,
+nonloc::LazyCompoundVal LCV);
+
   RegionBindingsRef bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
   SVal V);
@@ -2392,6 +2408,40 @@
   return B.addBinding(R, BindingKey::Default, V);
 }
 
+Optional RegionStoreManager::tryBindSmallArray(
+RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
+nonloc::LazyCompoundVal LCV) {
+
+  auto CAT = dyn_cast(AT);
+
+  // If we don't know the size, create a lazyCompoundVal instead.
+  if (!CAT)
+return None;
+
+  QualType Ty = CAT->getElementType();
+  if (!(Ty->isScalarType() || Ty->isReferenceType()))
+return None;
+
+  // If the array is too big, create a LCV instead.
+  uint64_t ArrSize = CAT->getSize().getLimitedValue();
+  if (ArrSize > SmallArrayLimit)
+return None;
+
+  RegionBindingsRef NewB = B;
+
+  for (uint64_t i = 0; i < ArrSize; ++i) {
+auto Idx = svalBuilder.makeArrayIndex(i);
+const ElementRegion *SrcER =
+MRMgr.getElementRegion(Ty, Idx, LCV.getRegion(), Ctx);
+SVal V = getBindingForElement(getRegionBindings(LCV.getStore()), SrcER);
+
+const ElementRegion *DstER = MRMgr.getElementRegion(Ty, Idx, R, Ctx);
+NewB = bind(NewB, loc::MemRegionVal(DstER), V);
+  }
+
+  return NewB;
+}
+
 RegionBindingsRef
 RegionStoreManager::bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
@@ -2413,8 +2463,13 @@
   }
 
   // Handle lazy compound values.
-  if (isa(Init))
+  if (Optional LCV =
+  Init.getAs()) {
+if (Optional NewB = tryBindSmallArray(B, R, AT, *LCV))
+  return *NewB;
+
 return bindAggregate(B, R, Init);
+  }
 
   if (Init.isUnknown())
 return bindAggregate(B, R, UnknownVal());
Index: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===

[clang] 92bf652 - [Static Analyzer] Small array binding policy

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:56:13+02:00
New Revision: 92bf652d40740b947de6c41fe09f282ec0530dc5

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

LOG: [Static Analyzer] Small array binding policy

If a lazyCompoundVal to a struct is bound to the store, there is a policy which 
decides
whether a copy gets created instead.

This patch introduces a similar policy for arrays, which is required to model 
structured
binding to arrays without false negatives.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/test/Analysis/analyzer-config.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index d7075fb39fc89..9974ea9392acb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -440,11 +440,19 @@ ANALYZER_OPTION(
 ANALYZER_OPTION(
 unsigned, RegionStoreSmallStructLimit, "region-store-small-struct-limit",
 "The largest number of fields a struct can have and still be considered "
-"small This is currently used to decide whether or not it is worth forcing 
"
+"small. This is currently used to decide whether or not it is worth 
forcing "
 "a LazyCompoundVal on bind. To disable all small-struct-dependent "
 "behavior, set the option to 0.",
 2)
 
+ANALYZER_OPTION(
+unsigned, RegionStoreSmallArrayLimit, "region-store-small-array-limit",
+"The largest number of elements an array can have and still be considered "
+"small. This is currently used to decide whether or not it is worth 
forcing "
+"a LazyCompoundVal on bind. To disable all small-array-dependent "
+"behavior, set the option to 0.",
+5)
+
 
//===--===//
 // String analyzer options.
 
//===--===//

diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 8a50cb27c8d3a..b432247bad7d8 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -345,6 +345,16 @@ class RegionStoreManager : public StoreManager {
   /// To disable all small-struct-dependent behavior, set the option to "0".
   unsigned SmallStructLimit;
 
+  /// The largest number of element an array can have and still be
+  /// considered "small".
+  ///
+  /// This is currently used to decide whether or not it is worth "forcing" a
+  /// LazyCompoundVal on bind.
+  ///
+  /// This is controlled by 'region-store-small-struct-limit' option.
+  /// To disable all small-struct-dependent behavior, set the option to "0".
+  unsigned SmallArrayLimit;
+
   /// A helper used to populate the work list with the given set of
   /// regions.
   void populateWorkList(InvalidateRegionsWorker ,
@@ -354,10 +364,11 @@ class RegionStoreManager : public StoreManager {
 public:
   RegionStoreManager(ProgramStateManager )
   : StoreManager(mgr), RBFactory(mgr.getAllocator()),
-CBFactory(mgr.getAllocator()), SmallStructLimit(0) {
+CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) 
{
 ExprEngine  = StateMgr.getOwningEngine();
 AnalyzerOptions  = Eng.getAnalysisManager().options;
 SmallStructLimit = Options.RegionStoreSmallStructLimit;
+SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
   }
 
   /// setImplicitDefaultValue - Set the default binding for the provided
@@ -487,6 +498,11 @@ class RegionStoreManager : public StoreManager {
   RegionBindingsRef bindVector(RegionBindingsConstRef B,
const TypedValueRegion* R, SVal V);
 
+  Optional tryBindSmallArray(RegionBindingsConstRef B,
+const TypedValueRegion *R,
+const ArrayType *AT,
+nonloc::LazyCompoundVal LCV);
+
   RegionBindingsRef bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
   SVal V);
@@ -2392,6 +2408,40 @@ 
RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
   return B.addBinding(R, BindingKey::Default, V);
 }
 
+Optional RegionStoreManager::tryBindSmallArray(
+RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
+nonloc::LazyCompoundVal LCV) {
+
+  auto CAT = dyn_cast(AT);
+
+  // If we don't know the size, create a lazyCompoundVal instead.
+  if 

[PATCH] D128056: [clang][dataflow] Singleton pointer values for null pointers.

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I am wondering about the future plans regarding how pointers are represented.
What will be the expected behavior when the analysis discovers that the pointer 
has a null value? E.g.:

  if (p == nullptr)
  {

  }

Would we expect `p` in this case to have the same singleton value in the then 
block of the if statement?




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:146
+  ///  `PointeeType`.
+  void setNullPointerVal(QualType PointeeType, PointerValue ) {
+assert(NullPointerVals.find(PointeeType.getAsString()) ==

Since you always want this function to create a null pointer value, I think it 
would be less error prone to ask for the location instead of an arbitrary 
value. Currently, a confused caller could put a non-null value into a table. 



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:149
+   NullPointerVals.end());
+NullPointerVals[PointeeType.getAsString()] = 
+  }

I think `getAsString` is considered expensive. Could you use `QualType` 
directly as the key?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128056/new/

https://reviews.llvm.org/D128056

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


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:92
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();

Do we support `DoStmt` or is that missing?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128060/new/

https://reviews.llvm.org/D128060

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


[PATCH] D127993: [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl

2022-06-17 Thread Domján Dániel via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfc6b2281bfd7: [Static Analyzer][CFG] Introducing the source 
array in the CFG of… (authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D127993?vs=437859=437943#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127993/new/

https://reviews.llvm.org/D127993

Files:
  clang/lib/Analysis/CFG.cpp
  clang/test/Analysis/cfg.cpp


Index: clang/test/Analysis/cfg.cpp
===
--- clang/test/Analysis/cfg.cpp
+++ clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
+"OpaqueValueExpr!");
+  if (CFGBlock *R = Visit(OVE->getSourceExpr()))
+B = R;
+
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
   // ObjCAtCatchStmt are treated like labels, so they are the first statement
   // in a block.


Index: clang/test/Analysis/cfg.cpp
===
--- clang/test/Analysis/cfg.cpp
+++ clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() 

[clang] fc6b228 - [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:34:34+02:00
New Revision: fc6b2281bfd747b3e24d23e2ee8de189f741770f

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

LOG: [Static Analyzer][CFG] Introducing the source array in the CFG of 
DecompositionDecl

For DecompositionDecl, the array, which is being decomposed was not present in 
the
CFG, which lead to the liveness analysis falsely detecting it as a dead symbol.

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

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/test/Analysis/cfg.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 8379e108fa27b..b16898d3ffa0b 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@ class CFGBuilder {
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@ CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
+"OpaqueValueExpr!");
+  if (CFGBlock *R = Visit(OVE->getSourceExpr()))
+B = R;
+
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
   // ObjCAtCatchStmt are treated like labels, so they are the first statement
   // in a block.

diff  --git a/clang/test/Analysis/cfg.cpp b/clang/test/Analysis/cfg.cpp
index 333ea565287b2..df4c7b32fb685 100644
--- a/clang/test/Analysis/cfg.cpp
+++ b/clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@ int crash_with_thread_local(char *p, int *q) {
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1



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


[PATCH] D126779: [analyzer] Fix assertion in simplifySymbolCast

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1082
+  // FIXME support cast from non-integers.
+  // E.g (char)(double)(double x) -> (char)(double x)
+  if (!RT->isIntegralOrEnumerationType())

steakhal wrote:
> Well, I would expect the same, but crosscheck this with the actual dump.
Please elaborate.



Comment at: clang/test/Analysis/produce-symbolcast_x86.cpp:16
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((double) ((reg_$0) / 30))}}
+  char C = D;

steakhal wrote:
> Place here a FIXME that we should not have two double casts.
The `(double)(double)` problem is handled in the parent patch. Please check 
that out.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126779/new/

https://reviews.llvm.org/D126779

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-06-17 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 437940.
royjacobson added a comment.

Fix the AST test on windows and rebase on HEAD.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126194/new/

https://reviews.llvm.org/D126194

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/ast-dump-decl.cpp
  clang/test/AST/overloaded-destructors.cpp
  clang/test/CXX/class/class.dtor/p4.cpp
  clang/test/CXX/over/over.match/over.match.viable/p3.cpp
  clang/test/SemaTemplate/destructor-template.cpp

Index: clang/test/SemaTemplate/destructor-template.cpp
===
--- clang/test/SemaTemplate/destructor-template.cpp
+++ clang/test/SemaTemplate/destructor-template.cpp
@@ -98,7 +98,7 @@
   template 
   ~S(); // expected-error{{destructor cannot be declared as a template}}
 };
-struct T : S {// expected-note{{destructor of 'T' is implicitly deleted because base class 'PR38671::S' has no destructor}}
-  ~T() = default; // expected-warning{{explicitly defaulted destructor is implicitly deleted}}
+struct T : S {
+  ~T() = default;
 };
 } // namespace PR38671
Index: clang/test/CXX/over/over.match/over.match.viable/p3.cpp
===
--- clang/test/CXX/over/over.match/over.match.viable/p3.cpp
+++ clang/test/CXX/over/over.match/over.match.viable/p3.cpp
@@ -49,7 +49,6 @@
   S(A) requires false;
   S(double) requires true;
   ~S() requires false;
-  // expected-note@-1 2{{because 'false' evaluated to false}}
   ~S() requires true;
   operator int() requires true;
   operator int() requires false;
@@ -58,11 +57,7 @@
 void bar() {
   WrapsStatics::foo(A{});
   S{1.}.foo(A{});
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
-  // Note - this behavior w.r.t. constrained dtors is a consequence of current
-  // wording, which does not invoke overload resolution when a dtor is called.
-  // P0848 is set to address this issue.
+
   S s = 1;
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
   int a = s;
 }
Index: clang/test/CXX/class/class.dtor/p4.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.dtor/p4.cpp
@@ -0,0 +1,77 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+struct A {
+  ~A() = delete;  // expected-note {{explicitly marked deleted}}
+  ~A() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+// FIXME: We should probably make it illegal to mix virtual and non-virtual methods
+// this way. See CWG2488 and some discussion in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105699.
+template 
+struct B {
+  ~B() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+  virtual ~B() = delete;  // expected-note {{explicitly marked deleted}}
+};
+
+template 
+concept CO1 = N == 1;
+
+template 
+concept CO2 = N >
+0;
+
+template 
+struct C {
+  ~C() = delete; // expected-note {{explicitly marked deleted}}
+  ~C() requires(CO1) = delete;
+  ~C() requires(CO1 &) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct D {
+  ~D() requires(N != 0) = delete; // expected-note {{explicitly marked deleted}}
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+  ~D() requires(N == 1) = delete;
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+};
+
+template 
+concept Foo = requires(T t) {
+  {t.foo()};
+};
+
+template 
+struct E {
+  void foo();
+  ~E();
+  ~E() requires Foo = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template struct A<1>;
+template struct A<2>;
+template struct B<1>;
+template struct B<2>;
+template struct C<1>;
+template struct C<2>;
+template struct D<0>; // expected-error {{no viable destructor found for class 'D<0>'}} expected-note {{in instantiation of template}}
+template struct D<1>; // expected-error {{destructor of class 'D<1>' is ambiguous}} expected-note {{in instantiation of template}}
+template struct D<2>;
+template struct E<1>;
+
+int main() {
+  A<1> a1; // expected-error {{attempt to use a deleted function}}
+  A<2> a2; // expected-error {{attempt to use a deleted function}}
+  B<1> b1; 

[PATCH] D126779: [analyzer] Fix assertion in simplifySymbolCast

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 437938.
martong added a comment.

- Rebase on dependent patch


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126779/new/

https://reviews.llvm.org/D126779

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/produce-symbolcast_x86.cpp


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 
30)}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((reg_$0) / 30))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) 
((reg_$0) / 30)))}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1104,6 +1104,10 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support simplification from non-integers.
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory  = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 30)}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((reg_$0) / 30))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) ((reg_$0) / 30)))}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1104,6 +1104,10 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support simplification from non-integers.
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory  = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D127873#3589465 , @jackhong12 
wrote:

> I think it's a good idea. When does `MatchingParen` bind? The value of 
> `PrevToken->MatchingParen` is still NULL in `determineStarAmpUsage` function.

What has changed, now you are using that.




Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

Unknown is everything, until some type is assigned. This way it should be 
clearer.

Also put that check above the other one and add the `r_brace` back.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127873/new/

https://reviews.llvm.org/D127873

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


[PATCH] D128068: [analyzer] Do not emit redundant SymbolCasts

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: steakhal, NoQ, ASDenysPetrov.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In RegionStore::getBinding we call `evalCast` unconditionally to align
the stored value's type to the one that is being queried. However, the
stored type might be the same, so we may end up having redundant
SymbolCasts emitted. The simplest solution is to check whether the `to`
and `from` type are the same in `makeNonLoc`. We can't just do that check
in `evalCast` because there are many additonal logic before we'd end up
in `makeNonLoc`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128068

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/symbolcast-floatingpoint.cpp


Index: clang/test/Analysis/symbolcast-floatingpoint.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbolcast-floatingpoint.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=false \
+// RUN:-verify %s
+
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-verify %s
+
+template 
+void clang_analyzer_dump(T);
+
+void test_no_redundant_floating_point_cast(int n) {
+
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 
30)}}
+
+  // There are two cast operations evaluated above:
+  // 1. (n / 30) is cast to a double during the store of `D`.
+  // 2. Then in the next line, in RegionStore::getBinding during the load of 
`D`.
+  //
+  // We should not see in the dump of the SVal any redundant casts like
+  // (double) ((double) $n / 30)
+
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -113,6 +113,8 @@
   QualType fromTy, QualType toTy) {
   assert(operand);
   assert(!Loc::isLocType(toTy));
+  if (fromTy == toTy)
+return operand;
   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
 }
 


Index: clang/test/Analysis/symbolcast-floatingpoint.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbolcast-floatingpoint.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=false \
+// RUN:-verify %s
+
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-verify %s
+
+template 
+void clang_analyzer_dump(T);
+
+void test_no_redundant_floating_point_cast(int n) {
+
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 30)}}
+
+  // There are two cast operations evaluated above:
+  // 1. (n / 30) is cast to a double during the store of `D`.
+  // 2. Then in the next line, in RegionStore::getBinding during the load of `D`.
+  //
+  // We should not see in the dump of the SVal any redundant casts like
+  // (double) ((double) $n / 30)
+
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -113,6 +113,8 @@
   QualType fromTy, QualType toTy) {
   assert(operand);
   assert(!Loc::isLocType(toTy));
+  if (fromTy == toTy)
+return operand;
   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127277: [clang][analyzer] Fix StdLibraryFunctionsChecker 'mkdir' return value.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437925.
balazske added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127277/new/

https://reviews.llvm.org/D127277

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -1904,44 +1904,40 @@
 ArgumentCondition(1, WithinRange, Range(0, SizeMax;
 
 // int mkdir(const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mkdirat(int dirfd, const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdirat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 
 Optional Dev_tTy = lookupTy("dev_t");
 
 // int mknod(const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknod",
 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknodat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, Dev_tTy},
   RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 


Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -1904,44 +1904,40 @@
 ArgumentCondition(1, WithinRange, Range(0, SizeMax;
 
 // int mkdir(const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mkdirat(int dirfd, const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdirat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 
 Optional Dev_tTy = lookupTy("dev_t");
 
 // int mknod(const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknod",
 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, 

[PATCH] D125400: [clang][Analyzer] Add errno state to standard functions modeling.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437924.
balazske marked 2 inline comments as done.
balazske added a comment.

Small fixes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125400/new/

https://reviews.llvm.org/D125400

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/errno-stdlibraryfunctions-notes.c
  clang/test/Analysis/errno-stdlibraryfunctions.c

Index: clang/test/Analysis/errno-stdlibraryfunctions.c
===
--- /dev/null
+++ clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -0,0 +1,56 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=apiModeling.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true
+
+#include "Inputs/errno_var.h"
+
+typedef typeof(sizeof(int)) size_t;
+typedef __typeof(sizeof(int)) off_t;
+typedef size_t ssize_t;
+ssize_t send(int sockfd, const void *buf, size_t len, int flags);
+off_t lseek(int fildes, off_t offset, int whence);
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+int unsafe_errno_read(int sock, void *data, int data_size) {
+  if (send(sock, data, data_size, 0) != data_size) {
+if (errno == 1) {
+  // expected-warning@-1{{An undefined value may be read from 'errno'}}
+  return 0;
+}
+  }
+  return 1;
+}
+
+int errno_lseek(int fildes, off_t offset) {
+  off_t result = lseek(fildes, offset, 0);
+  if (result == (off_t)-1) {
+// Failure path.
+// check if the function is modeled
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+return 2;
+  }
+  if (result != offset) {
+// Not success path (?)
+// not sure if this is a valid case, allow to check 'errno'
+if (errno == 1) { // no warning
+  return 1;
+}
+clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+  if (result == offset) {
+// The checker does not differentiate for this case.
+// In general case no relation exists between the arg 2 and the returned
+// value, only for SEEK_SET.
+if (errno == 1) { // no warning
+  return 1;
+}
+clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+  return 0;
+}
Index: clang/test/Analysis/errno-stdlibraryfunctions-notes.c
===
--- /dev/null
+++ clang/test/Analysis/errno-stdlibraryfunctions-notes.c
@@ -0,0 +1,49 @@
+// RUN: %clang_analyze_cc1 -verify -analyzer-output text %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=apiModeling.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true
+
+#include "Inputs/errno_var.h"
+
+int access(const char *path, int amode);
+
+void clang_analyzer_warnIfReached();
+
+void test1() {
+  access("path", 0); // no note here
+  access("path", 0);
+  // expected-note@-1{{Assuming that function 'access' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  if (errno != 0) {
+// expected-warning@-1{{An undefined value may be read from 'errno'}}
+// expected-note@-2{{An undefined value may be read from 'errno'}}
+  }
+}
+
+void test2() {
+  if (access("path", 0) == -1) {
+// expected-note@-1{{Taking true branch}}
+// Failure path.
+if (errno != 0) {
+  // expected-note@-1{{'errno' is not equal to 0}}
+  // expected-note@-2{{Taking true branch}}
+  clang_analyzer_warnIfReached(); // expected-note {{REACHABLE}} expected-warning {{REACHABLE}}
+} else {
+  clang_analyzer_warnIfReached(); // no-warning: We are on the failure path.
+}
+  }
+}
+
+void test3() {
+  if (access("path", 0) != -1) {
+// Success path.
+// expected-note@-2{{Assuming that function 'access' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+// expected-note@-3{{Taking true branch}}
+if (errno != 0) {
+  // expected-warning@-1{{An undefined value may be read from 'errno'}}
+  // expected-note@-2{{An undefined value may be read from 'errno'}}
+}
+  }
+}
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -40,6 +40,7 @@
 //
 //===--===//
 
+#include "ErrnoModeling.h"
 #include 

[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437922.
balazske marked 16 inline comments as done.
balazske added a comment.

Removed Errno_ prefix from ErrnoCheckState, documentation fixes, other small 
fixes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122150/new/

https://reviews.llvm.org/D122150

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/errno-notes.c
  clang/test/Analysis/errno-options.c
  clang/test/Analysis/errno.c

Index: clang/test/Analysis/errno.c
===
--- clang/test/Analysis/errno.c
+++ clang/test/Analysis/errno.c
@@ -3,6 +3,7 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_VAR
 
 // RUN: %clang_analyze_cc1 -verify %s \
@@ -10,8 +11,10 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_FUNC
 
+#include "Inputs/system-header-simulator.h"
 #ifdef ERRNO_VAR
 #include "Inputs/errno_var.h"
 #endif
@@ -24,6 +27,7 @@
 int ErrnoTesterChecker_getErrno();
 int ErrnoTesterChecker_setErrnoIfError();
 int ErrnoTesterChecker_setErrnoIfErrorRange();
+int ErrnoTesterChecker_setErrnoCheckState();
 
 void something();
 
@@ -61,3 +65,199 @@
 clang_analyzer_eval(errno == 1); // expected-warning{{FALSE}} expected-warning{{TRUE}}
   }
 }
+
+void testErrnoCheck0() {
+  // If the function returns a success result code, value of 'errno'
+  // is unspecified and it is unsafe to make any decision with it.
+  // The function did not promise to not change 'errno' if no failure happens.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+if (errno) { // no warning for second time (analysis stops at the first warning)
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+errno = 0;
+if (errno) { // no warning after overwritten 'errno'
+}
+  }
+}
+
+void testErrnoCheck1() {
+  // If the function returns error result code that is out-of-band (not a valid
+  // non-error return value) the value of 'errno' can be checked but it is not
+  // required to do so.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+if (errno) { // no warning
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+errno = 0; // no warning
+  }
+}
+
+void testErrnoCheck2() {
+  // If the function returns an in-band error result the value of 'errno' is
+  // required to be checked to verify if error happened.
+  // The same applies to other functions that can indicate failure only by
+  // change of 'errno'.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value of 'errno' was not checked and is overwritten here [alpha.unix.Errno]}}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value of 'errno' was not checked and is overwritten here [alpha.unix.Errno]}}
+if (errno) {
+}
+  }
+}
+
+void testErrnoCheck3() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+if (errno) {
+}
+errno = 0; // no warning after 'errno' was read
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+int A = errno;
+errno = 0; // no warning after 'errno' was read
+  }
+}
+
+void testErrnoCheckUndefinedLoad() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+  }
+}
+
+void testErrnoNotCheckedAtSystemCall() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+printf("%i", 1); // expected-warning{{Value of 'errno' was not checked and may be overwritten by function 'printf' [alpha.unix.Errno]}}
+printf("%i", 1); // no warning ('printf' does not change errno state)
+  }
+}
+
+void testErrnoCheckStateInvalidate() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) 

[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 437918.
sgatev added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128060/new/

https://reviews.llvm.org/D128060

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,88 @@
   });
 }
 
+TEST_F(TransferTest, BranchesExtendFlowCondition) {
+  std::string IfBranchCode = R"(
+void target(bool Foo) {
+  if (Foo) {
+(void)0;
+// [[if_then]]
+  } else {
+(void)0;
+// [[if_else]]
+  }
+}
+  )";
+  runDataflow(
+  IfBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results,
+ElementsAre(Pair("if_else", _), Pair("if_then", _)));
+const Environment  = Results[1].second.Env;
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(ThenEnv.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(ThenEnv.flowConditionImplies(ThenFooVal));
+
+BoolValue  =
+*cast(ElseEnv.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(ElseEnv.flowConditionImplies(ElseEnv.makeNot(ElseFooVal)));
+  });
+
+  std::string WhileBranchCode = R"(
+void target(bool Foo) {
+  while (Foo) {
+(void)0;
+// [[while_branch]]
+  }
+}
+  )";
+  runDataflow(WhileBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("while_branch", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+
+  std::string ForBranchCode = R"(
+void target(bool Foo) {
+  for (; Foo;) {
+(void)0;
+// [[for_branch]]
+  }
+}
+  )";
+  runDataflow(ForBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("for_branch", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -89,6 +89,12 @@
 extendFlowCondition(*Cond);
   }
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();
+assert(Cond != nullptr);
+extendFlowCondition(*Cond);
+  }
+
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
 auto *LHS = S->getLHS();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.

Mild preference for splitting into three tests, since it technically different 
code that's covered in each. But, up to you.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128060/new/

https://reviews.llvm.org/D128060

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


[PATCH] D127142: [HIP] Link with clang_rt.builtins

2022-06-17 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D127142#3590874 , @yaxunl wrote:

> In D127142#3571260 , @MaskRay wrote:
>
>> In D127142#3570290 , @yaxunl wrote:
>>
>>> If I use --rtlib=compiler-rt, does that also requires --unwindlib=unwindlib 
>>> ?
>>
>> No. --unwindlib=libunwind requires --rtlib=compiler-rt. --rtlib=compiler-rt 
>> is compatible with both --unwindlib=libgcc and --unwindlib=libunwind.
>
> If only use -rtlib=compiler-rt without changing unwind lib, I will get 
> missing symbol:
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: undefined symbol: _Unwind_Resume
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(generate_skipahead_file())
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(main)
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(std::function bool&)> reduce::ReduceOpFn2(miopenReduceTensorOp_t))
>
> [2022-06-16T20:05:28.644Z] >>> referenced 1246 more times
>
> [2022-06-16T20:05:28.644Z]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_Resume [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_Backtrace [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_GetIP [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] clang-15: error: linker command failed with exit 
> code 1 (use -v to see invocation)

If I use --rtlib=compiler-rt, do I have to explicitly add --unwindlib=libgcc or 
--unwindlib=libunwind? I suspect the linker is not linking the unwind library 
when -rtlib=compiler-rt is specified.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127142/new/

https://reviews.llvm.org/D127142

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


[PATCH] D128008: [clang][deps] Sort submodules when calculating dependencies

2022-06-17 Thread Ben Langmuir via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4a3a9a5fa0b2: [clang][deps] Sort submodules when calculating 
dependencies (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128008/new/

https://reviews.llvm.org/D128008

Files:
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/submodule-order.c

Index: clang/test/ClangScanDeps/submodule-order.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/submodule-order.c
@@ -0,0 +1,56 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -generate-modules-path-args > %t/deps1.json
+// RUN: mv %t/tu2.c %t/tu.c
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -generate-modules-path-args > %t/deps2.json
+// RUN: diff -u %t/deps1.json %t/deps2.json
+// RUN: FileCheck %s < %t/deps1.json
+
+// CHECK: "-fmodule-file={{.*}}Indirect1
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+// CHECK: "-fmodule-file={{.*}}Indirect2
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu.c"
+}]
+
+//--- module.modulemap
+module Indirect1 { header "Indirect1.h" }
+module Indirect2 { header "Indirect2.h" }
+module Mod {
+  umbrella "Mod"
+  module * { export * }
+}
+
+//--- Indirect1.h
+void indirect1(void);
+
+//--- Indirect2.h
+void indirect2(void);
+
+//--- Mod/SubMod1.h
+#include "../Indirect1.h"
+
+//--- Mod/SubMod2.h
+#include "../Indirect2.h"
+
+//--- tu.c
+#include "Mod/SubMod1.h"
+#include "Mod/SubMod2.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
+
+//--- tu2.c
+#include "Mod/SubMod2.h"
+#include "Mod/SubMod1.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
\ No newline at end of file
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -317,13 +317,28 @@
   return MD.ID;
 }
 
+static void forEachSubmoduleSorted(const Module *M,
+   llvm::function_ref F) {
+  // Submodule order depends on order of header includes for inferred submodules
+  // we don't care about the exact order, so sort so that it's consistent across
+  // TUs to improve sharing.
+  SmallVector Submodules(M->submodule_begin(),
+ M->submodule_end());
+  llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
+return A->Name < B->Name;
+  });
+  for (const Module *SubM : Submodules)
+F(SubM);
+}
+
 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
 const Module *M, ModuleDeps ,
 llvm::DenseSet ) {
   addModulePrebuiltDeps(M, MD, SeenSubmodules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
+  });
 }
 
 void ModuleDepCollectorPP::addModulePrebuiltDeps(
@@ -341,8 +356,9 @@
 llvm::DenseSet ) {
   addModuleDep(M, MD, AddedModules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmoduleDeps(SubM, MD, AddedModules);
+  });
 }
 
 void ModuleDepCollectorPP::addModuleDep(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4a3a9a5 - [clang][deps] Sort submodules when calculating dependencies

2022-06-17 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-06-17T07:55:27-07:00
New Revision: 4a3a9a5fa0b2fd0e70672c35010fe2f00740f098

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

LOG: [clang][deps] Sort submodules when calculating dependencies

Dependency scanning does not care about the order of submodules for
correctness, so sort the submodules so that we get the same
command-lines to build the module across different TUs. The order of
inferred submodules can vary depending on the order of #includes in the
including TU.

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

Added: 
clang/test/ClangScanDeps/submodule-order.c

Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 8fad65c14e376..f7d96130b9712 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -317,13 +317,28 @@ ModuleID ModuleDepCollectorPP::handleTopLevelModule(const 
Module *M) {
   return MD.ID;
 }
 
+static void forEachSubmoduleSorted(const Module *M,
+   llvm::function_ref F) 
{
+  // Submodule order depends on order of header includes for inferred 
submodules
+  // we don't care about the exact order, so sort so that it's consistent 
across
+  // TUs to improve sharing.
+  SmallVector Submodules(M->submodule_begin(),
+ M->submodule_end());
+  llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
+return A->Name < B->Name;
+  });
+  for (const Module *SubM : Submodules)
+F(SubM);
+}
+
 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
 const Module *M, ModuleDeps ,
 llvm::DenseSet ) {
   addModulePrebuiltDeps(M, MD, SeenSubmodules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
+  });
 }
 
 void ModuleDepCollectorPP::addModulePrebuiltDeps(
@@ -341,8 +356,9 @@ void ModuleDepCollectorPP::addAllSubmoduleDeps(
 llvm::DenseSet ) {
   addModuleDep(M, MD, AddedModules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmoduleDeps(SubM, MD, AddedModules);
+  });
 }
 
 void ModuleDepCollectorPP::addModuleDep(

diff  --git a/clang/test/ClangScanDeps/submodule-order.c 
b/clang/test/ClangScanDeps/submodule-order.c
new file mode 100644
index 0..9ab84c120356f
--- /dev/null
+++ b/clang/test/ClangScanDeps/submodule-order.c
@@ -0,0 +1,56 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -generate-modules-path-args > %t/deps1.json
+// RUN: mv %t/tu2.c %t/tu.c
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -generate-modules-path-args > %t/deps2.json
+// RUN: 
diff  -u %t/deps1.json %t/deps2.json
+// RUN: FileCheck %s < %t/deps1.json
+
+// CHECK: "-fmodule-file={{.*}}Indirect1
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+// CHECK: "-fmodule-file={{.*}}Indirect2
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu.c"
+}]
+
+//--- module.modulemap
+module Indirect1 { header "Indirect1.h" }
+module Indirect2 { header "Indirect2.h" }
+module Mod {
+  umbrella "Mod"
+  module * { export * }
+}
+
+//--- Indirect1.h
+void indirect1(void);
+
+//--- Indirect2.h
+void indirect2(void);
+
+//--- Mod/SubMod1.h
+#include "../Indirect1.h"
+
+//--- Mod/SubMod2.h
+#include "../Indirect2.h"
+
+//--- tu.c
+#include "Mod/SubMod1.h"
+#include "Mod/SubMod2.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
+
+//--- tu2.c
+#include "Mod/SubMod2.h"
+#include "Mod/SubMod1.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
\ No newline at end of file



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


[PATCH] D127690: [NFC] clang/Parser: remove dead code

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 437906.
mizvekov added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127690/new/

https://reviews.llvm.org/D127690

Files:
  clang/lib/Parse/Parser.cpp


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2056,36 +2056,6 @@
   return false;
 }
 
-// If this is a template-id, annotate with a template-id or type token.
-// FIXME: This appears to be dead code. We already have formed template-id
-// tokens when parsing the scope specifier; this can never form a new one.
-if (NextToken().is(tok::less)) {
-  TemplateTy Template;
-  UnqualifiedId TemplateName;
-  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
-  bool MemberOfUnknownSpecialization;
-  if (TemplateNameKind TNK = Actions.isTemplateName(
-  getCurScope(), SS,
-  /*hasTemplateKeyword=*/false, TemplateName,
-  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
-  MemberOfUnknownSpecialization)) {
-// Only annotate an undeclared template name as a template-id if the
-// following tokens have the form of a template argument list.
-if (TNK != TNK_Undeclared_template ||
-isTemplateArgumentList(1) != TPResult::False) {
-  // Consume the identifier.
-  ConsumeToken();
-  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
-  TemplateName)) {
-// If an unrecoverable error occurred, we need to return true here,
-// because the token stream is in a damaged state.  We may not
-// return a valid identifier.
-return true;
-  }
-}
-  }
-}
-
 // The current token, which is either an identifier or a
 // template-id, is not part of the annotation. Fall through to
 // push that token back into the stream and complete the C++ scope


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2056,36 +2056,6 @@
   return false;
 }
 
-// If this is a template-id, annotate with a template-id or type token.
-// FIXME: This appears to be dead code. We already have formed template-id
-// tokens when parsing the scope specifier; this can never form a new one.
-if (NextToken().is(tok::less)) {
-  TemplateTy Template;
-  UnqualifiedId TemplateName;
-  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
-  bool MemberOfUnknownSpecialization;
-  if (TemplateNameKind TNK = Actions.isTemplateName(
-  getCurScope(), SS,
-  /*hasTemplateKeyword=*/false, TemplateName,
-  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
-  MemberOfUnknownSpecialization)) {
-// Only annotate an undeclared template name as a template-id if the
-// following tokens have the form of a template argument list.
-if (TNK != TNK_Undeclared_template ||
-isTemplateArgumentList(1) != TPResult::False) {
-  // Consume the identifier.
-  ConsumeToken();
-  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
-  TemplateName)) {
-// If an unrecoverable error occurred, we need to return true here,
-// because the token stream is in a damaged state.  We may not
-// return a valid identifier.
-return true;
-  }
-}
-  }
-}
-
 // The current token, which is either an identifier or a
 // template-id, is not part of the annotation. Fall through to
 // push that token back into the stream and complete the C++ scope
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127351: clang: fix early substitution of alias templates

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 437905.
mizvekov added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127351/new/

https://reviews.llvm.org/D127351

Files:
  clang/include/clang/Sema/Template.h
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/ast-dump-template-decls.cpp

Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -121,7 +121,7 @@
 // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void'
 // CHECK-NEXT: FunctionProtoType 0x{{[^ ]*}} 'void (int)' cdecl
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'void' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent depth 0 index 0
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent depth 1 index 0
 // CHECK-NEXT: TemplateTypeParm 0x{{[^ ]*}} 'U'
 // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void'
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1029,8 +1029,9 @@
   // will contain the instantiations of the template parameters.
   LocalInstantiationScope Scope(SemaRef);
 
-  TemplateParameterList *TempParams = D->getTemplateParameters();
-  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
+  auto EarlySubstitutionScope = TemplateArgs.getEarlySubstitutionRAII();
+  TemplateParameterList *InstParams =
+  SubstTemplateParams(D->getTemplateParameters());
   if (!InstParams)
 return nullptr;
 
@@ -2757,7 +2758,7 @@
 
   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
   SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
-  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
+  TemplateArgs.getNewDepth(D->getDepth()), D->getIndex(),
   D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
   D->hasTypeConstraint(), NumExpanded);
 
@@ -2910,14 +2911,14 @@
   if (IsExpandedParameterPack)
 Param = NonTypeTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
 ExpandedParameterPackTypesAsWritten);
   else
 Param = NonTypeTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), T, D->isParameterPack(), DI);
 
   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
 if (AutoLoc.isConstrained())
@@ -3051,13 +3052,13 @@
   if (IsExpandedParameterPack)
 Param = TemplateTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), InstParams, ExpandedParams);
   else
 Param = TemplateTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->isParameterPack(), D->getIdentifier(), InstParams);
   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
 NestedNameSpecifierLoc QualifierLoc =
 D->getDefaultArgument().getTemplateQualifierLoc();
@@ -4021,6 +4022,7 @@
   if (Expr *E = L->getRequiresClause()) {
 EnterExpressionEvaluationContext ConstantEvaluated(
 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
+auto LateSubstitutionScope = TemplateArgs.getLateSubstitutionRAII();
 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
 if (Res.isInvalid() || !Res.isUsable()) {
   return nullptr;
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -959,8 +959,12 @@
   this->Entity = Entity;
 }
 
-unsigned TransformTemplateDepth(unsigned Depth) {
-  return 

[PATCH] D127579: [clang][WIP] add option to keep types of ptr args for non-kernel functions in metadata

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Btw do we have any issue tracking this failure, I am having a feeling that the 
translation of special types might be related to 
https://github.com/llvm/llvm-project/issues/55121? I am not aware at which 
point libclc is expected to be linked for SPIR-V but if linking happens at 
SPIR-V binary level it is likely going to face the other problem I described 
here.

Either way we should track this problem and we probably need a solution ideally 
within a month or so, as we can't release clang-15 with broken SPIR-V 
support... potentially one solution is to enable pointer types just for SPIR-V 
but this is probably the least option we should consider.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127579/new/

https://reviews.llvm.org/D127579

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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

In D128012#3592098 , @Anastasia wrote:

> aha, are you having a lot of these types then? Ok that sounds similar problem 
> to OpenCL builtin functions as we had to go away from a simple header include 
> due to long parsing time.

Very similar problem. We have a two-part problem where we both have enough of 
them that parsing a header would be too slow _and_ the HLSL language actually 
can't represent them. The later we're working to fix. My hope is that 
eventually we can write the HLSL libraries in HLSL and use a pre-compilation 
step (PCH or Module-style) to get past the performance issues.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128012/new/

https://reviews.llvm.org/D128012

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


[clang] 1a02c96 - Revert "Revert "[clang] Dont print implicit forrange initializer""

2022-06-17 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-06-17T16:51:16+02:00
New Revision: 1a02c963e338100a3000734b91f5956da9b8c95e

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

LOG: Revert "Revert "[clang] Dont print implicit forrange initializer""

This reverts commit 7aac15d5df6cfa03b802e055b63227a95fa1734e.

Only updates the tests, as these statements are still part of the CFG
and its just the pretty printer policy that changes. Hopefully this
shouldn't affect any analysis.

Added: 


Modified: 
clang/lib/AST/DeclPrinter.cpp
clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
clang/test/Analysis/scopes-cfg-output.cpp
clang/unittests/AST/DeclPrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index faafe307f03cf..c6a392c9c01b5 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -895,12 +895,15 @@ void DeclPrinter::VisitVarDecl(VarDecl *D) {
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (CXXConstructExpr *Construct =
-dyn_cast(Init->IgnoreImplicit())) {
+if (D->isCXXForRangeDecl()) {
+  // FIXME: We should print the range expression instead.
+  ImplicitInit = true;
+} else if (CXXConstructExpr *Construct =
+   dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-  Construct->getArg(0)->isDefaultArgument();
+   Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {

diff  --git a/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp 
b/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
index 82c86a95792a9..e5397f5678cb5 100644
--- a/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
+++ b/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
@@ -1098,7 +1098,7 @@ void test_for_implicit_scope() {
 // CHECK-NEXT:   2: [B3.1] (ImplicitCastExpr, LValueToRValue, int *)
 // CHECK-NEXT:   3: *[B3.2]
 // CHECK-NEXT:   4: [B3.3] (ImplicitCastExpr, LValueToRValue, int)
-// CHECK-NEXT:   5: int n = *__begin1;
+// CHECK-NEXT:   5: int n
 // WARNINGS-NEXT:   6:  (CXXConstructExpr, class A)
 // ANALYZER-NEXT:   6:  (CXXConstructExpr, [B3.7], class A)
 // CHECK-NEXT:   7: A c;

diff  --git a/clang/test/Analysis/scopes-cfg-output.cpp 
b/clang/test/Analysis/scopes-cfg-output.cpp
index c8212d51f6b24..ef2cac9538163 100644
--- a/clang/test/Analysis/scopes-cfg-output.cpp
+++ b/clang/test/Analysis/scopes-cfg-output.cpp
@@ -834,7 +834,7 @@ void test_for_compound_and_break() {
 // CHECK-NEXT:   2: __begin1
 // CHECK-NEXT:   3: [B4.2] (ImplicitCastExpr, LValueToRValue, class A *)
 // CHECK-NEXT:   4: *[B4.3]
-// CHECK-NEXT:   5: auto  = *__begin1;
+// CHECK-NEXT:   5: auto 
 // CHECK-NEXT:   6: operator=
 // CHECK-NEXT:   7: [B4.6] (ImplicitCastExpr, FunctionToPointerDecay, class A 
&(*)(const class A &)
 // CHECK-NEXT:   8: i

diff  --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index c2d7d78738f96..11dca6ed68167 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,4 +1426,7 @@ TEST(DeclPrinter, VarDeclWithInitializer) {
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy ) { Policy.ConstantsAsWritten = true; }));
+  ASSERT_TRUE(
+  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
+  namedDecl(hasName("a")).bind("id"), "int a"));
 }



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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D128012#3591828 , @beanz wrote:

> For just the type alias, adding it during parsing would probably work. Where 
> things get more complicated is we have a whole mess of other data types that 
> we’ll need to add too eventually. One of the advantages of using an external 
> sema source is that we can create incomplete records during initialization, 
> and complete them when the sema source gets the callback from lookup. That 
> gives us cheap and efficient lazy-initialization of our buffer types which 
> (in DXC) has a huge impact on compile time.

aha, are you having a lot of these types then? Ok that sounds similar problem 
to OpenCL builtin functions as we had to go away from a simple header include 
due to long parsing time.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128012/new/

https://reviews.llvm.org/D128012

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


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp:3577-3580
+ASSERT_THAT(Results, ElementsAre(Pair("if_branch_1", _),
+ Pair("if_branch_0", _)));
+const Environment  = Results[1].second.Env;
+const Environment  = Results[0].second.Env;




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128060/new/

https://reviews.llvm.org/D128060

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


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, xazax.hun, gribozavr2.
Herald added subscribers: martong, tschuett, rnkovacs.
Herald added a project: All.
sgatev requested review of this revision.
Herald added a project: clang.

Extend flow condition in the body of a for loop.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128060

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,87 @@
   });
 }
 
+TEST_F(TransferTest, BranchesExtendFlowCondition) {
+  std::string IfBranchCode = R"(
+void target(bool Foo) {
+  if (Foo) {
+(void)0;
+// [[if_branch_0]]
+  } else {
+(void)0;
+// [[if_branch_1]]
+  }
+}
+  )";
+  runDataflow(IfBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("if_branch_1", _),
+ Pair("if_branch_0", _)));
+const Environment  = Results[1].second.Env;
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(Env0.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env0.flowConditionImplies(FooVal0));
+
+BoolValue  =
+*cast(Env1.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env1.flowConditionImplies(Env1.makeNot(FooVal1)));
+  });
+
+  std::string WhileBranchCode = R"(
+void target(bool Foo) {
+  while (Foo) {
+(void)0;
+// [[while_branch]]
+  }
+}
+  )";
+  runDataflow(WhileBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("while_branch", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+
+  std::string ForBranchCode = R"(
+void target(bool Foo) {
+  for (; Foo;) {
+(void)0;
+// [[for_branch]]
+  }
+}
+  )";
+  runDataflow(ForBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("for_branch", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue  =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -89,6 +89,12 @@
 extendFlowCondition(*Cond);
   }
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();
+assert(Cond != nullptr);
+extendFlowCondition(*Cond);
+  }
+
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
 auto *LHS = S->getLHS();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128059: [Clang] Add a warning on invalid UTF-8 in comments.

2022-06-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Introduce an off-by default `-Winvalid-utf8` warning
that detects invalid UTF-8 code units sequences in comments.

Invalid UTF-8 in other places is already diagnosed,
as that cannot appear in identifiers and other grammar constructs.

The warning is off by default as its likely to be somewhat disruptive
otherwise.

This warning allows clang to conform to the yet-to be approved WG21
"P2295R5 Support for UTF-8 as a portable source file encoding"
paper.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128059

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/Lexer.cpp
  clang/test/Lexer/comment-invalid-utf8.c
  llvm/include/llvm/Support/ConvertUTF.h
  llvm/lib/Support/ConvertUTF.cpp

Index: llvm/lib/Support/ConvertUTF.cpp
===
--- llvm/lib/Support/ConvertUTF.cpp
+++ llvm/lib/Support/ConvertUTF.cpp
@@ -417,6 +417,18 @@
 return isLegalUTF8(source, length);
 }
 
+/*
+ * Exported function to return the size of the first utf-8 code unit sequence,
+ * Or 0 if the sequence is not valid;
+ */
+unsigned getUTF8SequenceSize(const UTF8 *source, const UTF8 *sourceEnd) {
+  int length = trailingBytesForUTF8[*source] + 1;
+  if (length > sourceEnd - source) {
+return 0;
+  }
+  return isLegalUTF8(source, length) ? length : 0;
+}
+
 /* - */
 
 static unsigned
Index: llvm/include/llvm/Support/ConvertUTF.h
===
--- llvm/include/llvm/Support/ConvertUTF.h
+++ llvm/include/llvm/Support/ConvertUTF.h
@@ -181,6 +181,8 @@
 
 Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd);
 
+unsigned getUTF8SequenceSize(const UTF8 *source, const UTF8 *sourceEnd);
+
 unsigned getNumBytesForUTF8(UTF8 firstByte);
 
 /*/
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -2391,13 +2391,40 @@
   //
   // This loop terminates with CurPtr pointing at the newline (or end of buffer)
   // character that ends the line comment.
+
+  bool WarnOnInvalidUtf8 =
+  !isLexingRawMode() &&
+  !PP->getDiagnostics().isIgnored(diag::warn_invalid_utf8_in_comment,
+  getSourceLocation(CurPtr));
+  bool UnicodeDecodeFailed = false;
+
   char C;
   while (true) {
 C = *CurPtr;
 // Skip over characters in the fast loop.
-while (C != 0 &&// Potentially EOF.
-   C != '\n' && C != '\r')  // Newline or DOS-style newline.
+// Warn on invalid UTF-8 if the corresponding warning is enabled, emitting a
+// diagnostic only once per sequence that cannot be decoded.
+while ((!WarnOnInvalidUtf8 || isASCII(C)) && C != 0 && // Potentially EOF.
+   C != '\n' && C != '\r') { // Newline or DOS-style newline.
   C = *++CurPtr;
+  UnicodeDecodeFailed = false;
+}
+
+if (WarnOnInvalidUtf8 && !isASCII(C)) {
+  unsigned Length = llvm::getUTF8SequenceSize(
+  (const llvm::UTF8 *)CurPtr, (const llvm::UTF8 *)BufferEnd);
+  if (Length == 0) {
+if (!UnicodeDecodeFailed) {
+  Diag(CurPtr, diag::warn_invalid_utf8_in_comment);
+}
+UnicodeDecodeFailed = true;
+++CurPtr;
+  } else {
+UnicodeDecodeFailed = false;
+CurPtr += Length;
+  }
+  continue;
+}
 
 const char *NextLine = CurPtr;
 if (C != 0) {
@@ -2664,10 +2691,18 @@
   if (C == '/')
 C = *CurPtr++;
 
+  bool WarnOnInvalidUtf8 =
+  !isLexingRawMode() &&
+  !PP->getDiagnostics().isIgnored(diag::warn_invalid_utf8_in_comment,
+  getSourceLocation(CurPtr));
+  bool UnicodeDecodeFailed = false;
+
   while (true) {
 // Skip over all non-interesting characters until we find end of buffer or a
 // (probably ending) '/' character.
-if (CurPtr + 24 < BufferEnd &&
+// When diagnosing invalid UTF-8 sequences we always skip the fast
+// vectorized path.
+if (!WarnOnInvalidUtf8 && CurPtr + 24 < BufferEnd &&
 // If there is a code-completion point avoid the fast scan because it
 // doesn't check for '\0'.
 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
@@ -2714,9 +2749,28 @@
   C = *CurPtr++;
 }
 
-// Loop to scan the remainder.
-while (C != '/' && C != '\0')
-  C = *CurPtr++;
+// Loop to scan the remainder, warning on invalid UTF-8
+// if the corresponding warning is enabled, emitting a diagnostic only once
+// per sequence that 

[PATCH] D127544: Add no_sanitize('hwaddress') (and 'memtag', but that's a no-op).

2022-06-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM! The debian failures look like precommit CI is in a broken state again, 
but have nothing to do with your patch.




Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8849
 break;
-  
   // HLSL attributes:

hctim wrote:
> aaron.ballman wrote:
> > hctim wrote:
> > > aaron.ballman wrote:
> > > > Spurious whitespace change?
> > > unfortunately there's no way in my editor to trim trailing whitespace 
> > > only on changed lines :(, so i end up fixing things like this drive-by.
> > > 
> > > let me know if you feel very strongly about this diff and I can kill it, 
> > > but I personally think the drive-by-fix isn't a huge problem and the 
> > > alternative of whitespace-fix-only commit seems a bit overkill
> > Personally, I don't feel very strongly because the chances of the 
> > whitespace being someone's entrypoint to git-blame is pretty minimal 
> > (especially given there's only one change here). However, we typically 
> > still ask for formatting changes to be separated out 
> > (https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access #2) 
> > rather than lumped in with functional changes so reviewers will ask for 
> > these sort of changes to be backed out, so this may crop up repeatedly if 
> > your editor doesn't give you the options you need.
> Fixed in ee28837a1fbd574dbec14b9f09cb4effab6a492a.
Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127544/new/

https://reviews.llvm.org/D127544

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


[PATCH] D128056: [clang][dataflow] Singleton pointer values for null pointers.

2022-06-17 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, tschuett, xazax.hun.
Herald added a project: All.
wyt requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When a `nullptr` is assigned to a pointer variable, it is wrapped in a 
`ImplicitCastExpr` with cast kind `CK_NullTo(Member)Pointer`. This patch 
assigns singleton pointer values representing null to these expressions.

For each pointee type, a singleton null `PointerValue` is created and stored in 
the `NullPointerVals` map of the `DataflowAnalysisContext` class. The pointee 
type is retrieved from the implicit cast expression, and used to initialise the 
`PointeeLoc` field of the `PointerValue`. The `PointeeLoc` created is not 
mapped to any `Value`, reflecting the absence of value indicated by null 
pointers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128056

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2214,6 +2214,93 @@
   });
 }
 
+TEST_F(TransferTest, NullToPointerCast) {
+  std::string Code = R"(
+struct Baz {};
+void target() {
+  int *FooX = nullptr;
+  int *FooY = nullptr;
+  bool **Bar = nullptr;
+  Baz *Baz = nullptr;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *FooXDecl = findValueDecl(ASTCtx, "FooX");
+ASSERT_THAT(FooXDecl, NotNull());
+
+const ValueDecl *FooYDecl = findValueDecl(ASTCtx, "FooY");
+ASSERT_THAT(FooYDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const auto *FooXVal =
+cast(Env.getValue(*FooXDecl, SkipPast::None));
+const auto *FooYVal =
+cast(Env.getValue(*FooYDecl, SkipPast::None));
+const auto *BarVal =
+cast(Env.getValue(*BarDecl, SkipPast::None));
+const auto *BazVal =
+cast(Env.getValue(*BazDecl, SkipPast::None));
+
+EXPECT_EQ(FooXVal, FooYVal);
+EXPECT_NE(FooXVal, BarVal);
+EXPECT_NE(FooXVal, BazVal);
+EXPECT_NE(BarVal, BazVal);
+
+const StorageLocation  = FooXVal->getPointeeLoc();
+EXPECT_TRUE(isa(FooPointeeLoc));
+EXPECT_THAT(Env.getValue(FooPointeeLoc), IsNull());
+
+const StorageLocation  = BarVal->getPointeeLoc();
+EXPECT_TRUE(isa(BarPointeeLoc));
+EXPECT_THAT(Env.getValue(BarPointeeLoc), IsNull());
+
+const StorageLocation  = BazVal->getPointeeLoc();
+EXPECT_TRUE(isa(BazPointeeLoc));
+EXPECT_THAT(Env.getValue(BazPointeeLoc), IsNull());
+  });
+}
+
+TEST_F(TransferTest, NullToMemberPointerCast) {
+  std::string Code = R"(
+struct Foo {};
+void target(Foo *Foo) {
+  int Foo::*MemberPointer = nullptr;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment  = Results[0].second.Env;
+
+const ValueDecl *MemberPointerDecl =
+findValueDecl(ASTCtx, "MemberPointer");
+ASSERT_THAT(MemberPointerDecl, NotNull());
+
+const auto *MemberPointerVal = cast(
+Env.getValue(*MemberPointerDecl, SkipPast::None));
+
+const StorageLocation  = MemberPointerVal->getPointeeLoc();
+EXPECT_THAT(Env.getValue(MemberLoc), IsNull());
+  });
+}
+
 TEST_F(TransferTest, AddrOfValue) {
   std::string Code = R"(
 void target() {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -246,6 +246,16 @@
   Env.setStorageLocation(*S, *SubExprLoc);
   

[PATCH] D128049: [mlir] move SCF headers to SCF/{IR,Transforms} respectively

2022-06-17 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse marked an inline comment as done.
ftynse added inline comments.



Comment at: mlir/include/mlir/Dialect/SCF/Transforms/Transforms.h:13
 
-#ifndef MLIR_DIALECT_SCF_TRANSFORMS_H_
-#define MLIR_DIALECT_SCF_TRANSFORMS_H_
+#ifndef MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
+#define MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_

jpienaar wrote:
> Transforms transforms feels a bit strange, for many others I believe this 
> would have been passes file (which is also not that accurate, patterns and 
> passes would be more, but most others it is just passes and convenient 
> shorthand). Keeping the move mostly mechanical is good though 
There's already Transforms/Passes.h and Transforms/Patterns.h, these things are 
more like standalone transform functions. Maybe Transforms/Utils.h?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128049/new/

https://reviews.llvm.org/D128049

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


[PATCH] D128049: [mlir] move SCF headers to SCF/{IR,Transforms} respectively

2022-06-17 Thread Jacques Pienaar via Phabricator via cfe-commits
jpienaar accepted this revision.
jpienaar added a comment.
This revision is now accepted and ready to land.

More consistency is good and update for downstream users mechanical, so LGTM




Comment at: mlir/include/mlir/Dialect/SCF/Transforms/Transforms.h:13
 
-#ifndef MLIR_DIALECT_SCF_TRANSFORMS_H_
-#define MLIR_DIALECT_SCF_TRANSFORMS_H_
+#ifndef MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
+#define MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_

Transforms transforms feels a bit strange, for many others I believe this would 
have been passes file (which is also not that accurate, patterns and passes 
would be more, but most others it is just passes and convenient shorthand). 
Keeping the move mostly mechanical is good though 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128049/new/

https://reviews.llvm.org/D128049

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


  1   2   >