[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429152.
martong marked an inline comment as done.
martong added a comment.

- Add type parameter to evalMinus and evalComplement
- Correct dumpToStream in case of binary sub expressions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/explain-svals.cpp
  clang/test/Analysis/expr-inspection.cpp
  clang/test/Analysis/unary-sym-expr.c

Index: clang/test/Analysis/unary-sym-expr.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr.c
@@ -0,0 +1,36 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+int test(int x, int y) {
+
+  clang_analyzer_dump(-x);   // expected-warning{{-reg_$0}}
+  clang_analyzer_dump(~x);   // expected-warning{{~reg_$0}}
+  int z = x + y;
+  clang_analyzer_dump(-z);   // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-(x + y)); // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-x + y);   // expected-warning{{(-reg_$0) + (reg_$1)}}
+
+  if (-x == 0) {
+clang_analyzer_eval(-x == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(-x > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(-x < 0);  // expected-warning{{FALSE}}
+  }
+  if (~y == 0) {
+clang_analyzer_eval(~y == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(~y > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(~y < 0);  // expected-warning{{FALSE}}
+  }
+  (void)(x);
+  return 42;
+}
+
+void test_svalbuilder_simplification(int x, int y) {
+  if (x + y != 3)
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}
Index: clang/test/Analysis/expr-inspection.cpp
===
--- clang/test/Analysis/expr-inspection.cpp
+++ clang/test/Analysis/expr-inspection.cpp
@@ -18,6 +18,8 @@
   clang_analyzer_express(x); // expected-warning{{Unable to express}}
 
   clang_analyzer_denote(x, "$x");
+  clang_analyzer_express(-x); // expected-warning{{-$x}}
+
   clang_analyzer_denote(y, "$y");
   clang_analyzer_express(x + y); // expected-warning{{$x + $y}}
 
Index: clang/test/Analysis/explain-svals.cpp
===
--- clang/test/Analysis/explain-svals.cpp
+++ clang/test/Analysis/explain-svals.cpp
@@ -72,6 +72,7 @@
 void test_4(int x, int y) {
   int z;
   static int stat;
+  clang_analyzer_explain(-x);// expected-warning-re^\- \(argument 'x'\)$
   clang_analyzer_explain(x + 1); // expected-warning-re^\(argument 'x'\) \+ 1$
   clang_analyzer_explain(1 + y); // expected-warning-re^\(argument 'y'\) \+ 1$
   clang_analyzer_explain(x + y); // expected-warning-re^\(argument 'x'\) \+ \(argument 'y'\)$
Index: clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -70,6 +70,16 @@
   os << ')';
 }
 
+void UnarySymExpr::dumpToStream(raw_ostream &os) const {
+  os << UnaryOperator::getOpcodeStr(Op);
+  bool Binary = isa(Operand);
+  if (Binary)
+os << '(';
+  Operand->dumpToStream(os);
+  if (Binary)
+os << ')';
+}
+
 void SymbolConjured::dumpToStream(raw_ostream &os) const {
   os << getKindStr() << getSymbolID() << '{' << T << ", LC" << LCtx->getID();
   if (S)
@@ -134,6 +144,9 @@
 case SymExpr::SymbolCastKind:
   itr.push_back(cast(SE)->getOperand());
   return;
+case SymExpr::UnarySymExprKind:
+  itr.push_back(cast(SE)->getOperand());
+  return;
 case SymExpr::SymIntExprKind:
   itr.push_back(cast(SE)->getLHS());
   return;
@@ -306,6 +319,22 @@
   return cast(data);
 }
 
+const UnarySymExpr *SymbolManager::getUnarySymExpr(const SymExpr *Operand,
+   UnaryOperator::Opcode Opc,
+   QualType T) {
+  llvm::FoldingSetNodeID ID;
+  UnarySymExpr::Prof

[PATCH] D125162: [clang-format] fix alignment w/o binpacked args

2022-05-13 Thread cha5on via Phabricator via cfe-commits
cha5on added a comment.

In D125162#3510737 , @curdeius wrote:

> LGTM. Tell us if you need help landing this.

I don't have commit access, so some help would be great :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125162

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


[PATCH] D123685: [clang][ASTImporter] Add isNewDecl

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 4 inline comments as done.
martong added inline comments.



Comment at: clang/include/clang/AST/ASTImporterSharedState.h:83
+
+  void setNewDecl(Decl *ToD) { NewDecls.insert(ToD); }
 };

`markAsNewDecl` sounds better, I'll update before commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123685

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


[clang] 094fb13 - [analyzer] Add taint to the BoolAssignmentChecker

2022-05-13 Thread Endre Fülöp via cfe-commits

Author: Endre Fülöp
Date: 2022-05-13T09:27:28+02:00
New Revision: 094fb13b88b36ecfa475cb877d2c6e9d90b4d1a5

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

LOG: [analyzer] Add taint to the BoolAssignmentChecker

BoolAssignment checker is now taint-aware and warns if a tainted value is
assigned.

Original author: steakhal

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
clang/test/Analysis/bool-assignment.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
index 6c0caf3c4e78..dad25d6f853b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
@@ -12,6 +12,7 @@
 
//===--===//
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Checkers/Taint.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
@@ -23,20 +24,23 @@ using namespace ento;
 namespace {
   class BoolAssignmentChecker : public Checker< check::Bind > {
 mutable std::unique_ptr BT;
-void emitReport(ProgramStateRef state, CheckerContext &C) const;
+void emitReport(ProgramStateRef state, CheckerContext &C,
+bool IsTainted = false) const;
+
   public:
 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
   };
 } // end anonymous namespace
 
-void BoolAssignmentChecker::emitReport(ProgramStateRef state,
-   CheckerContext &C) const {
+void BoolAssignmentChecker::emitReport(ProgramStateRef state, CheckerContext 
&C,
+   bool IsTainted) const {
   if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
 if (!BT)
   BT.reset(new BuiltinBug(this, "Assignment of a non-Boolean value"));
 
-C.emitReport(
-std::make_unique(*BT, BT->getDescription(), 
N));
+StringRef Msg = IsTainted ? "Might assign a tainted non-Boolean value"
+  : "Assignment of a non-Boolean value";
+C.emitReport(std::make_unique(*BT, Msg, N));
   }
 }
 
@@ -90,6 +94,8 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, 
const Stmt *S,
 
   if (!StIn)
 emitReport(StOut, C);
+  if (StIn && StOut && taint::isTainted(state, *NV))
+emitReport(StOut, C, /*IsTainted=*/true);
 }
 
 void ento::registerBoolAssignmentChecker(CheckerManager &mgr) {

diff  --git a/clang/test/Analysis/bool-assignment.c 
b/clang/test/Analysis/bool-assignment.c
index 57a7f0b5dc1b..812710786d94 100644
--- a/clang/test/Analysis/bool-assignment.c
+++ b/clang/test/Analysis/bool-assignment.c
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment 
-analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment 
-analyzer-store=region -verify -x c++ %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint 
-analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint 
-analyzer-store=region -verify -x c++ %s
 
 // Test C++'s bool and C's _Bool.
 // FIXME: We stopped warning on these when SValBuilder got smarter about
@@ -104,3 +104,10 @@ void test_Boolean_assignment(int y) {
   }
   x = y; // no-warning
 }
+
+int scanf(const char *format, ...);
+void test_tainted_Boolean() {
+  int n;
+  scanf("%d", &n);
+  Boolean copy = n; // expected-warning {{Might assign a tainted non-Boolean 
value}}
+}



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


[PATCH] D125360: [analyzer] Add taint to the BoolAssignmentChecker

2022-05-13 Thread Endre Fülöp via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG094fb13b88b3: [analyzer] Add taint to the 
BoolAssignmentChecker (authored by gamesh411).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125360

Files:
  clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
  clang/test/Analysis/bool-assignment.c


Index: clang/test/Analysis/bool-assignment.c
===
--- clang/test/Analysis/bool-assignment.c
+++ clang/test/Analysis/bool-assignment.c
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment 
-analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment 
-analyzer-store=region -verify -x c++ %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint 
-analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint 
-analyzer-store=region -verify -x c++ %s
 
 // Test C++'s bool and C's _Bool.
 // FIXME: We stopped warning on these when SValBuilder got smarter about
@@ -104,3 +104,10 @@
   }
   x = y; // no-warning
 }
+
+int scanf(const char *format, ...);
+void test_tainted_Boolean() {
+  int n;
+  scanf("%d", &n);
+  Boolean copy = n; // expected-warning {{Might assign a tainted non-Boolean 
value}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
@@ -12,6 +12,7 @@
 
//===--===//
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Checkers/Taint.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
@@ -23,20 +24,23 @@
 namespace {
   class BoolAssignmentChecker : public Checker< check::Bind > {
 mutable std::unique_ptr BT;
-void emitReport(ProgramStateRef state, CheckerContext &C) const;
+void emitReport(ProgramStateRef state, CheckerContext &C,
+bool IsTainted = false) const;
+
   public:
 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
   };
 } // end anonymous namespace
 
-void BoolAssignmentChecker::emitReport(ProgramStateRef state,
-   CheckerContext &C) const {
+void BoolAssignmentChecker::emitReport(ProgramStateRef state, CheckerContext 
&C,
+   bool IsTainted) const {
   if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
 if (!BT)
   BT.reset(new BuiltinBug(this, "Assignment of a non-Boolean value"));
 
-C.emitReport(
-std::make_unique(*BT, BT->getDescription(), 
N));
+StringRef Msg = IsTainted ? "Might assign a tainted non-Boolean value"
+  : "Assignment of a non-Boolean value";
+C.emitReport(std::make_unique(*BT, Msg, N));
   }
 }
 
@@ -90,6 +94,8 @@
 
   if (!StIn)
 emitReport(StOut, C);
+  if (StIn && StOut && taint::isTainted(state, *NV))
+emitReport(StOut, C, /*IsTainted=*/true);
 }
 
 void ento::registerBoolAssignmentChecker(CheckerManager &mgr) {


Index: clang/test/Analysis/bool-assignment.c
===
--- clang/test/Analysis/bool-assignment.c
+++ clang/test/Analysis/bool-assignment.c
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment -analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment -analyzer-store=region -verify -x c++ %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint -analyzer-store=region -verify -std=c99 -Dbool=_Bool %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.BoolAssignment,alpha.security.taint -analyzer-store=region -verify -x c++ %s
 
 // Test C++'s bool and C's _Bool.
 // FIXME: We stopped warning on these when SValBuilder got smarter about
@@ -104,3 +104,10 @@
   }
   x = y; // no-warning
 }
+
+int scanf(const char *format, ...);
+void test_tainted_Boolean() {
+  int n;
+  scanf("%d", &n);
+  Boolean copy = n; // expected-warning {{Might assign a tainted non-Boolean value}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
@@ -12,6 +12,7 @@
 //===--

[PATCH] D124038: [clang] Prevent folding of non-const compound expr

2022-05-13 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 429156.
serge-sans-paille added a comment.

Update messed up format


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

https://reviews.llvm.org/D124038

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaTemplate/constexpr-instantiate.cpp


Index: clang/test/SemaTemplate/constexpr-instantiate.cpp
===
--- clang/test/SemaTemplate/constexpr-instantiate.cpp
+++ clang/test/SemaTemplate/constexpr-instantiate.cpp
@@ -219,7 +219,9 @@
   static int n;
 };
 template struct B {};
-template constexpr int A::k = *(int[N]){N}; // expected-error 
1+{{negative}}
+template  constexpr int A::k = *(int[N]){N}; // expected-error 
1+{{negative}} expected-note 1+{{not valid in a constant expression}} 
expected-note 1+{{declared here}}
+// expected-error@-1 1+{{must be initialized by a constant expression}}
+
 template int A::n = *(int[N]){0};
 
 template  void f() {
@@ -230,9 +232,9 @@
 };
 
 decltype(A<-3>::k) d1 = 0; // ok
-decltype(char{A<-4>::k}) d2 = 0; // expected-note {{instantiation of }} 
expected-error {{narrow}} expected-note {{cast}}
-decltype(char{A<1>::k}) d3 = 0; // ok
-decltype(char{A<1 + (unsigned char)-1>::k}) d4 = 0; // expected-error 
{{narrow}} expected-note {{cast}}
+decltype(char{A<-4>::k}) d2 = 0;// expected-note 
1+{{instantiation of }} expected-error {{narrow}} expected-note {{cast}}
+decltype(char{A<1>::k}) d3 = 0; // expected-note 
1+{{instantiation of }} expected-error {{narrow}} expected-note {{cast}}
+decltype(char{A<1 + (unsigned char)-1>::k}) d4 = 0; // expected-error 
{{narrow}} expected-note {{cast}}  expected-note {{instantiation of}}
   }
 }
 
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1596,8 +1596,13 @@
   // Matching GCC, file-scope array compound literals initialized by constants
   // are lifetime-extended.
   constexpr int *p = (int*)(int[1]){3}; // expected-warning {{C99}}
-  static_assert(*p == 3, "");
+  static_assert(*p == 3, "");   // expected-error {{static_assert 
expression is not an integral constant expression}}
+// expected-note@-1 {{subexpression 
not valid}}
+// expected-note@-3 {{declared here}}
   static_assert((int[2]){1, 2}[1] == 2, ""); // expected-warning {{C99}}
+  // expected-error@-1 {{static_assert expression is not an integral constant 
expression}}
+  // expected-note@-2 {{subexpression not valid}}
+  // expected-note@-3 {{declared here}}
 
   // Other kinds are not.
   struct X { int a[2]; };
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -4259,9 +4259,33 @@
 Info.FFDiag(Conv);
 return false;
   }
+
   APValue Lit;
   if (!Evaluate(Lit, Info, CLE->getInitializer()))
 return false;
+
+  // According to GCC info page:
+  //
+  // 6.28 Compound Literals
+  //
+  // As an optimization, G++ sometimes gives array compound literals longer
+  // lifetimes: when the array either appears outside a function or has a
+  // const-qualified type. If foo and its initializer had elements of type
+  // char *const rather than char *, or if foo were a global variable, the
+  // array would have static storage duration. But it is probably safest
+  // just to avoid the use of array compound literals in C++ code.
+  //
+  // Obey that rule by checking constness for converted array types.
+
+  QualType CLETy = CLE->getType();
+  if (CLETy->isArrayType() && !Type->isArrayType()) {
+if (!CLETy.isConstant(Info.Ctx)) {
+  Info.FFDiag(Conv);
+  Info.Note(CLE->getExprLoc(), diag::note_declared_at);
+  return false;
+}
+  }
+
   CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
   return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
 } else if (isa(Base) || isa(Base)) {


Index: clang/test/SemaTemplate/constexpr-instantiate.cpp
===
--- clang/test/SemaTemplate/constexpr-instantiate.cpp
+++ clang/test/SemaTemplate/constexpr-instantiate.cpp
@@ -219,7 +219,9 @@
   static int n;
 };
 template struct B {};
-template constexpr int A::k = *(int[N]){N}; // expected-error 1+{{negative}}
+template  constexpr int A::k = *(int[N]){N}; // expected-error 1+{{negative}} expected-note 1+{{not valid in a constant expression}} expected-note 1+{{declared here}}
+

[PATCH] D122734: [CUDA][HIP] Fix mangling number for local struct

2022-05-13 Thread Mikael Holmén via Phabricator via cfe-commits
uabelho added a comment.

In D122734#3509187 , @yaxunl wrote:

> In D122734#3509096 , @yaxunl wrote:
>
>> In D122734#3508294 , @uabelho 
>> wrote:
>>
>>> Hi,
>>>
>>> I noticed when compiling with gcc 9.3.0 that we get a bunch of new warnings 
>>> with this patch:
>>>
>>>   [1/351] Building CXX object 
>>> tools/clang/lib/AST/CMakeFiles/obj.clangAST.dir/MicrosoftCXXABI.cpp.o
>>>   ../../clang/lib/AST/MicrosoftCXXABI.cpp:57:12: warning: 'virtual unsigned 
>>> int {anonymous}::MicrosoftNumberingContext::getManglingNumber(const 
>>> clang::VarDecl*, unsigned int)' was hidden [-Woverloaded-virtual]
>>>  57 |   unsigned getManglingNumber(const VarDecl *VD,
>>> |^
>>>   ../../clang/lib/AST/MicrosoftCXXABI.cpp:80:12: warning:   by 'virtual 
>>> unsigned int {anonymous}::MSHIPNumberingContext::getManglingNumber(const 
>>> clang::TagDecl*, unsigned int)' [-Woverloaded-virtual]
>>>  80 |   unsigned getManglingNumber(const TagDecl *TD,
>>> |^
>
> fixed by 0f292141aadb0489231de31de966c239486e019d 
> 

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122734

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


[PATCH] D125524: [BoundV2] ArrayBoundV2 checks if the extent is tainted

2022-05-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added a reviewer: steakhal.
Herald added subscribers: martong, Szelethus, dkrupp.
Herald added a reviewer: Szelethus.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Use upperbound instead of offset to check if the extent of memory region
being accessed is tainted or not.

Original author: steakhal


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125524

Files:
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/test/Analysis/taint-diagnostic-visitor.c


Index: clang/test/Analysis/taint-diagnostic-visitor.c
===
--- clang/test/Analysis/taint-diagnostic-visitor.c
+++ clang/test/Analysis/taint-diagnostic-visitor.c
@@ -1,9 +1,12 @@
-// RUN: %clang_cc1 -analyze 
-analyzer-checker=alpha.security.taint,core,alpha.security.ArrayBoundV2 
-analyzer-output=text -verify %s
+// RUN: %clang_cc1 -analyze 
-analyzer-checker=alpha.security.taint,core,unix.Malloc,alpha.security.ArrayBoundV2
 -analyzer-output=text -verify %s
 
 // This file is for testing enhanced diagnostics produced by the 
GenericTaintChecker
 
 int scanf(const char *restrict format, ...);
 int system(const char *command);
+typedef __typeof(sizeof(int)) size_t;
+void *malloc(size_t size);
+void free(void *ptr);
 
 void taintDiagnostic(void)
 {
@@ -34,3 +37,18 @@
   int vla[x]; // expected-warning {{Declared variable-length array (VLA) has 
tainted size}}
   // expected-note@-1 {{Declared variable-length array (VLA) has 
tainted size}}
 }
+
+void taintDiagnosticMalloc(int conj) {
+  int x;
+  scanf("%d", &x);
+  // expected-note@-1 2 {{Taint originated here}} Once for malloc(tainted), 
once for BoundsV2.
+
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted 
allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}
+
+  p[1] = 1; // BoundsV2 checker can not prove that the access is safe.
+  // expected-warning@-1 {{Out of bound memory access (index is tainted)}}
+  // expected-note@-2{{Out of bound memory access (index is tainted)}}
+  free(p);
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -205,10 +205,9 @@
 
 // If we are under constrained and the index variables are tainted, report.
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = rawOffset.getByteOffset();
-  if (isTainted(state, ByteOffset)) {
+  if (isTainted(state, *upperboundToCheck)) {
 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,
-  std::make_unique(ByteOffset));
+  std::make_unique(*upperboundToCheck));
 return;
   }
 } else if (state_exceedsUpperBound) {


Index: clang/test/Analysis/taint-diagnostic-visitor.c
===
--- clang/test/Analysis/taint-diagnostic-visitor.c
+++ clang/test/Analysis/taint-diagnostic-visitor.c
@@ -1,9 +1,12 @@
-// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.security.taint,core,alpha.security.ArrayBoundV2 -analyzer-output=text -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.security.taint,core,unix.Malloc,alpha.security.ArrayBoundV2 -analyzer-output=text -verify %s
 
 // This file is for testing enhanced diagnostics produced by the GenericTaintChecker
 
 int scanf(const char *restrict format, ...);
 int system(const char *command);
+typedef __typeof(sizeof(int)) size_t;
+void *malloc(size_t size);
+void free(void *ptr);
 
 void taintDiagnostic(void)
 {
@@ -34,3 +37,18 @@
   int vla[x]; // expected-warning {{Declared variable-length array (VLA) has tainted size}}
   // expected-note@-1 {{Declared variable-length array (VLA) has tainted size}}
 }
+
+void taintDiagnosticMalloc(int conj) {
+  int x;
+  scanf("%d", &x);
+  // expected-note@-1 2 {{Taint originated here}} Once for malloc(tainted), once for BoundsV2.
+
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}
+
+  p[1] = 1; // BoundsV2 checker can not prove that the access is safe.
+  // expected-warning@-1 {{Out of bound memory access (index is tainted)}}
+  // expected-note@-2{{Out of bound memory access (index is tainted)}}
+  free(p);
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checker

[libunwind] f6366ef - [libunwind][AArch64] Add support for DWARF expression for RA_SIGN_STATE.

2022-05-13 Thread Daniel Kiss via cfe-commits

Author: Daniel Kiss
Date: 2022-05-13T10:05:59+02:00
New Revision: f6366ef7f4f3cf1182fd70e0c50a9fa54374b612

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

LOG: [libunwind][AArch64] Add support for DWARF expression for RA_SIGN_STATE.

Program may set the RA_SIGN_STATE pseudo register by expressions.
Libunwind expected only the DW_CFA_AARCH64_negate_ra_state could change the 
value
of the register which leads to runtime errors on PAC enabled systems.
In the recent version of the aadwarf64[1] a limitation is added[2] to forbid 
the mixing the
DW_CFA_AARCH64_negate_ra_state with other DWARF Register Rule Instructions.

[1] https://github.com/ARM-software/abi-aa/releases/tag/2022Q1
[2] https://github.com/ARM-software/abi-aa/pull/129

Reviewed By: #libunwind, MaskRay

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

Added: 
libunwind/test/aarch64.ra_sign_state.pass.cpp

Modified: 
libunwind/src/DwarfInstructions.hpp

Removed: 




diff  --git a/libunwind/src/DwarfInstructions.hpp 
b/libunwind/src/DwarfInstructions.hpp
index ab83b0c87acdc..865a489526047 100644
--- a/libunwind/src/DwarfInstructions.hpp
+++ b/libunwind/src/DwarfInstructions.hpp
@@ -72,6 +72,10 @@ class DwarfInstructions {
 assert(0 && "getCFA(): unknown location");
 __builtin_unreachable();
   }
+#if defined(_LIBUNWIND_TARGET_AARCH64)
+  static bool getRA_SIGN_STATE(A &addressSpace, R registers, pint_t cfa,
+   PrologInfo &prolog);
+#endif
 };
 
 template 
@@ -166,6 +170,21 @@ v128 DwarfInstructions::getSavedVectorRegister(
   }
   _LIBUNWIND_ABORT("unsupported restore location for vector register");
 }
+#if defined(_LIBUNWIND_TARGET_AARCH64)
+template 
+bool DwarfInstructions::getRA_SIGN_STATE(A &addressSpace, R registers,
+   pint_t cfa, PrologInfo &prolog) 
{
+  pint_t raSignState;
+  auto regloc = prolog.savedRegisters[UNW_AARCH64_RA_SIGN_STATE];
+  if (regloc.location == CFI_Parser::kRegisterUnused)
+raSignState = regloc.value;
+  else
+raSignState = getSavedRegister(addressSpace, registers, cfa, regloc);
+
+  // Only bit[0] is meaningful.
+  return raSignState & 0x01;
+}
+#endif
 
 template 
 int DwarfInstructions::stepWithDwarf(A &addressSpace, pint_t pc,
@@ -235,7 +254,7 @@ int DwarfInstructions::stepWithDwarf(A &addressSpace, 
pint_t pc,
   // restored. autia1716 is used instead of autia as autia1716 assembles
   // to a NOP on pre-v8.3a architectures.
   if ((R::getArch() == REGISTERS_ARM64) &&
-  prolog.savedRegisters[UNW_AARCH64_RA_SIGN_STATE].value &&
+  getRA_SIGN_STATE(addressSpace, registers, cfa, prolog) &&
   returnAddress != 0) {
 #if !defined(_LIBUNWIND_IS_NATIVE_ONLY)
 return UNW_ECROSSRASIGNING;

diff  --git a/libunwind/test/aarch64.ra_sign_state.pass.cpp 
b/libunwind/test/aarch64.ra_sign_state.pass.cpp
new file mode 100644
index 0..1e09c936d664b
--- /dev/null
+++ b/libunwind/test/aarch64.ra_sign_state.pass.cpp
@@ -0,0 +1,63 @@
+// -*- 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
+//
+//===--===//
+
+// REQUIRES: linux && target={{aarch64-.+}}
+
+// This test ensures the .cfi_negate_ra_state the RA_SIGN_STATE pseudo register
+// could be set directly set by a DWARF expression and the unwinder handles it
+// correctly. The two directives can't be mixed in one CIE/FDE sqeuence.
+
+#include 
+
+__attribute__((noinline, target("branch-protection=pac-ret+leaf")))
+void bar() {
+  // ".cfi_negate_ra_state" is emitted by the compiler.
+  throw 1;
+}
+
+__attribute__((noinline, target("branch-protection=none")))
+void foo() {
+  // Here a DWARF expression sets RA_SIGN_STATE.
+  // The LR is signed manually and stored on the stack.
+  asm volatile(
+  ".cfi_escape 0x16,"// DW_CFA_val_expression
+"34,"// REG_34(RA_SIGN_STATE)
+ "1,"// expression_length(1)
+"0x31\n" // DW_OP_lit1
+  "add sp, sp, 16\n" // Restore SP's value before the stack frame is
+ // created.
+  "paciasp\n"// Sign the LR.
+  "str lr, [sp, -0x8]\n" // Overwrite LR on the stack.
+  "sub sp, sp, 16\n" // Restore SP's value.
+  );
+  bar();
+  _Exit(-1);
+}
+
+__attribute__((noinline, target("branch-protection=pac-ret")))
+void bazz() {
+  // ".cfi_negate_ra_state" is emitted by the compiler.
+  try {
+foo();
+  } catch (int i) {
+

[PATCH] D125524: [BoundV2] ArrayBoundV2 checks if the extent is tainted

2022-05-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 429159.
gamesh411 added a comment.

add analyzer tag


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125524

Files:
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/test/Analysis/taint-diagnostic-visitor.c


Index: clang/test/Analysis/taint-diagnostic-visitor.c
===
--- clang/test/Analysis/taint-diagnostic-visitor.c
+++ clang/test/Analysis/taint-diagnostic-visitor.c
@@ -1,9 +1,12 @@
-// RUN: %clang_cc1 -analyze 
-analyzer-checker=alpha.security.taint,core,alpha.security.ArrayBoundV2 
-analyzer-output=text -verify %s
+// RUN: %clang_cc1 -analyze 
-analyzer-checker=alpha.security.taint,core,unix.Malloc,alpha.security.ArrayBoundV2
 -analyzer-output=text -verify %s
 
 // This file is for testing enhanced diagnostics produced by the 
GenericTaintChecker
 
 int scanf(const char *restrict format, ...);
 int system(const char *command);
+typedef __typeof(sizeof(int)) size_t;
+void *malloc(size_t size);
+void free(void *ptr);
 
 void taintDiagnostic(void)
 {
@@ -34,3 +37,18 @@
   int vla[x]; // expected-warning {{Declared variable-length array (VLA) has 
tainted size}}
   // expected-note@-1 {{Declared variable-length array (VLA) has 
tainted size}}
 }
+
+void taintDiagnosticMalloc(int conj) {
+  int x;
+  scanf("%d", &x);
+  // expected-note@-1 2 {{Taint originated here}} Once for malloc(tainted), 
once for BoundsV2.
+
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted 
allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}
+
+  p[1] = 1; // BoundsV2 checker can not prove that the access is safe.
+  // expected-warning@-1 {{Out of bound memory access (index is tainted)}}
+  // expected-note@-2{{Out of bound memory access (index is tainted)}}
+  free(p);
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -205,10 +205,9 @@
 
 // If we are under constrained and the index variables are tainted, report.
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = rawOffset.getByteOffset();
-  if (isTainted(state, ByteOffset)) {
+  if (isTainted(state, *upperboundToCheck)) {
 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,
-  std::make_unique(ByteOffset));
+  std::make_unique(*upperboundToCheck));
 return;
   }
 } else if (state_exceedsUpperBound) {


Index: clang/test/Analysis/taint-diagnostic-visitor.c
===
--- clang/test/Analysis/taint-diagnostic-visitor.c
+++ clang/test/Analysis/taint-diagnostic-visitor.c
@@ -1,9 +1,12 @@
-// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.security.taint,core,alpha.security.ArrayBoundV2 -analyzer-output=text -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.security.taint,core,unix.Malloc,alpha.security.ArrayBoundV2 -analyzer-output=text -verify %s
 
 // This file is for testing enhanced diagnostics produced by the GenericTaintChecker
 
 int scanf(const char *restrict format, ...);
 int system(const char *command);
+typedef __typeof(sizeof(int)) size_t;
+void *malloc(size_t size);
+void free(void *ptr);
 
 void taintDiagnostic(void)
 {
@@ -34,3 +37,18 @@
   int vla[x]; // expected-warning {{Declared variable-length array (VLA) has tainted size}}
   // expected-note@-1 {{Declared variable-length array (VLA) has tainted size}}
 }
+
+void taintDiagnosticMalloc(int conj) {
+  int x;
+  scanf("%d", &x);
+  // expected-note@-1 2 {{Taint originated here}} Once for malloc(tainted), once for BoundsV2.
+
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}
+
+  p[1] = 1; // BoundsV2 checker can not prove that the access is safe.
+  // expected-warning@-1 {{Out of bound memory access (index is tainted)}}
+  // expected-note@-2{{Out of bound memory access (index is tainted)}}
+  free(p);
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -205,10 +205,9 @@
 
 // If we are under constrained and the index variables are tainted, report.
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = ra

[PATCH] D119720: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-05-13 Thread Dave Green via Phabricator via cfe-commits
dmgreen accepted this revision.
dmgreen added a comment.
This revision is now accepted and ready to land.

Thanks. LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119720

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-13 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

@aaron.ballman

I prepared a new public email address: `g...@kmatsui.me` instead of the 
auto-generated one.
So, could you please use the new one for future commit?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124726

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


[PATCH] D119720: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-05-13 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham accepted this revision.
simon_tatham added a comment.

Thanks, that explanation looks fine. (And I agree that re-paragraphing it made 
more sense than my version)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119720

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


[PATCH] D125383: [ASTMatchers][clang-tidy][NFC] Hoist 'forEachTemplateArgument' matcher into the core library

2022-05-13 Thread Whisperity via Phabricator via cfe-commits
whisperity updated this revision to Diff 429161.
whisperity added a comment.

- Added to `ASTMatchers/Registry.cpp`
- Updated with release notes


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

https://reviews.llvm.org/D125383

Files:
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -4971,6 +4971,63 @@
 std::make_unique>("if", 6)));
 }
 
+TEST(ForEachTemplateArgument, OnFunctionDecl) {
+  const std::string Code = R"(
+template  void f(T, U) {}
+void test() {
+  int I = 1;
+  bool B = false;
+  f(I, B);
+})";
+  EXPECT_TRUE(matches(
+  Code, functionDecl(forEachTemplateArgument(refersToType(builtinType(,
+  langCxx11OrLater()));
+  auto matcher =
+  functionDecl(forEachTemplateArgument(
+   templateArgument(refersToType(builtinType().bind("BT")))
+   .bind("TA")))
+  .bind("FN");
+
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("FN", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TA", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("BT", 2)));
+}
+
+TEST(ForEachTemplateArgument, OnClassTemplateSpecialization) {
+  const std::string Code = R"(
+template 
+struct Matrix {};
+
+static constexpr unsigned R = 2;
+
+Matrix M;
+)";
+  EXPECT_TRUE(matches(
+  Code, templateSpecializationType(forEachTemplateArgument(isExpr(expr(,
+  langCxx11OrLater()));
+  auto matcher = templateSpecializationType(
+ forEachTemplateArgument(
+ templateArgument(isExpr(expr().bind("E"))).bind("TA")))
+ .bind("TST");
+
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TST",
+  2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TA", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("E", 2)));
+}
+
 TEST(Has, DoesNotDeleteBindings) {
   EXPECT_TRUE(matchAndVerifyResultTrue(
 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -250,6 +250,7 @@
   REGISTER_MATCHER(forEachLambdaCapture);
   REGISTER_MATCHER(forEachOverridden);
   REGISTER_MATCHER(forEachSwitchCase);
+  REGISTER_MATCHER(forEachTemplateArgument);
   REGISTER_MATCHER(forField);
   REGISTER_MATCHER(forFunction);
   REGISTER_MATCHER(forStmt);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -5011,6 +5011,49 @@
   return Node.getNumParams() == N;
 }
 
+/// Matches classTemplateSpecialization, templateSpecializationType and
+/// functionDecl nodes where the template argument matches the inner matcher.
+/// This matcher may produce multiple matches.
+///
+/// Given
+/// \code
+///   template 
+///   struct Matrix {};
+///
+///   constexpr unsigned R = 2;
+///   Matrix M;
+///
+///   template 
+///   void f(T&& t, U&& u) {}
+///
+///   bool B = false;
+///   f(R, B);
+/// \endcode
+/// templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+///   matches twice, with expr() matching 'R * 2' and 'R * 4'
+/// functionDecl(forEachTemplateArgument(refersToType(builtinType(
+///   matches the specialization f twice, for 'unsigned'
+///   and 'bool'
+AST_POLYMORPHIC_MATCHER_P(
+forEachTemplateArgument,
+AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
+TemplateSpecializationType, FunctionDecl),
+clang::ast_matchers::internal::Matcher, InnerMatcher) {
+  ArrayRef TemplateArgs =
+  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
+  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
+  bool Matched = false;
+  for (const auto &Arg : TemplateArgs) {
+clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
+if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
+  Matched = true;
+  Result.addMatch(ArgBuilder);
+}
+  }
+  *Builder = std::move(Result);
+  return Mat

[PATCH] D125383: [ASTMatchers][clang-tidy][NFC] Hoist 'forEachTemplateArgument' matcher into the core library

2022-05-13 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In D125383#3509084 , @aaron.ballman 
wrote:

> Then I think the only thing missing here are updates to 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/ASTMatchers/Dynamic/Registry.cpp.

Could you please check if I did it the right way? I did not know about this 
file, and I am still not exactly sure about its purpose.


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

https://reviews.llvm.org/D125383

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


[PATCH] D124974: [clang] Include clang config.h in LangStandards.cpp

2022-05-13 Thread Cassie Jones via Phabricator via cfe-commits
porglezomp added a comment.

That looks good to me. I'm testing it out locally to make sure it still works 
right and also catches the issue, and will plan put up an updated patch in the 
morning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124974

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


[PATCH] D124715: Add ThreadPriority::Low, and use QoS class Utility on Mac

2022-05-13 Thread Stefan Haller via Phabricator via cfe-commits
stefanhaller added a comment.

In D124715#3498846 , @sammccall wrote:

> Looks great! I'm happy to land it, will do so on Tuesday unless anyone has 
> further comments.

@sammccall Just a friendly ping, in case you forgot. 😄


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-13 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

@aaron.ballman

I prepared a new public email address: `v...@kmatsui.me` instead of the 
auto-generated one.
So, could you please use the new one for future commit?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124726

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


[PATCH] D125526: Fix ADL leakage due to MSVC compatibility flag

2022-05-13 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource created this revision.
frederic-tingaud-sonarsource added a reviewer: rnk.
Herald added a project: All.
frederic-tingaud-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Patch https://reviews.llvm.org/D124613 introduced an ADL leakage of friend 
functions when in MSVC compatibility mode. It broke some C++ compliant code. 
That patch fixes the problem introduced.

The original fix flagged friend function declarations as declarations, to 
follow MSVC behavior. The problem it introduced is that this same flag is used 
to do ADL and that made friend functions visible at the namespace level instead 
of them being visible at the class level only.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125526

Files:
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaCXX/ms-friend-function-decl.cpp


Index: clang/test/SemaCXX/ms-friend-function-decl.cpp
===
--- clang/test/SemaCXX/ms-friend-function-decl.cpp
+++ clang/test/SemaCXX/ms-friend-function-decl.cpp
@@ -1,9 +1,5 @@
-// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern 
%s
-#if __cplusplus < 202002L
-// expected-no-diagnostics
-#endif
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only 
-verify=expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only 
-verify=modern,expected %s
 
 namespace ns {
 
@@ -43,3 +39,43 @@
 
 void funGlob() {
 }
+
+// At some point, considering friend declaration as full declarations broke 
ADL detection.
+// The following test checks that the friend declaration is only visible 
inside the class it's declared in.
+namespace check_adl {
+template 
+struct A {};
+
+struct NotADLVisible {
+  template 
+  friend constexpr bool operator==(A, NotADLVisible) noexcept {
+static_assert(sizeof(T) < 0, "This should never be instantiated");
+return false;
+  }
+
+  constexpr NotADLVisible(int) {}
+};
+} // namespace check_adl
+
+void shouldNotSeeAnyOperator() {
+  bool b = check_adl::A() == 2; // expected-error {{invalid operands to 
binary expression ('check_adl::A' and 'int')}}
+}
+
+// Check that we don't break the case of a function that is both visible to 
ADL and a friend
+namespace check_adl_compliant {
+struct A {};
+
+struct B {
+  friend constexpr bool operator==(A, B) noexcept;
+
+  constexpr B(int) {}
+};
+
+constexpr bool operator==(check_adl_compliant::A, check_adl_compliant::B) 
noexcept {
+  return false;
+}
+} // namespace check_adl_compliant
+
+void shouldSeeTheOperator() {
+  bool b = check_adl_compliant::A() == 2;
+}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -3634,14 +3634,17 @@
   bool Visible = false;
   for (D = D->getMostRecentDecl(); D;
D = cast_or_null(D->getPreviousDecl())) {
-if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
-  if (isVisible(D)) {
+// We check the friend case first because in case of MSVC compatibility
+// a friend declaration is also flagged as Ordinary but we don't want
+// it to be visible outside its associated class.
+if (D->getFriendObjectKind()) {
+  auto *RD = cast(D->getLexicalDeclContext());
+  if (AssociatedClasses.count(RD) && isVisible(D)) {
 Visible = true;
 break;
   }
-} else if (D->getFriendObjectKind()) {
-  auto *RD = cast(D->getLexicalDeclContext());
-  if (AssociatedClasses.count(RD) && isVisible(D)) {
+} else if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
+  if (isVisible(D)) {
 Visible = true;
 break;
   }


Index: clang/test/SemaCXX/ms-friend-function-decl.cpp
===
--- clang/test/SemaCXX/ms-friend-function-decl.cpp
+++ clang/test/SemaCXX/ms-friend-function-decl.cpp
@@ -1,9 +1,5 @@
-// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern %s
-#if __cplusplus < 202002L
-// expected-no-diagnostics
-#endif
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify=expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern,expected %s
 
 namespace ns {
 
@@ -43,3 +39,43 @@
 
 void funGlob() {
 }
+
+// At some point, considering friend declaration as full declarations broke ADL detection.
+// The following test checks that the friend declaration is only visible inside the class it's declared in.

[PATCH] D124613: In MSVC compatibility mode, friend function declarations behave as function declarations

2022-05-13 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource added a comment.

Sorry for the delay, the fix is here: https://reviews.llvm.org/D125526
If there is any risk or problem identified with this new fix that could delay 
it, I'll propose a revert of this one to avoid breaking more legitimate code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124613

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


[PATCH] D125323: [RISCV] Add the passthru operand for RVV unmasked segment load IR intrinsics.

2022-05-13 Thread Zakk Chen 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 rG7dfc56c10746: [RISCV] Add the passthru operand for RVV 
unmasked segment load IR intrinsics. (authored by khchen).

Changed prior to commit:
  https://reviews.llvm.org/D125323?vs=428674&id=429171#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125323

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vloxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vloxseg_mf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vluxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vluxseg_mf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vloxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vloxseg_mask.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vloxseg_mask_mf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vloxseg_mf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vlseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vlsegff.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vlsseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vluxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vluxseg_mask.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vluxseg_mask_mf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vluxseg_mf.c
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.h
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/test/CodeGen/RISCV/regalloc-last-chance-recoloring-failure.ll
  llvm/test/CodeGen/RISCV/rvv/rv32-spill-zvlsseg.ll
  llvm/test/CodeGen/RISCV/rvv/rv64-spill-zvlsseg.ll
  llvm/test/CodeGen/RISCV/rvv/vloxseg-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vloxseg-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vlseg-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vlseg-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vlseg2ff-rv32-readvl.ll
  llvm/test/CodeGen/RISCV/rvv/vlseg2ff-rv64-readvl.ll
  llvm/test/CodeGen/RISCV/rvv/vlsegff-rv32-dead.ll
  llvm/test/CodeGen/RISCV/rvv/vlsegff-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vlsegff-rv64-dead.ll
  llvm/test/CodeGen/RISCV/rvv/vlsegff-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vlsseg-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vlsseg-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vluxseg-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vluxseg-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/zvlsseg-zero-vl.ll

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


[PATCH] D123773: [clang][analyzer][ctu] Make CTU a two phase analysis

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 15 inline comments as done.
martong added inline comments.



Comment at: clang/include/clang/AST/ASTImporterSharedState.h:83
+
+  void setNewDecl(Decl *ToD) { NewDecls.insert(ToD); }
 };

whisperity wrote:
> (The naming of this function feels a bit odd. `markAsNewDecl` or just 
> `markNewDecl`?)
Good point, `markAsNewDecl` sounds better. I'll update this in the parent patch 
https://reviews.llvm.org/D123685 though (and rebase this).



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def:413-419
+"We count the nodes for a normal single tu analysis. We multiply that "
+"number with this config value then we divide the result by 100 to get "
+"the maximum number of nodes that the analyzer can generate while "
+"exploring a top level function in CTU mode (for each exploded graph)."
+"For example, 100 means that CTU will explore maximum as much nodes that "
+"we explored during the single tu mode, 200 means it will explore twice as 
"
+"much, 50 means it will explore maximum 50% more.", 100)

whisperity wrote:
> whisperity wrote:
> > 
> Couldn't this description here be simplified to say something along the lines 
> of //"the percentage of single-TU analysed nodes that the CTU analysis is 
> allowed to visit"//? Is the calculation method needed from the user's 
> perspective? The examples talk about percentage too.
Thanks, this is so true, very good point. I've changed it. And also changed the 
name to suffix `-pct` instead of `-mul` to reflect this.



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:141
 
+enum class CTUPhase1InliningKind { None, Small, All };
+

whisperity wrote:
> whisperity wrote:
> > Is this configuration inherent to the static analyser, and not the 
> > //CrossTU// library?
> (Documentation for the options are missing.)
Yes, this is only for the analyzer.



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:141
 
+enum class CTUPhase1InliningKind { None, Small, All };
+

martong wrote:
> whisperity wrote:
> > whisperity wrote:
> > > Is this configuration inherent to the static analyser, and not the 
> > > //CrossTU// library?
> > (Documentation for the options are missing.)
> Yes, this is only for the analyzer.
This is the direct representation of the analyzer option `ctu-phase1-inlining` 
and there is a bulky documentation for that in `AnalyzerOptions.def`. I'd 
rather not repeat that documentation here.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h:814-816
+  /// Returns true if the CTU analysis is running its first phase.
+  /// Returns true in single TU (non-CTU) mode!
+  bool isCTUInFirtstPhase() { return Engine.getCTUWorkList(); }

whisperity wrote:
> How and why is this needed? Could you call it `isSingleTUOr1stPhaseCTU` 
> instead?
> 
> Rather, if this is used as a distinction input in conditionals, could you 
> invert the branches and have a function `isSecondPhaseCTU`, and do the 
> inverted logic where this function is consumed?
Yep, very good point, thanks again. Changed it with the inverted branch version.



Comment at: 
clang/test/Analysis/Inputs/ctu-onego-existingdef-other.cpp.externalDefMap.ast-dump.txt:1
+11:c:@F@other# ctu-onego-other.cpp.ast

whisperity wrote:
> Why is there only 1 symbol in this file, when the file above contains two 
> function definitions?
Good catch. I've added the other function. Besides, I had the wrong filename 
provided, it should have been `ctu-onego-existingdef-other.cpp.ast`, the 
`existingdef` was missing. Fixed that too, plus added and extra `FileCheck` to 
the `existingdef` test that detects if the ast file is not loaded.



Comment at: clang/test/Analysis/ctu-onego-toplevel.cpp:30
+
+// During the onego CTU analysis, we start with c() as top level function.
+// Then we visit b() as non-toplevel during the processing of the FWList, thus

whisperity wrote:
> One-go? And what does that refer to? Is "Onego" analysis the one this patch 
> is introducing?
Yes. I've updated the summary of the patch to make this clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123773

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


[PATCH] D123773: [clang][analyzer][ctu] Make CTU a two phase analysis

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429172.
martong marked 7 inline comments as done.
martong added a comment.

- Change -mul to -pct
- Change default values to ctu-max-nodes-pct = 50 and ctu-max-nodes-min = 1
- Rename isCTUInFirtstPhase to isSecondPhaseCTU and invert the condition
- Check that the AST file is loaded in existingdef test file
- Set CTUWlist as nullptr in single-TU mode
- Add bar to ctu-onego-existingdef-other.cpp.externalDefMap.ast-dump.txt
- Changes in comments of test files


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123773

Files:
  clang/include/clang/CrossTU/CrossTranslationUnit.h
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  clang/test/Analysis/Inputs/ctu-onego-existingdef-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-existingdef-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-indirect-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-indirect-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-small-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-small-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-toplevel-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-toplevel-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/ctu-implicit.c
  clang/test/Analysis/ctu-main.c
  clang/test/Analysis/ctu-main.cpp
  clang/test/Analysis/ctu-on-demand-parsing.c
  clang/test/Analysis/ctu-on-demand-parsing.cpp
  clang/test/Analysis/ctu-onego-existingdef.cpp
  clang/test/Analysis/ctu-onego-indirect.cpp
  clang/test/Analysis/ctu-onego-small.cpp
  clang/test/Analysis/ctu-onego-toplevel.cpp

Index: clang/test/Analysis/ctu-onego-toplevel.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-onego-toplevel.cpp
@@ -0,0 +1,54 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -emit-pch -o %t/ctudir/ctu-onego-toplevel-other.cpp.ast %S/Inputs/ctu-onego-toplevel-other.cpp
+// RUN: cp %S/Inputs/ctu-onego-toplevel-other.cpp.externalDefMap.ast-dump.txt %t/ctudir/externalDefMap.txt
+
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config ctu-phase1-inlining=none \
+// RUN:   -verify=ctu %s
+
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config ctu-phase1-inlining=none \
+// RUN:   -analyzer-config display-ctu-progress=true \
+// RUN:   -analyzer-display-progress \
+// RUN:   -verify=ctu %s 2>&1 | FileCheck %s
+
+// CallGraph: c->b
+// topological sort: c, b
+// Note that `other` calls into `b` but that is not visible in the CallGraph
+// because that happens in another TU.
+
+// During the onego CTU analysis, we start with c() as top level function.
+// Then we visit b() as non-toplevel during the processing of the FWList, thus
+// that would not be visited as toplevel without special care.
+
+// `c` is analyzed as toplevel and during that the other TU is loaded:
+// CHECK: ANALYZE (Path,  Inline_Regular): {{.*}} c(int){{.*}}CTU loaded AST file
+// next, `b` is analyzed as toplevel:
+// CHECK: ANALYZE (Path,  Inline_Regular): {{.*}} b(int)
+
+void b(int x);
+void other(int y);
+void c(int y) {
+  other(y);
+  return;
+  // The below call is here to form the proper CallGraph, but will not be
+  // analyzed.
+  b(1);
+}
+
+void b(int x) {
+  if (x == 0)
+(void)(1 / x);
+// ctu-warning@-1{{Division by zero}}
+// We receive the above warning only if `b` is analyzed as top-level.
+}
Index: clang/test/Analysis/ctu-onego-small.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-onego-small.cpp
@@ -0,0 +1,51 @@
+// RUN: rm 

[PATCH] D122747: [NFC][ARM] Tests for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-05-13 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.

I spent some time last night trying to work out if a combination of 
`--enable-misched=false --pre-RA-sched=linearize -disable-post-ra 
-enable-post-misched=false` would help avoid having two sets of match lines, 
and none seemed to. @MaskRay as I can't find a quick way of making it smaller, 
and the patch these tests are for has been approved, I'm going to land this 
as-is. I hope that is ok.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122747

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


[PATCH] D125526: Fix ADL leakage due to MSVC compatibility flag

2022-05-13 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource abandoned this revision.
frederic-tingaud-sonarsource added a comment.

After checking, I realize that the previous fix was really mimicking MSVC 
behavior up to its mishandling of standard compliant code.
https://godbolt.org/z/cEPGfMz3f
I'll revert it for now and try to see if there is a way to have it under 
another flag or something.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125526

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


[PATCH] D125517: [Frontend] [Coroutines] Emit error when we found incompatible allocation function in promise_type

2022-05-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 429176.
ChuanqiXu added a comment.

Remove invalid character


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

https://reviews.llvm.org/D125517

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaCoroutine.cpp
  clang/test/SemaCXX/coroutine-allocs.cpp

Index: clang/test/SemaCXX/coroutine-allocs.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/coroutine-allocs.cpp
@@ -0,0 +1,61 @@
+// RUN: %clang_cc1 %s -std=c++20 -fsyntax-only -verify
+#include "Inputs/std-coroutine.h"
+
+namespace std {
+typedef decltype(sizeof(int)) size_t;
+}
+
+struct Allocator {};
+
+struct resumable {
+  struct promise_type {
+void *operator new(std::size_t sz, Allocator &);
+
+resumable get_return_object() { return {}; }
+auto initial_suspend() { return std::suspend_always(); }
+auto final_suspend() noexcept { return std::suspend_always(); }
+void unhandled_exception() {}
+void return_void(){};
+  };
+};
+
+resumable f1() { // expected-error {{'operator new' provided by 'std::coroutine_traits::promise_type' (aka 'resumable::promise_type') is not usable}}
+  co_return;
+}
+
+// NOTE: Although the argument here is a rvalue reference and the corresponding
+// allocation function in resumable::promise_type have lvalue references, it looks
+// the signature of f2 is invalid. But according to [dcl.fct.def.coroutine]p4:
+//
+//   In the following, pi is an lvalue of type Pi, where p1 denotes the object 
+//   parameter and pi+1 denotes the ith non-object function parameter for a
+//   non-static member function.
+//
+// And [dcl.fct.def.coroutine]p9.1
+//
+//   overload resolution is performed on a function call created by assembling an argument list.
+//   The first argument is the amount of space requested, and has type std::size_­t.
+//   The lvalues p1…pn are the succeeding arguments.
+//
+// So the acctual type passed to resumable::promise_type::operator new is lvalue
+// Allocator. It is allowed  to convert a lvalue to a lvalue reference. So the 
+// following one is valid.
+resumable f2(Allocator &&) {
+  co_return;
+}
+
+resumable f3(Allocator &) {
+  co_return;
+}
+
+resumable f4(Allocator) {
+  co_return;
+}
+
+resumable f5(const Allocator) { // expected-error {{operator new' provided by 'std::coroutine_traits::promise_type' (aka 'resumable::promise_type') is not usable}}
+  co_return;
+}
+
+resumable f6(const Allocator &) { // expected-error {{operator new' provided by 'std::coroutine_traits::promise_type' (aka 'resumable::promise_type') is not usable}}
+  co_return;
+}
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1308,10 +1308,39 @@
 
 PlacementArgs.push_back(PDRefExpr.get());
   }
-  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
-/*DeleteScope*/ Sema::AFS_Both, PromiseType,
-/*isArray*/ false, PassAlignment, PlacementArgs,
-OperatorNew, UnusedResult, /*Diagnose*/ false);
+
+  bool PromiseContainNew = [this, &PromiseType]() -> bool {
+DeclarationName NewName =
+S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
+LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
+
+if (PromiseType->isRecordType())
+  S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
+
+return !R.empty() && !R.isAmbiguous();
+  }();
+
+  auto LookupAllocationFunction = [&]() {
+// [dcl.fct.def.coroutine]p9
+//   The allocation function's name is looked up by searching for it in the
+// scope of the promise type.
+// - If any declarations are found, ...
+if (PromiseContainNew)
+  S.FindAllocationFunctions(Loc, SourceRange(),
+/*NewScope*/ Sema::AFS_Class,
+/*DeleteScope*/ Sema::AFS_Both, PromiseType,
+/*isArray*/ false, PassAlignment, PlacementArgs,
+OperatorNew, UnusedResult, /*Diagnose*/ false);
+// - Otherwise, a search is performed in the global scope.
+else
+  S.FindAllocationFunctions(Loc, SourceRange(),
+/*NewScope*/ Sema::AFS_Global,
+/*DeleteScope*/ Sema::AFS_Both, PromiseType,
+/*isArray*/ false, PassAlignment, PlacementArgs,
+OperatorNew, UnusedResult, /*Diagnose*/ false);
+  };
+
+  LookupAllocationFunction();
 
   // [dcl.fct.def.coroutine]p9
   //   If no viable function is found ([over.match.viable]), overload resolution
@@ -1319,22 +1348,7 @@
   // space required as an argument of type std::size_t.
   if (!OperatorNew && !PlacementArgs.empty()) {
  

[PATCH] D125528: [clang-format] Fix PointerAlignment: Right not working with tab indentation.

2022-05-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: HazardyKnusperkeks, owenpan, MyDeveloperDay.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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

Given configuration:

  UseTab: Always
  PointerAlignment: Right
  AlignConsecutiveDeclarations: true

Before, the pointer was misaligned in this code:

  void f() {
unsigned long long big;
char  *ptr; // misaligned
inti;
  }

That was due to the fact that when handling right-aligned pointers, the Spaces 
were changed but StartOfTokenColumn was not.

Also, a tab was used not only for indentation but for spacing too when using 
`UseTab: ForIndentation` config option:

  

void f() {
unsigned long long big;
char  *ptr; // \t after char
inti;
}

  


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125528

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14161,6 +14161,21 @@
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,27 @@
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar * ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar  *ptr;\n"
+   "}",
+   TabAlignment);
+
   Tab.UseTab = FormatStyle::UT_ForIndentation;
   verifyFormat("{\n"
"\t();\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -432,6 +432,7 @@
--Previous) {
 Changes[Previous + 1].Spaces -= Shift;
 Changes[Previous].Spaces += Shift;
+Changes[Previous].StartOfTokenColumn += Shift;
   }
 }
   }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14161,6 +14161,21 @@
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,27 @@
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlign

[PATCH] D125529: Revert MSVC compatibility feature that breaks conformant code

2022-05-13 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource created this revision.
frederic-tingaud-sonarsource added reviewers: rnk, thakis.
Herald added a reviewer: shafik.
Herald added a project: All.
frederic-tingaud-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The fix at https://reviews.llvm.org/D124613 mimics MSVC behavior with friend 
declarations, but it does break some C++ conformant code that was built with 
-fms-compatibility. This fix reverts it to avoid causing more problems.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125529

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/ms-friend-function-decl.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -2658,10 +2658,7 @@
   getTuDecl("struct X { friend void f(); };", Lang_CXX03, "input0.cc");
   auto *FromD = FirstDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
-FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   {
 auto FromName = FromD->getDeclName();
 auto *Class = FirstDeclMatcher().match(FromTU, ClassPattern);
@@ -2705,10 +2702,7 @@
   auto *FromNormal =
   LastDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
-FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
 
@@ -2799,10 +2793,7 @@
 
   ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromFriendTU->getLangOpts().MSVCCompat,
-FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_TRUE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   auto LookupRes = FromNormalTU->noload_lookup(FromNormalName);
   ASSERT_TRUE(LookupRes.isSingleResult());
Index: clang/test/SemaCXX/ms-friend-function-decl.cpp
===
--- clang/test/SemaCXX/ms-friend-function-decl.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern %s
-#if __cplusplus < 202002L
-// expected-no-diagnostics
-#endif
-
-namespace ns {
-
-class C {
-public:
-  template 
-  friend void funtemp();
-
-  friend void fun();
-
-  void test() {
-::ns::fun(); // modern-error {{no member named 'fun' in namespace 'ns'}}
-
-// modern-error@+3 {{no member named 'funtemp' in namespace 'ns'}}
-// modern-error@+2 {{expected '(' for function-style cast or type construction}}
-// modern-error@+1 {{expected expression}}
-::ns::funtemp();
-  }
-};
-
-void fun() {
-}
-
-template 
-void funtemp() {}
-
-} // namespace ns
-
-class Glob {
-public:
-  friend void funGlob();
-
-  void test() {
-funGlob(); // modern-error {{use of undeclared identifier 'funGlob'}}
-  }
-};
-
-void funGlob() {
-}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9632,15 +9632,11 @@
 }
 
 if (isFriend) {
-  // In MSVC mode for older versions of the standard, friend function
-  // declarations behave as declarations
-  bool PerformFriendInjection =
-  getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20;
   if (FunctionTemplate) {
-FunctionTemplate->setObjectOfFriendDecl(PerformFriendInjection);
+FunctionTemplate->setObjectOfFriendDecl();
 FunctionTemplate->setAccess(AS_public);
   }
-  NewFD->setObjectOfFriendDecl(PerformFriendInjection);
+  NewFD->setObjectOfFriendDecl();
   NewFD->setAccess(AS_public);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailma

[clang] 3a24df9 - [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-05-13 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2022-05-13T10:47:33+01:00
New Revision: 3a24df992cf87029ed89c5a4a6be4049b73ff3ab

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

LOG: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

This adds a late Machine Pass to work around a Cortex CPU Erratum
affecting Cortex-A57 and Cortex-A72:
- Cortex-A57 Erratum 1742098
- Cortex-A72 Erratum 1655431

The pass inserts instructions to make the inputs to the fused AES
instruction pairs no longer trigger the erratum. Here the pass errs on
the side of caution, inserting the instructions wherever we cannot prove
that the inputs came from a safe instruction.

The pass is used:
- for Cortex-A57 and Cortex-A72,
- for "generic" cores (which are used when using `-march=`),
- when the user specifies `-mfix-cortex-a57-aes-1742098` or
  `mfix-cortex-a72-aes-1655431` in the command-line arguments to clang.

Reviewed By: dmgreen, simon_tatham

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

Added: 
clang/test/Driver/arm-fix-cortex-a57-aes-1742098.c
llvm/lib/Target/ARM/ARMFixCortexA57AES1742098Pass.cpp

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/ARM.cpp
llvm/lib/Target/ARM/ARM.h
llvm/lib/Target/ARM/ARM.td
llvm/lib/Target/ARM/ARMTargetMachine.cpp
llvm/lib/Target/ARM/CMakeLists.txt
llvm/test/CodeGen/ARM/O3-pipeline.ll
llvm/test/CodeGen/ARM/aes-erratum-fix.ll

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6668ac4ca9470..a4fb0e3697012 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3451,6 +3451,20 @@ def mfix_cmse_cve_2021_35465 : Flag<["-"], 
"mfix-cmse-cve-2021-35465">,
 def mno_fix_cmse_cve_2021_35465 : Flag<["-"], "mno-fix-cmse-cve-2021-35465">,
   Group,
   HelpText<"Don't work around VLLDM erratum CVE-2021-35465 (ARM only)">;
+def mfix_cortex_a57_aes_1742098 : Flag<["-"], "mfix-cortex-a57-aes-1742098">,
+  Group,
+  HelpText<"Work around Cortex-A57 Erratum 1742098 (ARM only)">;
+def mno_fix_cortex_a57_aes_1742098 : Flag<["-"], 
"mno-fix-cortex-a57-aes-1742098">,
+  Group,
+  HelpText<"Don't work around Cortex-A57 Erratum 1742098 (ARM only)">;
+def mfix_cortex_a72_aes_1655431 : Flag<["-"], "mfix-cortex-a72-aes-1655431">,
+  Group,
+  HelpText<"Work around Cortex-A72 Erratum 1655431 (ARM only)">,
+  Alias;
+def mno_fix_cortex_a72_aes_1655431 : Flag<["-"], 
"mno-fix-cortex-a72-aes-1655431">,
+  Group,
+  HelpText<"Don't work around Cortex-A72 Erratum 1655431 (ARM only)">,
+  Alias;
 def mfix_cortex_a53_835769 : Flag<["-"], "mfix-cortex-a53-835769">,
   Group,
   HelpText<"Workaround Cortex-A53 erratum 835769 (AArch64 only)">;

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 2d961f6e836ff..0dbb25de45a3d 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -733,6 +733,16 @@ void arm::getARMTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   Features.push_back("-fix-cmse-cve-2021-35465");
   }
 
+  // This also handles the -m(no-)fix-cortex-a72-1655431 arguments via aliases.
+  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a57_aes_1742098,
+   options::OPT_mno_fix_cortex_a57_aes_1742098)) {
+if (A->getOption().matches(options::OPT_mfix_cortex_a57_aes_1742098)) {
+  Features.push_back("+fix-cortex-a57-aes-1742098");
+} else {
+  Features.push_back("-fix-cortex-a57-aes-1742098");
+}
+  }
+
   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
   // neither options are specified, see if we are compiling for kernel/kext and
   // decide whether to pass "+long-calls" based on the OS and its version.

diff  --git a/clang/test/Driver/arm-fix-cortex-a57-aes-1742098.c 
b/clang/test/Driver/arm-fix-cortex-a57-aes-1742098.c
new file mode 100644
index 0..84e43cb55b433
--- /dev/null
+++ b/clang/test/Driver/arm-fix-cortex-a57-aes-1742098.c
@@ -0,0 +1,25 @@
+// RUN: %clang -### %s -target arm-none-none-eabi -march=armv8a 
-mfix-cortex-a57-aes-1742098 2>&1 | FileCheck %s --check-prefix=FIX
+// RUN: %clang -### %s -target arm-none-none-eabi -march=armv8a 
-mno-fix-cortex-a57-aes-1742098 2>&1 | FileCheck %s --check-prefix=NO-FIX
+
+// RUN: %clang -### %s -target arm-none-none-eabi -march=armv8a 
-mfix-cortex-a72-aes-1655431 2>&1 | FileCheck %s --check-prefix=FIX
+// RUN: %clang -### %s -target arm-none-none-eabi -march=armv8a 
-mno-fix-cortex-a72-aes-1655431 2>&1 | FileCheck %s --check-prefix=NO-FIX
+
+// RUN: %clang -### %s -target arm-none-none-eabi -march=armv8a 2>&1 | 
FileCheck %s --check-prefix=UNSPEC
+// RUN: %clang -### 

[PATCH] D119720: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-05-13 Thread Sam Elliott 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 rG3a24df992cf8: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused 
AES Erratum (authored by lenary).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119720

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/arm-fix-cortex-a57-aes-1742098.c
  llvm/lib/Target/ARM/ARM.h
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMFixCortexA57AES1742098Pass.cpp
  llvm/lib/Target/ARM/ARMTargetMachine.cpp
  llvm/lib/Target/ARM/CMakeLists.txt
  llvm/test/CodeGen/ARM/O3-pipeline.ll
  llvm/test/CodeGen/ARM/aes-erratum-fix.ll

Index: llvm/test/CodeGen/ARM/aes-erratum-fix.ll
===
--- llvm/test/CodeGen/ARM/aes-erratum-fix.ll
+++ llvm/test/CodeGen/ARM/aes-erratum-fix.ll
@@ -47,6 +47,7 @@
 ; CHECK-FIX-NEXT:push {r4, lr}
 ; CHECK-FIX-NEXT:mov r4, r0
 ; CHECK-FIX-NEXT:bl get_input
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:vld1.64 {d16, d17}, [r4]
 ; CHECK-FIX-NEXT:aese.8 q0, q8
 ; CHECK-FIX-NEXT:aesmc.8 q8, q0
@@ -67,6 +68,7 @@
 ; CHECK-FIX-NEXT:push {r4, lr}
 ; CHECK-FIX-NEXT:mov r4, r0
 ; CHECK-FIX-NEXT:bl get_inputf16
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:vld1.64 {d16, d17}, [r4]
 ; CHECK-FIX-NEXT:aese.8 q0, q8
 ; CHECK-FIX-NEXT:aesmc.8 q8, q0
@@ -87,6 +89,7 @@
 ; CHECK-FIX-NEXT:push {r4, lr}
 ; CHECK-FIX-NEXT:mov r4, r0
 ; CHECK-FIX-NEXT:bl get_inputf32
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:vld1.64 {d16, d17}, [r4]
 ; CHECK-FIX-NEXT:aese.8 q0, q8
 ; CHECK-FIX-NEXT:aesmc.8 q8, q0
@@ -120,6 +123,8 @@
 define arm_aapcs_vfpcc <16 x i8> @aese_once_via_val(<16 x i8> %0, <16 x i8> %1) nounwind {
 ; CHECK-FIX-LABEL: aese_once_via_val:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q1, q1, q1
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:aese.8 q1, q0
 ; CHECK-FIX-NEXT:aesmc.8 q0, q1
 ; CHECK-FIX-NEXT:bx lr
@@ -156,6 +161,9 @@
 define arm_aapcs_vfpcc <16 x i8> @aese_twice_via_val(<16 x i8> %0, <16 x i8> %1) nounwind {
 ; CHECK-FIX-LABEL: aese_twice_via_val:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q1, q1, q1
+; CHECK-FIX-NEXT:vorr q0, q0, q0
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:aese.8 q1, q0
 ; CHECK-FIX-NEXT:aesmc.8 q8, q1
 ; CHECK-FIX-NEXT:aese.8 q8, q0
@@ -219,6 +227,8 @@
 define arm_aapcs_vfpcc <16 x i8> @aese_loop_via_val(i32 %0, <16 x i8> %1, <16 x i8> %2) nounwind {
 ; CHECK-FIX-LABEL: aese_loop_via_val:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q1, q1, q1
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:cmp r0, #0
 ; CHECK-FIX-NEXT:beq .LBB9_2
 ; CHECK-FIX-NEXT:  .LBB9_1: @ =>This Inner Loop Header: Depth=1
@@ -249,6 +259,7 @@
 define arm_aapcs_vfpcc void @aese_set8_via_ptr(i8* %0, <16 x i8> %1, <16 x i8>* %2) nounwind {
 ; CHECK-FIX-NOSCHED-LABEL: aese_set8_via_ptr:
 ; CHECK-FIX-NOSCHED:   @ %bb.0:
+; CHECK-FIX-NOSCHED-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NOSCHED-NEXT:ldrb r0, [r0]
 ; CHECK-FIX-NOSCHED-NEXT:vld1.64 {d16, d17}, [r1]
 ; CHECK-FIX-NOSCHED-NEXT:vmov.8 d0[0], r0
@@ -260,6 +271,7 @@
 ;
 ; CHECK-CORTEX-FIX-LABEL: aese_set8_via_ptr:
 ; CHECK-CORTEX-FIX:   @ %bb.0:
+; CHECK-CORTEX-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-CORTEX-FIX-NEXT:vld1.64 {d16, d17}, [r1]
 ; CHECK-CORTEX-FIX-NEXT:ldrb r0, [r0]
 ; CHECK-CORTEX-FIX-NEXT:vmov.8 d0[0], r0
@@ -281,6 +293,7 @@
 define arm_aapcs_vfpcc void @aese_set8_via_val(i8 zeroext %0, <16 x i8> %1, <16 x i8>* %2) nounwind {
 ; CHECK-FIX-LABEL: aese_set8_via_val:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:vld1.64 {d16, d17}, [r1]
 ; CHECK-FIX-NEXT:vmov.8 d0[0], r0
 ; CHECK-FIX-NEXT:vmov.8 d16[0], r0
@@ -300,6 +313,7 @@
 define arm_aapcs_vfpcc void @aese_set8_cond_via_ptr(i1 zeroext %0, i8* %1, <16 x i8> %2, <16 x i8>* %3) nounwind {
 ; CHECK-FIX-LABEL: aese_set8_cond_via_ptr:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:cmp r0, #0
 ; CHECK-FIX-NEXT:beq .LBB12_2
 ; CHECK-FIX-NEXT:  @ %bb.1:
@@ -351,6 +365,7 @@
 define arm_aapcs_vfpcc void @aese_set8_cond_via_val(i1 zeroext %0, i8 zeroext %1, <16 x i8> %2, <16 x i8>* %3) nounwind {
 ; CHECK-FIX-LABEL: aese_set8_cond_via_val:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q0, q0, q0
 ; CHECK-FIX-NEXT:vld1.64 {d16, d17}, [r2]
 ; CHECK-FIX-NEXT:cmp r0, #0
 ; CHECK-FIX-NEXT:beq .LBB13_2
@@ -380,6 +395,7 @@
 define arm_aapcs_vfpcc void @aese_set8_loop_via_ptr(i32 %0, i8* %1, <16 x i8> %2, <16 x i8>* %3) nounwind {
 ; CHECK-FIX-LABEL: aese_set8_loop_via_ptr:
 ; CHECK-FIX:   @ %bb.0:
+; CHECK-FIX-NEXT:vorr q0

[PATCH] D124613: In MSVC compatibility mode, friend function declarations behave as function declarations

2022-05-13 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource added a comment.

I realized that this current patch did in fact mimic MSVC behavior up to its 
mishandling on ADL. I understand that it is not in the spirit of clang's 
philosophy for MSVC compatibility to have that, but the fixed version I was 
about to propose would stray away from MSVC behavior, which doesn't really make 
sense either.
So instead I think the right approach should be to revert and see later whether 
we could put it back under the hood of another flag.
Is there currently a flag that could be used for "potentially C++ compliant 
breaking MSVC compatibility"? If there isn't, would it make sense to propose 
one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124613

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


[PATCH] D124730: [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

2022-05-13 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 429184.
kito-cheng marked 3 inline comments as done.
kito-cheng added a comment.

Changes:

- Address @khchen's comment.
- Use new hash scheme for cache the result of computeType.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124730

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -32,9 +32,6 @@
 class RVVEmitter {
 private:
   RecordKeeper &Records;
-  // Concat BasicType, LMUL and Proto as key
-  StringMap LegalTypes;
-  StringSet<> IllegalTypes;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -48,20 +45,11 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
-  std::string getSuffixStr(char Type, int Log2LMUL, StringRef Prototypes);
-
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
-  /// Compute output and input types by applying different config (basic type
-  /// and LMUL with type transformers). It also record result of type in legal
-  /// or illegal set to avoid compute the  same config again. The result maybe
-  /// have illegal RVVType.
-  Optional computeTypes(BasicType BT, int Log2LMUL, unsigned NF,
-  ArrayRef PrototypeSeq);
-  Optional computeType(BasicType BT, int Log2LMUL, StringRef Proto);
 
   /// Emit Acrh predecessor definitions and body, assume the element of Defs are
   /// sorted by extension.
@@ -73,14 +61,39 @@
   // non-empty string.
   bool emitMacroRestrictionStr(RISCVPredefinedMacroT PredefinedMacros,
raw_ostream &o);
-  // Slice Prototypes string into sub prototype string and process each sub
-  // prototype string individually in the Handler.
-  void parsePrototypes(StringRef Prototypes,
-   std::function Handler);
 };
 
 } // namespace
 
+static BasicType ParseBasicType(char c) {
+  switch (c) {
+  case 'c':
+return BasicType::Int8;
+break;
+  case 's':
+return BasicType::Int16;
+break;
+  case 'i':
+return BasicType::Int32;
+break;
+  case 'l':
+return BasicType::Int64;
+break;
+  case 'x':
+return BasicType::Float16;
+break;
+  case 'f':
+return BasicType::Float32;
+break;
+  case 'd':
+return BasicType::Float64;
+break;
+
+  default:
+return BasicType::Unknown;
+  }
+}
+
 void emitCodeGenSwitchBody(const RVVIntrinsic *RVVI, raw_ostream &OS) {
   if (!RVVI->getIRName().empty())
 OS << "  ID = Intrinsic::riscv_" + RVVI->getIRName() + ";\n";
@@ -202,24 +215,31 @@
   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
   // Print RVV boolean types.
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('c', Log2LMUL, "m");
+auto T = RVVType::computeType(BasicType::Int8, Log2LMUL,
+  PrototypeDescriptor::Mask);
 if (T.hasValue())
   printType(T.getValue());
   }
   // Print RVV int/float types.
   for (char I : StringRef("csil")) {
+BasicType BT = ParseBasicType(I);
 for (int Log2LMUL : Log2LMULs) {
-  auto T = computeType(I, Log2LMUL, "v");
+  auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
   if (T.hasValue()) {
 printType(T.getValue());
-auto UT = computeType(I, Log2LMUL, "Uv");
+auto UT = RVVType::computeType(
+BT, Log2LMUL,
+PrototypeDescriptor(BaseTypeModifier::Vector,
+VectorTypeModifier::NoModifier,
+TypeModifier::UnsignedInteger));
 printType(UT.getValue());
   }
 }
   }
   OS << "#if defined(__riscv_zvfh)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('x', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float16, Log2LMUL,
+  PrototypeDescriptor::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -227,7 +247,8 @@
 
   OS << "#if defined(__riscv_f)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('f', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float32, Log2LMUL,
+  PrototypeDescriptor::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -235,7 +256,8 @@
 
   OS << "#if defined(__riscv_d)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('d', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float64, Log2LMUL,
+  Pr

[PATCH] D124730: [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

2022-05-13 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:55
+// basic vector type, used to compute type info of arguments.
+enum class PrimitiveType : uint8_t {
+  Invalid,

khchen wrote:
> I think vector is not a primitive type in common sense, is it?
> why Widening2XVector, Widening4XVector, Widening8XVector and MaskVector is 
> not part of VectorTypeModifier?
> 
> Sorry, I'm confused and maybe forget something.
> I think vector is not a primitive type in common sense, is it?
It's called `primitive type transformer` on the comment[1], so that's why I use 
PrimitiveType here, but I admit that's kind of confusing, maybe 
BaseTypeModifier?

> Widening2XVector, Widening4XVector, Widening8XVector and MaskVector is not 
> part of VectorTypeModifier?

Good point, Moved to VectorTypeModifier!

[1] 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Support/RISCVVIntrinsicUtils.cpp#L366



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:85
+// TypeProfile is used to compute type info of arguments or return value.
+struct TypeProfile {
+  constexpr TypeProfile() = default;

khchen wrote:
> I think we need to update the comment in riscv_vector.td to sync the word 
> "TypeProfile", I feel the new word `TypeProfile` is similar to `modifier` or 
> `prototype`, is it?
> 
> ```
> The C/C++ prototype of the builtin is defined by the Prototype attribute.
> Prototype is a non-empty sequence of type transformers, the first of which
> is the return type of the builtin and the rest are the parameters of the
> builtin, in order. For instance if Prototype is "wvv" and TypeRange is "si"
> a first builtin will have type
> ```
> 
> we call it  `modifier` or `prototype` is because those words are coming from 
> clang intrinsic definition and other target.
> 
> https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/Builtins.def#L52
> https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/arm_sve.td#L58
> 
> personally I think consistent naming maybe better than creating a new word, 
> what do you think?
> 
> 
> BTW, I think having this new class is really good idea for refactoring!
Renamed to `PrototypeDescriptor`, that should be better I guess :)



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:90
+  : PT(static_cast(PT)), TM(static_cast(TM)) {}
+  constexpr TypeProfile(uint8_t PT, uint8_t VTM, uint8_t TM)
+  : PT(PT), VTM(VTM), TM(TM) {}

khchen wrote:
> If we allow parameter could `uint8_t`, why other constructors not follow the 
> same rule?
Keep only two version of constructor, one for all uint8_t and one for all enum.

All enum one used for checking type safe as possilbe.
And uint8_t version used for low-level construct (used in 
https://reviews.llvm.org/D111617)



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:97
+
+  std::string IndexStr() const {
+return std::to_string(PT) + "_" + std::to_string(VTM) + "_" +

khchen wrote:
> What's purpose of this function, translate TypeProfile to the Proto string?
Used for caching the `RVVType`, but I realized we could use integer(`uint64_t`) 
as hash value, use new hash scheme in new version.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124730

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


[PATCH] D125532: [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added a reviewer: martong.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In some rare cases the type of an SVal might be interesting.
This introspection function exposes this information in tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125532

Files:
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/test/Analysis/expr-inspection.c


Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -6,12 +6,16 @@
 
 void clang_analyzer_dump(int x);
 void clang_analyzer_dump_pointer(int *p);
+void clang_analyzer_dumpSvalType(int x);
+void clang_analyzer_dumpSvalType_pointer(int *p);
 void clang_analyzer_printState(void);
 void clang_analyzer_numTimesReached(void);
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
   clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dumpSvalType(x); // expected-warning {{int}}
+
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
@@ -53,4 +57,5 @@
 void test_field_dumps(struct S s, struct S *p) {
   clang_analyzer_dump_pointer(&s.x); // expected-warning{{&s.x}}
   clang_analyzer_dump_pointer(&p->x); // 
expected-warning{{&SymRegion{reg_$1}.x}}
+  clang_analyzer_dumpSvalType_pointer(&s.x); // expected-warning {{int *}}
 }
Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@
   void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
   void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
+  void analyzerDumpSValType(const CallExpr *CE, CheckerContext &C) const;
   void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
   void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
   void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
@@ -98,6 +99,8 @@
 &ExprInspectionChecker::analyzerDumpExtent)
   .Case("clang_analyzer_dumpElementCount",
 &ExprInspectionChecker::analyzerDumpElementCount)
+  .StartsWith("clang_analyzer_dumpSvalType",
+  &ExprInspectionChecker::analyzerDumpSValType)
   .StartsWith("clang_analyzer_dump",
   &ExprInspectionChecker::analyzerDump)
   .Case("clang_analyzer_getExtent",
@@ -255,6 +258,16 @@
   reportBug(Ex.Visit(V), C);
 }
 
+void ExprInspectionChecker::analyzerDumpSValType(const CallExpr *CE,
+ CheckerContext &C) const {
+  const Expr *Arg = getArgExpr(CE, C);
+  if (!Arg)
+return;
+
+  QualType Ty = C.getSVal(Arg).getType(C.getASTContext());
+  reportBug(Ty.getAsString(), C);
+}
+
 void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
  CheckerContext &C) const {
   const Expr *Arg = getArgExpr(CE, C);


Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -6,12 +6,16 @@
 
 void clang_analyzer_dump(int x);
 void clang_analyzer_dump_pointer(int *p);
+void clang_analyzer_dumpSvalType(int x);
+void clang_analyzer_dumpSvalType_pointer(int *p);
 void clang_analyzer_printState(void);
 void clang_analyzer_numTimesReached(void);
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
   clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dumpSvalType(x); // expected-warning {{int}}
+
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
@@ -53,4 +57,5 @@
 void test_field_dumps(struct S s, struct S *p) {
   clang_analyzer_dump_pointer(&s.x); // expected-warning{{&s.x}}
   clang_analyzer_dump_pointer(&p->x); // expected-warning{{&SymRegion{reg_$1}.x}}
+  clang_analyzer_dumpSvalType_pointer(&s.x); // expected-warning {{int *}}
 }
Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@
   void analyzerNumTimesReached

[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:107
+return makeNonLoc(X.castAs().getSymbol(), UO_Not,
+  X.getType(Context));
   default:

martong wrote:
> steakhal wrote:
> > I'm not sure if we should rely on `SVal::getType()`. I think the calling 
> > context should pass the type along here.
> Good point. One example where the type of the SVal is different than the type 
> of the UnaryExpr is here:
> ```
> void test_x(int x, long y) {
>   x = y;  // $x has `long` type
>   -x; // the UnaryExpr `-x` has `int` type
> }
> ```
> Note that if we use `support-symbolic-integer-casts=true` then there is no 
> such type mismatch because there is in implicit cast modeled at `x = y`, thus 
> $x type is correctly `int`.
> 
> Anyway, I am going to update evalMinus and evalComplement to take an 
> additional QualType parameter.
Please add this test with both scenarios with `support-symbolic-integer-casts`. 
D125532 will help in demonstrating this.



Comment at: clang/lib/StaticAnalyzer/Core/SymbolManager.cpp:73-76
+void UnarySymExpr::dumpToStream(raw_ostream &os) const {
+  os << UnaryOperator::getOpcodeStr(Op);
+  Operand->dumpToStream(os);
+}

martong wrote:
> Would be better to add parenthesis around for compound expressions. So 
> expressions like -x where x = a + b should look like `-($a + $b)` instead of 
> the wrong format `-$a + $b`. I am going to update.
Good point!



Comment at: clang/test/Analysis/unary-sym-expr.c:35
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}

Does it work if you swap x and y?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D125383: [ASTMatchers][clang-tidy][NFC] Hoist 'forEachTemplateArgument' matcher into the core library

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D125383#3510906 , @whisperity 
wrote:

> In D125383#3509084 , @aaron.ballman 
> wrote:
>
>> Then I think the only thing missing here are updates to 
>> https://github.com/llvm/llvm-project/blob/main/clang/lib/ASTMatchers/Dynamic/Registry.cpp.
>
> Could you please check if I did it the right way? I did not know about this 
> file, and I am still not exactly sure about its purpose.

Yup, you did it correct! This is the magic that allows clang-query to work -- 
it sets up the dynamic mapping of C++ matchers, so if you forget to add 
something to that list, it'll be available to folks in C++ but not in 
clang-query.


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

https://reviews.llvm.org/D125383

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


[clang-tools-extra] 9add949 - [ASTMatchers][clang-tidy][NFC] Hoist `forEachTemplateArgument` matcher into the core library

2022-05-13 Thread via cfe-commits

Author: Whisperity
Date: 2022-05-13T12:55:48+02:00
New Revision: 9add949557d2cf603b8f541f0dbb83a8fa035d17

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

LOG: [ASTMatchers][clang-tidy][NFC] Hoist `forEachTemplateArgument` matcher 
into the core library

Fixes the `FIXME:` related to adding `forEachTemplateArgument` to the
core AST Matchers library.

Reviewed By: aaron.ballman

Differential Revision: http://reviews.llvm.org/D125383

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
clang/docs/LibASTMatchersReference.html
clang/docs/ReleaseNotes.rst
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
index 9265504a7651..1ee757296d93 100644
--- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
@@ -18,26 +18,6 @@ namespace tidy {
 namespace misc {
 
 namespace {
-// FIXME: Move ASTMatcher library.
-AST_POLYMORPHIC_MATCHER_P(
-forEachTemplateArgument,
-AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
-TemplateSpecializationType, FunctionDecl),
-clang::ast_matchers::internal::Matcher, InnerMatcher) {
-  ArrayRef TemplateArgs =
-  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
-  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
-  bool Matched = false;
-  for (const auto &Arg : TemplateArgs) {
-clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
-if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
-  Matched = true;
-  Result.addMatch(ArgBuilder);
-}
-  }
-  *Builder = std::move(Result);
-  return Matched;
-}
 
 AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl,
   clang::ast_matchers::internal::Matcher, DeclMatcher) {

diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 55c4da639a81..b6dcf26e 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -7391,6 +7391,32 @@ AST Traversal Matchers
 
 
 
+MatcherClassTemplateSpecializationDecl>forEachTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
+Matches 
classTemplateSpecialization, templateSpecializationType and functionDecl nodes 
where the template argument matches the inner matcher.
+This matcher may produce multiple matches.
+
+Given
+  template 
+  struct Matrix {};
+
+  constexpr unsigned R = 2;
+  Matrix M;
+
+  template 
+  void f(T&& t, U&& u) {}
+
+  bool B = false;
+  f(R, B);
+
+templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+  matches twice, with expr() matching 'R * 2' and 'R * 4'
+
+functionDecl(forEachTemplateArgument(refersToType(builtinType(
+  matches the specialization f twice, for 'unsigned'
+  and 'bool'
+
+
+
 MatcherClassTemplateSpecializationDecl>hasAnyTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
 Matches 
classTemplateSpecializations, templateSpecializationType and
 functionDecl that have at least one TemplateArgument matching the given
@@ -8181,6 +8207,32 @@ AST Traversal Matchers
 
 
 
+MatcherFunctionDecl>forEachTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
+Matches 
classTemplateSpecialization, templateSpecializationType and functionDecl nodes 
where the template argument matches the inner matcher.
+This matcher may produce multiple matches.
+
+Given
+  template 
+  struct Matrix {};
+
+  constexpr unsigned R = 2;
+  Matrix M;
+
+  template 
+  void f(T&& t, U&& u) {}
+
+  bool B = false;
+  f(R, B);
+
+templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+  matches twice, with expr() matching 'R * 2' and 'R * 4'
+
+functionDecl(forEachTemplateArgument(refersToType(builtinType(
+  matches the specialization f twice, for 'unsigned'
+  and 'bool'
+
+
+
 Matcher

[PATCH] D125383: [ASTMatchers][clang-tidy][NFC] Hoist 'forEachTemplateArgument' matcher into the core library

2022-05-13 Thread Whisperity 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 rG9add949557d2: [ASTMatchers][clang-tidy][NFC] Hoist 
`forEachTemplateArgument` matcher into the… (authored by whisperity).

Changed prior to commit:
  https://reviews.llvm.org/D125383?vs=429161&id=429192#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125383

Files:
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -4971,6 +4971,62 @@
 std::make_unique>("if", 6)));
 }
 
+TEST(ForEachTemplateArgument, OnFunctionDecl) {
+  const std::string Code = R"(
+template  void f(T, U) {}
+void test() {
+  int I = 1;
+  bool B = false;
+  f(I, B);
+})";
+  EXPECT_TRUE(matches(
+  Code, functionDecl(forEachTemplateArgument(refersToType(builtinType(,
+  langCxx11OrLater()));
+  auto matcher =
+  functionDecl(forEachTemplateArgument(
+   templateArgument(refersToType(builtinType().bind("BT")))
+   .bind("TA")))
+  .bind("FN");
+
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("FN", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TA", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("BT", 2)));
+}
+
+TEST(ForEachTemplateArgument, OnClassTemplateSpecialization) {
+  const std::string Code = R"(
+template 
+struct Matrix {};
+
+static constexpr unsigned R = 2;
+
+Matrix M;
+)";
+  EXPECT_TRUE(matches(
+  Code, templateSpecializationType(forEachTemplateArgument(isExpr(expr(,
+  langCxx11OrLater()));
+  auto matcher = templateSpecializationType(
+ forEachTemplateArgument(
+ templateArgument(isExpr(expr().bind("E"))).bind("TA")))
+ .bind("TST");
+
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TST",
+  2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher,
+  std::make_unique>("TA", 2)));
+  EXPECT_TRUE(matchAndVerifyResultTrue(
+  Code, matcher, std::make_unique>("E", 2)));
+}
+
 TEST(Has, DoesNotDeleteBindings) {
   EXPECT_TRUE(matchAndVerifyResultTrue(
 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -250,6 +250,7 @@
   REGISTER_MATCHER(forEachLambdaCapture);
   REGISTER_MATCHER(forEachOverridden);
   REGISTER_MATCHER(forEachSwitchCase);
+  REGISTER_MATCHER(forEachTemplateArgument);
   REGISTER_MATCHER(forField);
   REGISTER_MATCHER(forFunction);
   REGISTER_MATCHER(forStmt);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -5011,6 +5011,49 @@
   return Node.getNumParams() == N;
 }
 
+/// Matches classTemplateSpecialization, templateSpecializationType and
+/// functionDecl nodes where the template argument matches the inner matcher.
+/// This matcher may produce multiple matches.
+///
+/// Given
+/// \code
+///   template 
+///   struct Matrix {};
+///
+///   constexpr unsigned R = 2;
+///   Matrix M;
+///
+///   template 
+///   void f(T&& t, U&& u) {}
+///
+///   bool B = false;
+///   f(R, B);
+/// \endcode
+/// templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+///   matches twice, with expr() matching 'R * 2' and 'R * 4'
+/// functionDecl(forEachTemplateArgument(refersToType(builtinType(
+///   matches the specialization f twice, for 'unsigned'
+///   and 'bool'
+AST_POLYMORPHIC_MATCHER_P(
+forEachTemplateArgument,
+AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
+TemplateSpecializationType, FunctionDecl),
+clang::ast_matchers::internal::Matcher, InnerMatcher) {
+  ArrayRef TemplateArgs =
+  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
+  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
+  bool Matched = false;
+  for (const auto &Arg : TemplateArgs) {
+clang::as

[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3510165 , @dexonsmith 
wrote:

> For additional context to my questions above, even though open source clang 
> hasn't been using `-Wstrict-prototypes`, Xcode has had it on-by-default in 
> new projects since sometime in 2017, with project modernizations to turn it 
> on for old projects.

Thanks, that's very good to know! And also, thank you for raising the questions 
here, I appreciate the discussion.

> Warning on block and function definitions such as `^(){}` and `void f1() {}`, 
> which are pedantically lacking a prototype but the compiler knows there are 
> exactly zero parameters, would be super noisy for users.
>
> Unless I read the RFC too quickly, it doesn't look like it's adding any 
> value, since these aren't going to change meaning. Is it possible to revert 
> this part of the change?

`-Wstrict-prototypes` is now a pedantic deprecation warning that fires any time 
you form a function type which has no prototype, which was discussed in the RFC 
(https://discourse.llvm.org/t/rfc-enabling-wstrict-prototypes-by-default-in-c/60521/38?u=aaronballman):

  Change -Wstrict-prototypes to diagnose functions without a prototype that 
don’t change behavior in C2x, it remains off-by-default but is automatically 
enabled by -pedantic as it’s still warning the user about a deprecation.

However, I think the blocks behavior is a bug based on this: 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L728 
and I'd be more than happy to fix that, as I'm not checking that condition 
here: 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L5579
 which seems like a pretty obvious thing to be checking for before warning 
about not having a strict prototype.

But I'm pretty insistent on warning about the other case as it does use 
functions without a prototype and we need *some* blanket warning for use of a 
deprecated feature for folks who want to be strictly conforming. It sounds like 
Apple may want to no longer enable `-Wstrict-prototypes` by default as it's 
shifted to be a more pedantic warning than it was before -- would that be a 
viable option for you (can you use project modernizations to turn it back off 
for old projects)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125468: [clangd] Include Cleaner: ignore headers with IWYU export pragmas

2022-05-13 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Headers.cpp:134
+  return false;
+return inMainFile() ? handleCommentInMainFile(PP, Range)
+: handleCommentInHeaderFile(PP, Range);

the split seems to be increasing code duplication (we've already copied a bug 
with it 😓), what about:
```
bool Err = false;
llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
if (!Err || (!Text.consume_front(IWYUPragmaKeep) &&
!Text.consume_front(IWYUPragmaExport)))
  return false;
if(inMainFile()) {
  unsigned Offset = SM.getFileOffset(Range.getBegin());
  LastPragmaKeepInMainFileLine =
  SM.getLineNumber(SM.getMainFileID(), Offset) - 1;
} else {
  Out->HasIWYUPragmas.insert(
*Out->getID(SM.getFileEntryForID(SM.getFileID(Range.getBegin();
}
return false;
```



Comment at: clang-tools-extra/clangd/Headers.cpp:154
+  bool handleCommentInMainFile(Preprocessor &PP, SourceRange Range) {
+assert(inMainFile());
+assert(!Range.getBegin().isMacroID());

i don't think the asserts carry their weight (here and also in the headerfile 
comment handler). we're not really performing anything dubious if the asserts 
don't hold. getCharacterData will return non-sense (but valid) buffers in case 
of a macroid, and we're already reading data whether we're in the main file or 
not. moreover these are private and controlled at the entry by the public 
interface (`HandleComment`).



Comment at: clang-tools-extra/clangd/Headers.cpp:172
+llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
+if (Err && !Text.consume_front(IWYUPragmaExport) &&
+!Text.consume_front(IWYUPragmaBeginExports))

shouldn't this be `if (Err || (!Text.consume ... && !Text.consume...)) return 
false;` ? same above for the main file comment handling



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:271
   }
   // Headers without include guards have side effects and are not
   // self-contained, skip them.

can you also move this comment below, next to the `isFileMultipleHeaderGuarded` 
check?



Comment at: clang-tools-extra/clangd/unittests/HeadersTests.cpp:427
+)cpp";
+  FS.Files[testPath("export.h")] = R"cpp(
+#pragma once

no need for `testPath`s here and below.



Comment at: clang-tools-extra/clangd/unittests/HeadersTests.cpp:438
+  FS.Files[testPath("none.h")] = R"cpp(
+#pragma once
+)cpp";

this is passing not because you don't have a IWYU pragma comment here, but 
because you don't have any comments at all. can you try inserting an arbitrary 
comment into the file?



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:603
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  // FIXME: This is not correct: foo.h and bar.h are unused but are not
+  // diagnosed as such because we ignore headers with IWYU export pragmas for

do you mean just `foo.h is unused` why are we talking about `bar.h` also being 
unused here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125468

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


[clang] 99d3582 - Comment parsing: Specify argument numbers for some block commands

2022-05-13 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2022-05-13T13:48:46+02:00
New Revision: 99d35826a043916b259a0e440a2aa5cabbad2773

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

LOG: Comment parsing: Specify argument numbers for some block commands

The command traits have a member NumArgs for which all the parsing
infrastructure is in place, but no command was setting it to a value
other than 0. By doing so we get warnings when passing an empty
paragraph to \retval (the first argument is the return value, then comes
the description). We also take \xrefitem along for the ride, although as
the documentation states it's unlikely to be used directly.

Reviewed By: gribozavr2

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

Added: 


Modified: 
clang/include/clang/AST/CommentCommands.td
clang/test/AST/ast-dump-comment.cpp
clang/test/Sema/warn-documentation.cpp

Removed: 




diff  --git a/clang/include/clang/AST/CommentCommands.td 
b/clang/include/clang/AST/CommentCommands.td
index 7e962a4b4171b..d357ec1cf8b99 100644
--- a/clang/include/clang/AST/CommentCommands.td
+++ b/clang/include/clang/AST/CommentCommands.td
@@ -154,7 +154,7 @@ def Post   : BlockCommand<"post">;
 def Pre: BlockCommand<"pre">;
 def Remark : BlockCommand<"remark">;
 def Remarks: BlockCommand<"remarks">;
-def Retval : BlockCommand<"retval">;
+def Retval : BlockCommand<"retval"> { let NumArgs = 1; }
 def Sa : BlockCommand<"sa">;
 def See: BlockCommand<"see">;
 def Since  : BlockCommand<"since">;
@@ -162,7 +162,7 @@ def Test   : BlockCommand<"test">;
 def Todo   : BlockCommand<"todo">;
 def Version: BlockCommand<"version">;
 def Warning: BlockCommand<"warning">;
-def XRefItem   : BlockCommand<"xrefitem">;
+def XRefItem   : BlockCommand<"xrefitem"> { let NumArgs = 3; }
 // HeaderDoc commands
 def Abstract  : BlockCommand<"abstract"> { let IsBriefCommand = 1; }
 def ClassDesign   : RecordLikeDetailCommand<"classdesign">;

diff  --git a/clang/test/AST/ast-dump-comment.cpp 
b/clang/test/AST/ast-dump-comment.cpp
index 11c96024546e0..1936c732cb989 100644
--- a/clang/test/AST/ast-dump-comment.cpp
+++ b/clang/test/AST/ast-dump-comment.cpp
@@ -32,6 +32,13 @@ int Test_BlockCommandComment;
 // CHECK-NEXT: ParagraphComment
 // CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
 
+/// \retval 42 Aaa
+int Test_BlockCommandComment_WithArgs();
+// CHECK:  FunctionDecl{{.*}}Test_BlockCommandComment_WithArgs
+// CHECK:BlockCommandComment{{.*}} Name="retval" Arg[0]="42"
+// CHECK-NEXT: ParagraphComment
+// CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
+
 /// \param Aaa xxx
 /// \param [in,out] Bbb yyy
 void Test_ParamCommandComment(int Aaa, int Bbb);

diff  --git a/clang/test/Sema/warn-documentation.cpp 
b/clang/test/Sema/warn-documentation.cpp
index 353c94a47eb6f..570b5baf54029 100644
--- a/clang/test/Sema/warn-documentation.cpp
+++ b/clang/test/Sema/warn-documentation.cpp
@@ -189,6 +189,14 @@ int test_multiple_returns3(int);
 int test_multiple_returns4(int);
 
 
+/// expected-warning@+1 {{empty paragraph passed to '\retval' command}}
+/// \retval 0
+int test_retval_no_paragraph();
+
+/// \retval 0 Everything is fine.
+int test_retval_fine();
+
+
 // expected-warning@+1 {{'\param' command used in a comment that is not 
attached to a function declaration}}
 /// \param a Blah blah.
 int test_param1_backslash;



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


[clang] d3a4033 - Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-13 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2022-05-13T13:48:46+02:00
New Revision: d3a4033d6ee1d017e216ff7caeeeb5ca2e18a783

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

LOG: Comment parsing: Allow inline commands to have 0 or more than 1 argument

That's required to support `\n`, but can also be used for other commands.
We already had the infrastructure in place to parse a varying number of
arguments, we simply needed to generalize it so that it would work not
only for block commands.

This should fix #55319.

Reviewed By: gribozavr2

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

Added: 


Modified: 
clang/include/clang/AST/Comment.h
clang/include/clang/AST/CommentCommands.td
clang/include/clang/AST/CommentParser.h
clang/include/clang/AST/CommentSema.h
clang/include/clang/Basic/DiagnosticCommentKinds.td
clang/lib/AST/CommentParser.cpp
clang/lib/AST/CommentSema.cpp
clang/test/AST/ast-dump-comment.cpp
clang/test/Headers/x86-intrinsics-headers-clean.cpp
clang/test/Sema/warn-documentation.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Comment.h 
b/clang/include/clang/AST/Comment.h
index 5ecc35791b7b0..0b68c11316649 100644
--- a/clang/include/clang/AST/Comment.h
+++ b/clang/include/clang/AST/Comment.h
@@ -194,6 +194,11 @@ class Comment {
 #include "clang/AST/CommentNodes.inc"
   };
 
+  struct Argument {
+SourceRange Range;
+StringRef Text;
+  };
+
   Comment(CommentKind K,
   SourceLocation LocBegin,
   SourceLocation LocEnd) :
@@ -296,13 +301,6 @@ class TextComment : public InlineContentComment {
 /// A command with word-like arguments that is considered inline content.
 class InlineCommandComment : public InlineContentComment {
 public:
-  struct Argument {
-SourceRange Range;
-StringRef Text;
-
-Argument(SourceRange Range, StringRef Text) : Range(Range), Text(Text) { }
-  };
-
   /// The most appropriate rendering mode for this command, chosen on command
   /// semantics in Doxygen.
   enum RenderKind {
@@ -588,15 +586,6 @@ class ParagraphComment : public BlockContentComment {
 /// arguments depends on command name) and a paragraph as an argument
 /// (e. g., \\brief).
 class BlockCommandComment : public BlockContentComment {
-public:
-  struct Argument {
-SourceRange Range;
-StringRef Text;
-
-Argument() { }
-Argument(SourceRange Range, StringRef Text) : Range(Range), Text(Text) { }
-  };
-
 protected:
   /// Word-like arguments.
   ArrayRef Args;

diff  --git a/clang/include/clang/AST/CommentCommands.td 
b/clang/include/clang/AST/CommentCommands.td
index d357ec1cf8b99..a3b9eb313fcf5 100644
--- a/clang/include/clang/AST/CommentCommands.td
+++ b/clang/include/clang/AST/CommentCommands.td
@@ -31,6 +31,7 @@ class Command {
 }
 
 class InlineCommand : Command {
+  let NumArgs = 1;
   let IsInlineCommand = 1;
 }
 
@@ -86,6 +87,7 @@ def C  : InlineCommand<"c">;
 def P  : InlineCommand<"p">;
 def A  : InlineCommand<"a">;
 def E  : InlineCommand<"e">;
+def N  : InlineCommand<"n"> { let NumArgs = 0; }
 def Em : InlineCommand<"em">;
 def Emoji  : InlineCommand<"emoji">;
 

diff  --git a/clang/include/clang/AST/CommentParser.h 
b/clang/include/clang/AST/CommentParser.h
index 1a0cfb06e52b7..e11e818b1af0a 100644
--- a/clang/include/clang/AST/CommentParser.h
+++ b/clang/include/clang/AST/CommentParser.h
@@ -97,9 +97,8 @@ class Parser {
   void parseTParamCommandArgs(TParamCommandComment *TPC,
   TextTokenRetokenizer &Retokenizer);
 
-  void parseBlockCommandArgs(BlockCommandComment *BC,
- TextTokenRetokenizer &Retokenizer,
- unsigned NumArgs);
+  ArrayRef
+  parseCommandArgs(TextTokenRetokenizer &Retokenizer, unsigned NumArgs);
 
   BlockCommandComment *parseBlockCommand();
   InlineCommandComment *parseInlineCommand();

diff  --git a/clang/include/clang/AST/CommentSema.h 
b/clang/include/clang/AST/CommentSema.h
index 015ce8f8652ac..5e30ff8adb915 100644
--- a/clang/include/clang/AST/CommentSema.h
+++ b/clang/include/clang/AST/CommentSema.h
@@ -128,16 +128,10 @@ class Sema {
   void actOnTParamCommandFinish(TParamCommandComment *Command,
 ParagraphComment *Paragraph);
 
-  InlineCommandComment *actOnInlineCommand(SourceLocation CommandLocBegin,
-   SourceLocation CommandLocEnd,
-   unsigned CommandID);
-
   InlineCommandComment *actOnInlineCommand(SourceLocation CommandLocBegin,
SourceLocation CommandLocEnd,
unsigned CommandID,
-   SourceLocation ArgLocB

[clang] d2396d8 - Comment parsing: Treat properties as zero-argument inline commands

2022-05-13 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2022-05-13T13:48:46+02:00
New Revision: d2396d896ee12ad20bc740174edfce2120d742b2

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

LOG: Comment parsing: Treat properties as zero-argument inline commands

That is more accurate, and using a separate class in TableGen seems
appropriate since these are not parts of the text but properties of the
declaration itself.

Reviewed By: gribozavr2

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

Added: 


Modified: 
clang/include/clang/AST/CommentCommands.td

Removed: 




diff  --git a/clang/include/clang/AST/CommentCommands.td 
b/clang/include/clang/AST/CommentCommands.td
index a3b9eb313fcf..e839031752cd 100644
--- a/clang/include/clang/AST/CommentCommands.td
+++ b/clang/include/clang/AST/CommentCommands.td
@@ -63,6 +63,11 @@ class VerbatimLineCommand : Command {
   let IsVerbatimLineCommand = 1;
 }
 
+class PropertyCommand : Command {
+  let NumArgs = 0;
+  let IsInlineCommand = 1;
+}
+
 class DeclarationVerbatimLineCommand :
   VerbatimLineCommand {
   let IsDeclarationCommand = 1;
@@ -275,31 +280,6 @@ def Until: VerbatimLineCommand<"until">;
 
 def NoOp : VerbatimLineCommand<"noop">;
 
-// These have actually no arguments, but we can treat them as line commands.
-def CallGraph   : VerbatimLineCommand<"callgraph">;
-def HideCallGraph   : VerbatimLineCommand<"hidecallgraph">;
-def CallerGraph : VerbatimLineCommand<"callergraph">;
-def HideCallerGraph : VerbatimLineCommand<"hidecallergraph">;
-def ShowInitializer : VerbatimLineCommand<"showinitializer">;
-def HideInitializer : VerbatimLineCommand<"hideinitializer">;
-def ShowRefBy   : VerbatimLineCommand<"showrefby">;
-def HideRefBy   : VerbatimLineCommand<"hiderefby">;
-def ShowRefs: VerbatimLineCommand<"showrefs">;
-def HideRefs: VerbatimLineCommand<"hiderefs">;
-
-// These also have no argument.
-def Private   : VerbatimLineCommand<"private">;
-def Protected : VerbatimLineCommand<"protected">;
-def Public: VerbatimLineCommand<"public">;
-def Pure  : VerbatimLineCommand<"pure">;
-def Static: VerbatimLineCommand<"static">;
-
-// These also have no argument.
-def NoSubgrouping: VerbatimLineCommand<"nosubgrouping">;
-def PrivateSection   : VerbatimLineCommand<"privatesection">;
-def ProtectedSection : VerbatimLineCommand<"protectedsection">;
-def PublicSection: VerbatimLineCommand<"publicsection">;
-
 // We might also build proper support for if/ifnot/else/elseif/endif.
 def If : VerbatimLineCommand<"if">;
 def IfNot  : VerbatimLineCommand<"ifnot">;
@@ -311,6 +291,32 @@ def Endif  : VerbatimLineCommand<"endif">;
 def Cond: VerbatimLineCommand<"cond">;
 def EndCond : VerbatimLineCommand<"endcond">;
 
+//===--===//
+// PropertyCommand
+//===--===//
+
+def CallGraph   : PropertyCommand<"callgraph">;
+def HideCallGraph   : PropertyCommand<"hidecallgraph">;
+def CallerGraph : PropertyCommand<"callergraph">;
+def HideCallerGraph : PropertyCommand<"hidecallergraph">;
+def ShowInitializer : PropertyCommand<"showinitializer">;
+def HideInitializer : PropertyCommand<"hideinitializer">;
+def ShowRefBy   : PropertyCommand<"showrefby">;
+def HideRefBy   : PropertyCommand<"hiderefby">;
+def ShowRefs: PropertyCommand<"showrefs">;
+def HideRefs: PropertyCommand<"hiderefs">;
+
+def Private   : PropertyCommand<"private">;
+def Protected : PropertyCommand<"protected">;
+def Public: PropertyCommand<"public">;
+def Pure  : PropertyCommand<"pure">;
+def Static: PropertyCommand<"static">;
+
+def NoSubgrouping: PropertyCommand<"nosubgrouping">;
+def PrivateSection   : PropertyCommand<"privatesection">;
+def ProtectedSection : PropertyCommand<"protectedsection">;
+def PublicSection: PropertyCommand<"publicsection">;
+
 
//===--===//
 // DeclarationVerbatimLineCommand
 
//===--===//



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


[PATCH] D125422: Comment parsing: Specify argument numbers for some block commands

2022-05-13 Thread Aaron Puchert 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 rG99d35826a043: Comment parsing: Specify argument numbers for 
some block commands (authored by aaronpuchert).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125422

Files:
  clang/include/clang/AST/CommentCommands.td
  clang/test/AST/ast-dump-comment.cpp
  clang/test/Sema/warn-documentation.cpp


Index: clang/test/Sema/warn-documentation.cpp
===
--- clang/test/Sema/warn-documentation.cpp
+++ clang/test/Sema/warn-documentation.cpp
@@ -189,6 +189,14 @@
 int test_multiple_returns4(int);
 
 
+/// expected-warning@+1 {{empty paragraph passed to '\retval' command}}
+/// \retval 0
+int test_retval_no_paragraph();
+
+/// \retval 0 Everything is fine.
+int test_retval_fine();
+
+
 // expected-warning@+1 {{'\param' command used in a comment that is not 
attached to a function declaration}}
 /// \param a Blah blah.
 int test_param1_backslash;
Index: clang/test/AST/ast-dump-comment.cpp
===
--- clang/test/AST/ast-dump-comment.cpp
+++ clang/test/AST/ast-dump-comment.cpp
@@ -32,6 +32,13 @@
 // CHECK-NEXT: ParagraphComment
 // CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
 
+/// \retval 42 Aaa
+int Test_BlockCommandComment_WithArgs();
+// CHECK:  FunctionDecl{{.*}}Test_BlockCommandComment_WithArgs
+// CHECK:BlockCommandComment{{.*}} Name="retval" Arg[0]="42"
+// CHECK-NEXT: ParagraphComment
+// CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
+
 /// \param Aaa xxx
 /// \param [in,out] Bbb yyy
 void Test_ParamCommandComment(int Aaa, int Bbb);
Index: clang/include/clang/AST/CommentCommands.td
===
--- clang/include/clang/AST/CommentCommands.td
+++ clang/include/clang/AST/CommentCommands.td
@@ -154,7 +154,7 @@
 def Pre: BlockCommand<"pre">;
 def Remark : BlockCommand<"remark">;
 def Remarks: BlockCommand<"remarks">;
-def Retval : BlockCommand<"retval">;
+def Retval : BlockCommand<"retval"> { let NumArgs = 1; }
 def Sa : BlockCommand<"sa">;
 def See: BlockCommand<"see">;
 def Since  : BlockCommand<"since">;
@@ -162,7 +162,7 @@
 def Todo   : BlockCommand<"todo">;
 def Version: BlockCommand<"version">;
 def Warning: BlockCommand<"warning">;
-def XRefItem   : BlockCommand<"xrefitem">;
+def XRefItem   : BlockCommand<"xrefitem"> { let NumArgs = 3; }
 // HeaderDoc commands
 def Abstract  : BlockCommand<"abstract"> { let IsBriefCommand = 1; }
 def ClassDesign   : RecordLikeDetailCommand<"classdesign">;


Index: clang/test/Sema/warn-documentation.cpp
===
--- clang/test/Sema/warn-documentation.cpp
+++ clang/test/Sema/warn-documentation.cpp
@@ -189,6 +189,14 @@
 int test_multiple_returns4(int);
 
 
+/// expected-warning@+1 {{empty paragraph passed to '\retval' command}}
+/// \retval 0
+int test_retval_no_paragraph();
+
+/// \retval 0 Everything is fine.
+int test_retval_fine();
+
+
 // expected-warning@+1 {{'\param' command used in a comment that is not attached to a function declaration}}
 /// \param a Blah blah.
 int test_param1_backslash;
Index: clang/test/AST/ast-dump-comment.cpp
===
--- clang/test/AST/ast-dump-comment.cpp
+++ clang/test/AST/ast-dump-comment.cpp
@@ -32,6 +32,13 @@
 // CHECK-NEXT: ParagraphComment
 // CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
 
+/// \retval 42 Aaa
+int Test_BlockCommandComment_WithArgs();
+// CHECK:  FunctionDecl{{.*}}Test_BlockCommandComment_WithArgs
+// CHECK:BlockCommandComment{{.*}} Name="retval" Arg[0]="42"
+// CHECK-NEXT: ParagraphComment
+// CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
+
 /// \param Aaa xxx
 /// \param [in,out] Bbb yyy
 void Test_ParamCommandComment(int Aaa, int Bbb);
Index: clang/include/clang/AST/CommentCommands.td
===
--- clang/include/clang/AST/CommentCommands.td
+++ clang/include/clang/AST/CommentCommands.td
@@ -154,7 +154,7 @@
 def Pre: BlockCommand<"pre">;
 def Remark : BlockCommand<"remark">;
 def Remarks: BlockCommand<"remarks">;
-def Retval : BlockCommand<"retval">;
+def Retval : BlockCommand<"retval"> { let NumArgs = 1; }
 def Sa : BlockCommand<"sa">;
 def See: BlockCommand<"see">;
 def Since  : BlockCommand<"since">;
@@ -162,7 +162,7 @@
 def Todo   : BlockCommand<"todo">;
 def Version: BlockCommand<"version">;
 def Warning: BlockCommand<"warning">;
-def XRefItem   : BlockCommand<"xrefitem">;
+def XRefItem   : BlockCommand<"xrefitem"> { let NumArgs = 3; }
 // HeaderDoc commands
 def Abstract  

[PATCH] D125429: Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-13 Thread Aaron Puchert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd3a4033d6ee1: Comment parsing: Allow inline commands to have 
0 or more than 1 argument (authored by aaronpuchert).

Changed prior to commit:
  https://reviews.llvm.org/D125429?vs=428968&id=429203#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125429

Files:
  clang/include/clang/AST/Comment.h
  clang/include/clang/AST/CommentCommands.td
  clang/include/clang/AST/CommentParser.h
  clang/include/clang/AST/CommentSema.h
  clang/include/clang/Basic/DiagnosticCommentKinds.td
  clang/lib/AST/CommentParser.cpp
  clang/lib/AST/CommentSema.cpp
  clang/test/AST/ast-dump-comment.cpp
  clang/test/Headers/x86-intrinsics-headers-clean.cpp
  clang/test/Sema/warn-documentation.cpp

Index: clang/test/Sema/warn-documentation.cpp
===
--- clang/test/Sema/warn-documentation.cpp
+++ clang/test/Sema/warn-documentation.cpp
@@ -1116,49 +1116,49 @@
 void test_attach38::test_attach39(int, B);
 
 // The inline comments expect a string after the command.
-// expected-warning@+1 {{'\a' command does not have a valid word argument}}
+// expected-warning@+1 {{'\a' command has no word arguments, expected 1}}
 /// \a
 int test_inline_no_argument_a_bad(int);
 
 /// \a A
 int test_inline_no_argument_a_good(int);
 
-// expected-warning@+1 {{'\anchor' command does not have a valid word argument}}
+// expected-warning@+1 {{'\anchor' command has no word arguments, expected 1}}
 /// \anchor
 int test_inline_no_argument_anchor_bad(int);
 
 /// \anchor A
 int test_inline_no_argument_anchor_good(int);
 
-// expected-warning@+1 {{'@b' command does not have a valid word argument}}
+// expected-warning@+1 {{'@b' command has no word arguments, expected 1}}
 /// @b
 int test_inline_no_argument_b_bad(int);
 
 /// @b A
 int test_inline_no_argument_b_good(int);
 
-// expected-warning@+1 {{'\c' command does not have a valid word argument}}
+// expected-warning@+1 {{'\c' command has no word arguments, expected 1}}
 /// \c
 int test_inline_no_argument_c_bad(int);
 
 /// \c A
 int test_inline_no_argument_c_good(int);
 
-// expected-warning@+1 {{'\e' command does not have a valid word argument}}
+// expected-warning@+1 {{'\e' command has no word arguments, expected 1}}
 /// \e
 int test_inline_no_argument_e_bad(int);
 
 /// \e A
 int test_inline_no_argument_e_good(int);
 
-// expected-warning@+1 {{'\em' command does not have a valid word argument}}
+// expected-warning@+1 {{'\em' command has no word arguments, expected 1}}
 /// \em
 int test_inline_no_argument_em_bad(int);
 
 /// \em A
 int test_inline_no_argument_em_good(int);
 
-// expected-warning@+1 {{'\p' command does not have a valid word argument}}
+// expected-warning@+1 {{'\p' command has no word arguments, expected 1}}
 /// \p
 int test_inline_no_argument_p_bad(int);
 
Index: clang/test/Headers/x86-intrinsics-headers-clean.cpp
===
--- clang/test/Headers/x86-intrinsics-headers-clean.cpp
+++ clang/test/Headers/x86-intrinsics-headers-clean.cpp
@@ -1,11 +1,11 @@
 // Make sure the intrinsic headers compile cleanly with no warnings or errors.
 
 // RUN: %clang_cc1 -ffreestanding -triple i386-unknown-unknown \
-// RUN:-Wextra -Werror -Wsystem-headers -Wsign-conversion -Wcast-qual -Wdocumentation \
+// RUN:-Wextra -Werror -Wsystem-headers -Wsign-conversion -Wcast-qual -Wdocumentation -Wdocumentation-pedantic -Wdocumentation-unknown-command \
 // RUN:-fsyntax-only -fretain-comments-from-system-headers -flax-vector-conversions=none -x c++ -verify %s
 
 // RUN: %clang_cc1 -ffreestanding -triple x86_64-unknown-unknown \
-// RUN:-Wextra -Werror -Wsystem-headers -Wsign-conversion -Wcast-qual -Wdocumentation \
+// RUN:-Wextra -Werror -Wsystem-headers -Wsign-conversion -Wcast-qual -Wdocumentation -Wdocumentation-pedantic -Wdocumentation-unknown-command \
 // RUN:-fsyntax-only -fretain-comments-from-system-headers -flax-vector-conversions=none -x c++ -verify %s
 
 // expected-no-diagnostics
Index: clang/test/AST/ast-dump-comment.cpp
===
--- clang/test/AST/ast-dump-comment.cpp
+++ clang/test/AST/ast-dump-comment.cpp
@@ -62,6 +62,12 @@
 // CHECK:  VarDecl{{.*}}Test_InlineCommandComment
 // CHECK:InlineCommandComment{{.*}} Name="c" RenderMonospaced Arg[0]="Aaa"
 
+/// \n Aaa
+int Test_InlineCommandComment_NoArgs;
+// CHECK:  VarDecl{{.*}}Test_InlineCommandComment_NoArgs
+// CHECK:InlineCommandComment{{.*}} Name="n" RenderNormal
+// CHECK-NEXT:   TextComment{{.*}} Text=" Aaa"
+
 /// \anchor Aaa
 int Test_InlineCommandCommentAnchor;
 // CHECK:  VarDecl{{.*}}Test_InlineCommandComment
Index: clang/lib/AST/CommentSema.cpp
===
--- clang/lib/AST/C

[PATCH] D125473: Comment parsing: Treat properties as zero-argument inline commands

2022-05-13 Thread Aaron Puchert 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 rGd2396d896ee1: Comment parsing: Treat properties as 
zero-argument inline commands (authored by aaronpuchert).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125473

Files:
  clang/include/clang/AST/CommentCommands.td


Index: clang/include/clang/AST/CommentCommands.td
===
--- clang/include/clang/AST/CommentCommands.td
+++ clang/include/clang/AST/CommentCommands.td
@@ -63,6 +63,11 @@
   let IsVerbatimLineCommand = 1;
 }
 
+class PropertyCommand : Command {
+  let NumArgs = 0;
+  let IsInlineCommand = 1;
+}
+
 class DeclarationVerbatimLineCommand :
   VerbatimLineCommand {
   let IsDeclarationCommand = 1;
@@ -275,31 +280,6 @@
 
 def NoOp : VerbatimLineCommand<"noop">;
 
-// These have actually no arguments, but we can treat them as line commands.
-def CallGraph   : VerbatimLineCommand<"callgraph">;
-def HideCallGraph   : VerbatimLineCommand<"hidecallgraph">;
-def CallerGraph : VerbatimLineCommand<"callergraph">;
-def HideCallerGraph : VerbatimLineCommand<"hidecallergraph">;
-def ShowInitializer : VerbatimLineCommand<"showinitializer">;
-def HideInitializer : VerbatimLineCommand<"hideinitializer">;
-def ShowRefBy   : VerbatimLineCommand<"showrefby">;
-def HideRefBy   : VerbatimLineCommand<"hiderefby">;
-def ShowRefs: VerbatimLineCommand<"showrefs">;
-def HideRefs: VerbatimLineCommand<"hiderefs">;
-
-// These also have no argument.
-def Private   : VerbatimLineCommand<"private">;
-def Protected : VerbatimLineCommand<"protected">;
-def Public: VerbatimLineCommand<"public">;
-def Pure  : VerbatimLineCommand<"pure">;
-def Static: VerbatimLineCommand<"static">;
-
-// These also have no argument.
-def NoSubgrouping: VerbatimLineCommand<"nosubgrouping">;
-def PrivateSection   : VerbatimLineCommand<"privatesection">;
-def ProtectedSection : VerbatimLineCommand<"protectedsection">;
-def PublicSection: VerbatimLineCommand<"publicsection">;
-
 // We might also build proper support for if/ifnot/else/elseif/endif.
 def If : VerbatimLineCommand<"if">;
 def IfNot  : VerbatimLineCommand<"ifnot">;
@@ -311,6 +291,32 @@
 def Cond: VerbatimLineCommand<"cond">;
 def EndCond : VerbatimLineCommand<"endcond">;
 
+//===--===//
+// PropertyCommand
+//===--===//
+
+def CallGraph   : PropertyCommand<"callgraph">;
+def HideCallGraph   : PropertyCommand<"hidecallgraph">;
+def CallerGraph : PropertyCommand<"callergraph">;
+def HideCallerGraph : PropertyCommand<"hidecallergraph">;
+def ShowInitializer : PropertyCommand<"showinitializer">;
+def HideInitializer : PropertyCommand<"hideinitializer">;
+def ShowRefBy   : PropertyCommand<"showrefby">;
+def HideRefBy   : PropertyCommand<"hiderefby">;
+def ShowRefs: PropertyCommand<"showrefs">;
+def HideRefs: PropertyCommand<"hiderefs">;
+
+def Private   : PropertyCommand<"private">;
+def Protected : PropertyCommand<"protected">;
+def Public: PropertyCommand<"public">;
+def Pure  : PropertyCommand<"pure">;
+def Static: PropertyCommand<"static">;
+
+def NoSubgrouping: PropertyCommand<"nosubgrouping">;
+def PrivateSection   : PropertyCommand<"privatesection">;
+def ProtectedSection : PropertyCommand<"protectedsection">;
+def PublicSection: PropertyCommand<"publicsection">;
+
 
//===--===//
 // DeclarationVerbatimLineCommand
 
//===--===//


Index: clang/include/clang/AST/CommentCommands.td
===
--- clang/include/clang/AST/CommentCommands.td
+++ clang/include/clang/AST/CommentCommands.td
@@ -63,6 +63,11 @@
   let IsVerbatimLineCommand = 1;
 }
 
+class PropertyCommand : Command {
+  let NumArgs = 0;
+  let IsInlineCommand = 1;
+}
+
 class DeclarationVerbatimLineCommand :
   VerbatimLineCommand {
   let IsDeclarationCommand = 1;
@@ -275,31 +280,6 @@
 
 def NoOp : VerbatimLineCommand<"noop">;
 
-// These have actually no arguments, but we can treat them as line commands.
-def CallGraph   : VerbatimLineCommand<"callgraph">;
-def HideCallGraph   : VerbatimLineCommand<"hidecallgraph">;
-def CallerGraph : VerbatimLineCommand<"callergraph">;
-def HideCallerGraph : VerbatimLineCommand<"hidecallergraph">;
-def ShowInitializer : VerbatimLineCommand<"showinitializer">;
-def HideInitializer : VerbatimLineCommand<"hideinitializer">;
-def ShowRefBy   : VerbatimLineCommand<"showrefby">;
-def HideRefBy   : VerbatimLineCommand<"hiderefby">;
-def ShowRefs: V

[PATCH] D118996: [clang-tidy] Support C++14 in bugprone-signal-handler.

2022-05-13 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 429205.
balazske marked 8 inline comments as done.
balazske added a comment.

Using one isa statement for all class names.
Changed the documentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118996

Files:
  clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone-signal-handler.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-msc54-cpp.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/signal.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-signal-handler/stdcpp.h
  clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.c
  clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp
@@ -0,0 +1,228 @@
+// RUN: %check_clang_tidy -std=c++14 %s bugprone-signal-handler %t -- -- -isystem %S/Inputs/Headers -isystem %S/Inputs/bugprone-signal-handler
+
+#include "stdcpp.h"
+#include "stdio.h"
+
+// Functions called "signal" that are different from the system version.
+typedef void (*callback_t)(int);
+void signal(int, callback_t, int);
+namespace ns {
+void signal(int, callback_t);
+}
+
+extern "C" void handler_unsafe(int) {
+  printf("xxx");
+}
+
+extern "C" void handler_unsafe_1(int) {
+  printf("xxx");
+}
+
+namespace test_invalid_handler {
+
+void handler_non_extern_c(int) {
+  printf("xxx");
+}
+
+struct A {
+  static void handler_member(int) {
+printf("xxx");
+  }
+};
+
+void test() {
+  std::signal(SIGINT, handler_unsafe_1);
+  // CHECK-MESSAGES: :[[@LINE-17]]:3: warning: standard function 'printf' may not be asynchronous-safe; calling it from a signal handler may be dangerous [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:23: note: function 'handler_unsafe_1' registered here as signal handler
+
+  std::signal(SIGINT, handler_non_extern_c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: functions without C linkage are not allowed as signal handler (until C++17) [bugprone-signal-handler]
+  std::signal(SIGINT, A::handler_member);
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: functions without C linkage are not allowed as signal handler (until C++17) [bugprone-signal-handler]
+  std::signal(SIGINT, [](int) { printf("xxx"); });
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: lambda function is not allowed as signal handler (until C++17) [bugprone-signal-handler]
+
+  // This case is (deliberately) not found by the checker.
+  std::signal(SIGINT, [](int) -> callback_t { return &handler_unsafe; }(1));
+}
+
+} // namespace test_invalid_handler
+
+namespace test_non_standard_signal_call {
+
+struct Signal {
+  static void signal(int, callback_t);
+};
+
+void test() {
+  // No diagnostics here. All these signal calls differ from the standard system one.
+  signal(SIGINT, handler_unsafe, 1);
+  ns::signal(SIGINT, handler_unsafe);
+  Signal::signal(SIGINT, handler_unsafe);
+  system_other::signal(SIGINT, handler_unsafe);
+}
+
+} // namespace test_non_standard_signal_call
+
+namespace test_cpp_construct_in_handler {
+
+struct Struct {
+  virtual ~Struct() {}
+  void f1();
+  int *begin();
+  int *end();
+  static void f2();
+};
+struct Derived : public Struct {
+};
+
+struct X {
+  X(int, float);
+};
+
+Struct *S_Global;
+const Struct *S_GlobalConst;
+
+void f_non_extern_c() {
+}
+
+void f_default_arg(int P1 = 0) {
+}
+
+extern "C" void handler_cpp(int) {
+  using namespace ::test_cpp_construct_in_handler;
+
+  // These calls are not found as problems.
+  // (Called functions are not analyzed if the current function has already
+  // other problems.)
+  f_non_extern_c();
+  Struct::f2();
+  // 'auto' is not disallowed
+  auto Auto = 28u;
+
+  Struct S;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: C++-only construct is not allowed in signal handler (until C++17) [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: remark: internally, the statement is parsed as a 'CXXConstructExpr'
+  // CHECK-MESSAGES: :198:23: note: function 'handler_cpp' registered here as signal handler
+  S_Global->f1();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: C++-only construct is not allowed in signal handler (until C++17) [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: remark: internally, the statement is parsed as a 'CXXMemberCallExpr'
+  // CHECK-MESSAGES: :198:23: note: function 'handler_cpp' registered here as signal handler
+  const Struct &SRef = Struct();
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: C++-only construct is not allowed in signal handler (un

[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:107
+return makeNonLoc(X.castAs().getSymbol(), UO_Not,
+  X.getType(Context));
   default:

steakhal wrote:
> martong wrote:
> > steakhal wrote:
> > > I'm not sure if we should rely on `SVal::getType()`. I think the calling 
> > > context should pass the type along here.
> > Good point. One example where the type of the SVal is different than the 
> > type of the UnaryExpr is here:
> > ```
> > void test_x(int x, long y) {
> >   x = y;  // $x has `long` type
> >   -x; // the UnaryExpr `-x` has `int` type
> > }
> > ```
> > Note that if we use `support-symbolic-integer-casts=true` then there is no 
> > such type mismatch because there is in implicit cast modeled at `x = y`, 
> > thus $x type is correctly `int`.
> > 
> > Anyway, I am going to update evalMinus and evalComplement to take an 
> > additional QualType parameter.
> Please add this test with both scenarios with 
> `support-symbolic-integer-casts`. D125532 will help in demonstrating this.
Ahh, unfortunately, if we use the type of the AST's `UnaryExpr` instead of the 
operand `SVal` then we will end up crashing the constraint solver, because of 
the missing SymbolCast below:
```
void crash(int b, long c) {
  b = c;
  if (b > 0)// $b  is long
if(-b) // should not crash here // $-b is int
  ;
  // SymbolicRangeInferrer
  // takes the negated range of $-b (with type int)
  // getRangeForNegatedSub
  // and takes the range of $b (with type long) and tries to intersect them.
  // RangeSet VisitSymExpr(SymbolRef Sym)
}
```
This manifests in the child patch, because that's where we add the support of 
UnarySymExpr to the solver, so I add a test case there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429207.
martong added a comment.

- Revert "Add type parameter to evalMinus and evalComplement"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/explain-svals.cpp
  clang/test/Analysis/expr-inspection.cpp
  clang/test/Analysis/unary-sym-expr.c

Index: clang/test/Analysis/unary-sym-expr.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr.c
@@ -0,0 +1,36 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+int test(int x, int y) {
+
+  clang_analyzer_dump(-x);   // expected-warning{{-reg_$0}}
+  clang_analyzer_dump(~x);   // expected-warning{{~reg_$0}}
+  int z = x + y;
+  clang_analyzer_dump(-z);   // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-(x + y)); // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-x + y);   // expected-warning{{(-reg_$0) + (reg_$1)}}
+
+  if (-x == 0) {
+clang_analyzer_eval(-x == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(-x > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(-x < 0);  // expected-warning{{FALSE}}
+  }
+  if (~y == 0) {
+clang_analyzer_eval(~y == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(~y > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(~y < 0);  // expected-warning{{FALSE}}
+  }
+  (void)(x);
+  return 42;
+}
+
+void test_svalbuilder_simplification(int x, int y) {
+  if (x + y != 3)
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}
Index: clang/test/Analysis/expr-inspection.cpp
===
--- clang/test/Analysis/expr-inspection.cpp
+++ clang/test/Analysis/expr-inspection.cpp
@@ -18,6 +18,8 @@
   clang_analyzer_express(x); // expected-warning{{Unable to express}}
 
   clang_analyzer_denote(x, "$x");
+  clang_analyzer_express(-x); // expected-warning{{-$x}}
+
   clang_analyzer_denote(y, "$y");
   clang_analyzer_express(x + y); // expected-warning{{$x + $y}}
 
Index: clang/test/Analysis/explain-svals.cpp
===
--- clang/test/Analysis/explain-svals.cpp
+++ clang/test/Analysis/explain-svals.cpp
@@ -72,6 +72,7 @@
 void test_4(int x, int y) {
   int z;
   static int stat;
+  clang_analyzer_explain(-x);// expected-warning-re^\- \(argument 'x'\)$
   clang_analyzer_explain(x + 1); // expected-warning-re^\(argument 'x'\) \+ 1$
   clang_analyzer_explain(1 + y); // expected-warning-re^\(argument 'y'\) \+ 1$
   clang_analyzer_explain(x + y); // expected-warning-re^\(argument 'x'\) \+ \(argument 'y'\)$
Index: clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -70,6 +70,16 @@
   os << ')';
 }
 
+void UnarySymExpr::dumpToStream(raw_ostream &os) const {
+  os << UnaryOperator::getOpcodeStr(Op);
+  bool Binary = isa(Operand);
+  if (Binary)
+os << '(';
+  Operand->dumpToStream(os);
+  if (Binary)
+os << ')';
+}
+
 void SymbolConjured::dumpToStream(raw_ostream &os) const {
   os << getKindStr() << getSymbolID() << '{' << T << ", LC" << LCtx->getID();
   if (S)
@@ -134,6 +144,9 @@
 case SymExpr::SymbolCastKind:
   itr.push_back(cast(SE)->getOperand());
   return;
+case SymExpr::UnarySymExprKind:
+  itr.push_back(cast(SE)->getOperand());
+  return;
 case SymExpr::SymIntExprKind:
   itr.push_back(cast(SE)->getLHS());
   return;
@@ -306,6 +319,22 @@
   return cast(data);
 }
 
+const UnarySymExpr *SymbolManager::getUnarySymExpr(const SymExpr *Operand,
+   UnaryOperator::Opcode Opc,
+   QualType T) {
+  llvm::FoldingSetNodeID ID;
+  UnarySymExpr::Profile(ID, Operand, Opc, T);
+  void *InsertPos;
+  SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
+  if (!data) {
+data = (UnarySymExpr *)BPAlloc.Allocate();
+new (data) UnarySymExpr(Operand, Opc, T);
+DataSet.InsertNode(data, InsertPos);
+ 

[PATCH] D125395: [analyzer][solver] Handle UnarySymExpr in RangeConstraintSolver

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429208.
martong added a comment.

- Add a test case for casts related crash


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125395

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/constraint_manager_negate.c
  clang/test/Analysis/constraint_manager_negate_difference.c
  clang/test/Analysis/unary-sym-expr-no-crash.c
  clang/test/Analysis/unary-sym-expr.c

Index: clang/test/Analysis/unary-sym-expr.c
===
--- clang/test/Analysis/unary-sym-expr.c
+++ clang/test/Analysis/unary-sym-expr.c
@@ -34,3 +34,12 @@
 return;
   clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
 }
+
+int test_fp(int flag) {
+  int value;
+  if (flag == 0)
+value = 1;
+  if (-flag == 0)
+return value; // no-warning
+  return 42;
+}
Index: clang/test/Analysis/unary-sym-expr-no-crash.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr-no-crash.c
@@ -0,0 +1,23 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=false \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// expected-no-diagnostics
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+void crash(int b, long c) {
+  b = c;
+  if (b > 0)
+if(-b) // should not crash here
+  ;
+}
Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -1,4 +1,6 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-binary-operation-simplification=true -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -10,11 +12,8 @@
 #define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
 #define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
 
-extern void __assert_fail (__const char *__assertion, __const char *__file,
-unsigned int __line, __const char *__function)
- __attribute__ ((__noreturn__));
-#define assert(expr) \
-  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
 
 void assert_in_range(int x) {
   assert(x <= ((int)INT_MAX / 4));
@@ -33,69 +32,60 @@
 
 void equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m != n)
-return;
+  assert(m == n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n == m); // expected-warning{{TRUE}}
 }
 
 void non_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m == n)
-return;
+  assert(m != n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n != m); // expected-warning{{TRUE}}
 }
 
 void less_or_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m < n)
-return;
+  assert(m >= n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n <= m); // expected-warning{{TRUE}}
 }
 
 void less(int m, int n) {
   assert_in_range_2(m, n);
-  if (m <= n)
-return;
+  assert(m > n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n < m); // expected-warning{{TRUE}}
 }
 
 void greater_or_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m > n)
-return;
+  assert(m <= n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n >= m); // expected-warning{{TRUE}}
 }
 
 void greater(int m, int n) {
   assert_in_range_2(m, n);
-  if (m >= n)
-return;
+  assert(m < n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n > m); // expected-warning{{TRUE}}
 }
 
 void negate_positive_range(int m, int n) {
-  if (m - n <= 0)
-return;
+  assert(m - n > 0);
   clang_analyzer_eval(n - m < 0); // expected-warning{{TRUE}}
   clang_analyzer_eval(n - m > INT_MIN); // expected-warning{{TRUE}}
-  clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{FALSE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void negate_int_min(int m, int n) {
-  if (m - n != INT_MIN)
-return;
+  assert(m - n == INT_MIN);
   clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{TRUE}}
 }
 
 void negate_mixed(int m, int n) {
-  if (m -n > INT_MIN && m - n <= 0)
-return;
+  assert(m - n > 0 || m - n == INT_MIN);
   clang_analyzer_eval(n - m <= 0); // expected-warning{{TRUE}}
 }
 
@@ -106,54 +96,59 @@
   clang_analy

[PATCH] D120727: [libc++] Overhaul how we select the ABI library

2022-05-13 Thread Louis Dionne via Phabricator via cfe-commits
ldionne accepted this revision as: libc++.
ldionne marked an inline comment as done.
ldionne added inline comments.
This revision is now accepted and ready to land.



Comment at: libcxx/CMakeLists.txt:250
+
+set(LIBCXX_SUPPORTED_ABI_LIBRARIES none libcxxabi system-libcxxabi libcxxrt 
libstdc++ libsupc++ vcruntime)
+set(LIBCXX_CXX_ABI "${LIBCXX_DEFAULT_ABI_LIBRARY}" CACHE STRING "Specify C++ 
ABI library to use. Supported values are ${LIBCXX_SUPPORTED_ABI_LIBRARIES}.")

phosek wrote:
> mstorsjo wrote:
> > ldionne wrote:
> > > phosek wrote:
> > > > All of these values refer to system ABI libraries except for libcxxabi 
> > > > where `libcxxabi is the in-tree one and `system-libcxxabi` is the 
> > > > system one. From a consistency perspective, I think it'd be better for 
> > > > `libcxxabi` to also refer to a system ABI library, and then use a 
> > > > different name for the in-tree one, perhaps `default`?
> > > I agree with the consistency argument. However, I'd like to avoid 
> > > `default` since it doesn't convey any information, and it also used to be 
> > > one of the valid values but it represented "whatever automatically 
> > > selected ABI we pick", which might not be libc++abi. I'd suggest 
> > > `libcxxabi` and `intree-libcxxabi`. It's not extremely pretty, but it 
> > > conveys exactly what it is.
> > > 
> > > Edit: I actually went ahead and made this change, and I realized that it 
> > > might be breaking for a bunch of people. Indeed, I think that most people 
> > > who specify `libcxxabi` are expecting to build against the in-tree one, 
> > > which is what happens today as long as they have `libcxxabi` in their 
> > > `LLVM_ENABLE_RUNTIMES`. With this renaming, they would implicitly start 
> > > building against the system libc++abi, and that might happen silently. 
> > > I'm not sure I like this. So, here's the diff to implement this change, 
> > > however I'd rather not apply it unless you think consistency is more 
> > > important that this concern:
> > > 
> > > ```
> > > diff --git a/libcxx/CMakeLists.txt b/libcxx/CMakeLists.txt
> > > index a7f1684235e6..7cbf8957ac90 100644
> > > --- a/libcxx/CMakeLists.txt
> > > +++ b/libcxx/CMakeLists.txt
> > > @@ -244,10 +244,10 @@ if (LIBCXX_TARGETING_MSVC)
> > >  elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
> > >set(LIBCXX_DEFAULT_ABI_LIBRARY "libcxxrt")
> > >  else()
> > > -  set(LIBCXX_DEFAULT_ABI_LIBRARY "libcxxabi")
> > > +  set(LIBCXX_DEFAULT_ABI_LIBRARY "intree-libcxxabi")
> > >  endif()
> > >  
> > > -set(LIBCXX_SUPPORTED_ABI_LIBRARIES none libcxxabi system-libcxxabi 
> > > libcxxrt libstdc++ libsupc++ vcruntime)
> > > +set(LIBCXX_SUPPORTED_ABI_LIBRARIES none intree-libcxxabi libcxxabi 
> > > libcxxrt libstdc++ libsupc++ vcruntime)
> > >  set(LIBCXX_CXX_ABI "${LIBCXX_DEFAULT_ABI_LIBRARY}" CACHE STRING "Specify 
> > > C++ ABI library to use. Supported values are 
> > > ${LIBCXX_SUPPORTED_ABI_LIBRARIES}.")
> > >  
> > >  # Temporary to still accept existing CMake caches that contain "default" 
> > > as the value
> > > diff --git a/libcxx/cmake/Modules/HandleLibCXXABI.cmake 
> > > b/libcxx/cmake/Modules/HandleLibCXXABI.cmake
> > > index 6e7a53258c0a..f22cfd674623 100644
> > > --- a/libcxx/cmake/Modules/HandleLibCXXABI.cmake
> > > +++ b/libcxx/cmake/Modules/HandleLibCXXABI.cmake
> > > @@ -97,7 +97,7 @@ add_library(libcxx-abi-headers INTERFACE)
> > >import_shared_library(libcxx-abi-static 
> > > "${LIBCXX_CXX_ABI_LIBRARY_PATH}" supc++)
> > >  
> > >  # Link against the in-tree libc++abi
> > > -elseif ("${LIBCXX_CXX_ABI}" STREQUAL "libcxxabi")
> > > +elseif ("${LIBCXX_CXX_ABI}" STREQUAL "intree-libcxxabi")
> > >add_library(libcxx-abi-headers INTERFACE)
> > >target_link_libraries(libcxx-abi-headers INTERFACE cxxabi-headers)
> > >target_compile_definitions(libcxx-abi-headers INTERFACE 
> > > "-DLIBCXX_BUILDING_LIBCXXABI")
> > > @@ -111,7 +111,7 @@ elseif ("${LIBCXX_CXX_ABI}" STREQUAL "libcxxabi")
> > >endif()
> > >  
> > >  # Link against a system-provided libc++abi
> > > -elseif ("${LIBCXX_CXX_ABI}" STREQUAL "system-libcxxabi")
> > > +elseif ("${LIBCXX_CXX_ABI}" STREQUAL "libcxxabi")
> > >add_library(libcxx-abi-headers INTERFACE)
> > >import_private_headers(libcxx-abi-headers 
> > > "${LIBCXX_CXX_ABI_INCLUDE_PATHS}" "cxxabi.h;__cxxabi_config.h")
> > >target_compile_definitions(libcxx-abi-headers INTERFACE 
> > > "-DLIBCXX_BUILDING_LIBCXXABI")
> > > diff --git a/libcxx/cmake/caches/AIX.cmake b/libcxx/cmake/caches/AIX.cmake
> > > index 029b8deae3d7..e3f31aea5192 100644
> > > --- a/libcxx/cmake/caches/AIX.cmake
> > > +++ b/libcxx/cmake/caches/AIX.cmake
> > > @@ -13,4 +13,4 @@ set(LIBCXX_ENABLE_SHARED ON CACHE BOOL "")
> > >  set(LIBCXX_ENABLE_STATIC OFF CACHE BOOL "")
> > >  set(LIBCXXABI_ENABLE_SHARED ON CACHE BOOL "")
> > >  set(LIBCXXABI_ENABLE_STATIC OFF CACHE BOOL "")
> > > -set(LIBCXX_CXX_ABI libcxxabi CACHE STRING "")
> > > +set(LIBCXX_CXX_ABI intree-libcxxabi CACHE STRING "")

[PATCH] D125318: [analyzer] Add UnarySymExpr

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



Comment at: clang/test/Analysis/unary-sym-expr.c:35
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}

steakhal wrote:
> Does it work if you swap x and y?
No, that does not. And the reason of that is we cannot handle commutativity 
(yet).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[clang] 4be105c - Silence some false positive -Wstrict-prototype warnings

2022-05-13 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-13T08:31:52-04:00
New Revision: 4be105c98a9c7e083cd878ee1751e11160b97b4a

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

LOG: Silence some false positive -Wstrict-prototype warnings

Before issuing the warning about use of a strict prototype, check if
the declarator is required to have a prototype through some other means
determined at parse time.

This silences false positives in OpenCL code (where the functions are
forced to have a prototype) and block literal expressions.

Added: 


Modified: 
clang/lib/Sema/SemaType.cpp
clang/test/Parser/opencl-kernel.cl
clang/test/Sema/block-return.c
clang/test/Sema/warn-strict-prototypes.m
clang/test/SemaOpenCL/address-spaces.cl
clang/test/SemaOpenCL/cl20-device-side-enqueue.cl
clang/test/SemaOpenCL/func.cl

Removed: 




diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 0bb352e914a8c..05a9b56f7d8f6 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5575,8 +5575,10 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
 // We suppress the warning when there's no LParen location, as this
 // indicates the declaration was an implicit declaration, which gets
-// warned about separately via -Wimplicit-function-declaration.
-if (FTI.NumParams == 0 && !FTI.isVariadic && 
FTI.getLParenLoc().isValid())
+// warned about separately via -Wimplicit-function-declaration. We also
+// suppress the warning when we know the function has a prototype.
+if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
+FTI.getLParenLoc().isValid())
   S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
   << IsBlock
   << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");

diff  --git a/clang/test/Parser/opencl-kernel.cl 
b/clang/test/Parser/opencl-kernel.cl
index e509ed59a9ea3..01c7ed6b5ab69 100644
--- a/clang/test/Parser/opencl-kernel.cl
+++ b/clang/test/Parser/opencl-kernel.cl
@@ -1,9 +1,10 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only
+// expected-no-diagnostics
 
-__kernel void test() // expected-warning {{a function declaration without a 
prototype is deprecated in all versions of C}}
+__kernel void test()
 {
 }
 
-kernel void test1() // expected-warning {{a function declaration without a 
prototype is deprecated in all versions of C}}
+kernel void test1()
 {
 }

diff  --git a/clang/test/Sema/block-return.c b/clang/test/Sema/block-return.c
index 3dcfe2dfea4ee..1ac050bfb4b29 100644
--- a/clang/test/Sema/block-return.c
+++ b/clang/test/Sema/block-return.c
@@ -100,7 +100,7 @@ bptr foo5(int j) {
 int (*funcptr3[5])(long);
 int sz8 = sizeof(^int (*[5])(long) {return funcptr3;}); // expected-error 
{{block cannot return array type}} expected-warning {{incompatible pointer to 
integer conversion}}
 int sz9 = sizeof(^int(*())()[3]{ }); // expected-error {{function cannot 
return array type}}
- // expected-warning@-1 2 {{a function 
declaration without a prototype is deprecated in all versions of C}}
+ // expected-warning@-1 {{a function 
declaration without a prototype is deprecated in all versions of C}}
 
 void foo6(void) {
   int (^b)(int) __attribute__((noreturn));

diff  --git a/clang/test/Sema/warn-strict-prototypes.m 
b/clang/test/Sema/warn-strict-prototypes.m
index edb8bc6ea388b..38e4ffaba767d 100644
--- a/clang/test/Sema/warn-strict-prototypes.m
+++ b/clang/test/Sema/warn-strict-prototypes.m
@@ -17,7 +17,7 @@ void foo() { // expected-warning {{a function declaration 
without a prototype is
   // FIXME: this should say "a block declaration" instead, but block literal
   // expressions do not track their full declarator information, so we don't
   // know it's a block when diagnosing.
-  void (^block2)(void) = ^void() { // expected-warning {{a function 
declaration without a prototype is deprecated in all versions of C}}
+  void (^block2)(void) = ^void() {
   };
   void (^block3)(void) = ^ { // no warning
   };

diff  --git a/clang/test/SemaOpenCL/address-spaces.cl 
b/clang/test/SemaOpenCL/address-spaces.cl
index 03f303575964b..41f5a33653254 100644
--- a/clang/test/SemaOpenCL/address-spaces.cl
+++ b/clang/test/SemaOpenCL/address-spaces.cl
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 %s -verify=expected,c -pedantic -fsyntax-only
-// RUN: %clang_cc1 %s -cl-std=CL2.0 -verify=expected,c -pedantic -fsyntax-only
-// RUN: %clang_cc1 %s -cl-std=CL3.0 -cl-ext=+__opencl_c_generic_address_space 
-verify=expected,c -pedantic -fsyntax-only
+// RUN: %clang_cc1 %s -verify=expected -p

[PATCH] D120727: [libc++] Overhaul how we select the ABI library

2022-05-13 Thread Louis Dionne via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa80e65e00ada: [libc++] Overhaul how we select the ABI 
library (authored by ldionne).

Changed prior to commit:
  https://reviews.llvm.org/D120727?vs=429069&id=429209#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120727

Files:
  clang/cmake/caches/CrossWinToARMLinux.cmake
  libcxx/CMakeLists.txt
  libcxx/cmake/Modules/HandleLibCXXABI.cmake
  libcxx/docs/BuildingLibcxx.rst
  libcxx/include/CMakeLists.txt
  libcxx/lib/abi/CMakeLists.txt
  libcxx/src/CMakeLists.txt
  libcxx/test/CMakeLists.txt
  libcxx/test/configs/legacy.cfg.in
  libcxx/utils/libcxx/test/config.py
  libcxxabi/test/configs/apple-libc++abi-backdeployment.cfg.in
  libcxxabi/test/configs/apple-libc++abi-shared.cfg.in
  libcxxabi/test/configs/cmake-bridge.cfg.in
  libcxxabi/test/configs/ibm-libc++abi-shared.cfg.in

Index: libcxxabi/test/configs/ibm-libc++abi-shared.cfg.in
===
--- libcxxabi/test/configs/ibm-libc++abi-shared.cfg.in
+++ libcxxabi/test/configs/ibm-libc++abi-shared.cfg.in
@@ -4,7 +4,7 @@
 
 config.substitutions.append(('%{flags}',''))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} ' +
+'-nostdinc++ -I %{include} -I %{cxx-include} -I %{cxx-target-include} ' +
 '-D__LIBC_NO_CPP_MATH_OVERLOADS__ -DLIBCXXABI_NO_TIMER ' +
 '-D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS ' +
 '-I %{libcxx}/test/support -I %{libcxx}/src'
Index: libcxxabi/test/configs/cmake-bridge.cfg.in
===
--- libcxxabi/test/configs/cmake-bridge.cfg.in
+++ libcxxabi/test/configs/cmake-bridge.cfg.in
@@ -28,7 +28,8 @@
 
 config.substitutions.append(('%{cxx}', '@CMAKE_CXX_COMPILER@'))
 config.substitutions.append(('%{libcxx}', '@LIBCXXABI_LIBCXX_PATH@'))
-config.substitutions.append(('%{include}', '@LIBCXXABI_HEADER_DIR@/include/c++/v1'))
-config.substitutions.append(('%{target-include}', '@LIBCXXABI_HEADER_DIR@/%{triple}/include/c++/v1'))
+config.substitutions.append(('%{include}', '@LIBCXXABI_SOURCE_DIR@/include'))
+config.substitutions.append(('%{cxx-include}', '@LIBCXXABI_HEADER_DIR@/include/c++/v1'))
+config.substitutions.append(('%{cxx-target-include}', '@LIBCXXABI_HEADER_DIR@/%{triple}/include/c++/v1'))
 config.substitutions.append(('%{lib}', '@LIBCXXABI_LIBRARY_DIR@'))
 config.substitutions.append(('%{executor}', '@LIBCXXABI_EXECUTOR@'))
Index: libcxxabi/test/configs/apple-libc++abi-shared.cfg.in
===
--- libcxxabi/test/configs/apple-libc++abi-shared.cfg.in
+++ libcxxabi/test/configs/apple-libc++abi-shared.cfg.in
@@ -6,7 +6,7 @@
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else ''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -DLIBCXXABI_NO_TIMER -D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS ' +
+'-nostdinc++ -I %{include} -I %{cxx-include} -I %{cxx-target-include} -DLIBCXXABI_NO_TIMER -D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS ' +
 '-I %{libcxx}/test/support -I %{libcxx}/src'
 ))
 config.substitutions.append(('%{link_flags}',
Index: libcxxabi/test/configs/apple-libc++abi-backdeployment.cfg.in
===
--- libcxxabi/test/configs/apple-libc++abi-backdeployment.cfg.in
+++ libcxxabi/test/configs/apple-libc++abi-backdeployment.cfg.in
@@ -45,7 +45,7 @@
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else ''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -DLIBCXXABI_NO_TIMER -D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS ' +
+'-nostdinc++ -I %{include} -I %{cxx-include} -I %{cxx-target-include} -DLIBCXXABI_NO_TIMER -D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS ' +
 '-I %{libcxx}/test/support -I %{libcxx}/src'
 ))
 config.substitutions.append(('%{link_flags}',
Index: libcxx/utils/libcxx/test/config.py
===
--- libcxx/utils/libcxx/test/config.py
+++ libcxx/utils/libcxx/test/config.py
@@ -412,7 +412,7 @@
 # The compiler normally links in oldnames.lib too, but we've
 # specified -nostdlib above, so we need to specify it manually.
 self.cxx.link_flags += ['-loldnames']
-elif cxx_abi == 'none' or cxx_abi == 'default':
+elif cxx_abi == 'none':
 if self.target_info.is_windows():
 debug_suffix = 'd' if self.debug_build else ''
 self.cxx.link_flags += ['-lmsvcrt%s' % debug_suffix]
Index: libcxx/test/configs/legacy.cfg.in
===
--- libcxx/test/configs/legacy.cfg.in
+++ libcxx/test/configs/legacy.cfg.in
@@ -14,7 +

[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3511312 , @aaron.ballman 
wrote:

> However, I think the blocks behavior is a bug based on this: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L728
>  and I'd be more than happy to fix that, as I'm not checking that condition 
> here: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L5579
>  which seems like a pretty obvious thing to be checking for before warning 
> about not having a strict prototype.

I fixed this false positive bug in 4be105c98a9c7e083cd878ee1751e11160b97b4a 
, so 
blocks (and OpenCL) behavior should now be improved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125532: [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp:268
+  QualType Ty = C.getSVal(Arg).getType(C.getASTContext());
+  reportBug(Ty.getAsString(), C);
+}

Would it make sense to call `Ty->dump(OS)` to a stream and then report the 
string of the stream?
That way we could see some more information. Or perhaps that could be done in 
another introspection function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125532

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


[PATCH] D124932: [clang][dataflow] Track `optional` contents in `optional` model.

2022-05-13 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 429210.
ymandel marked 6 inline comments as done.
ymandel added a comment.

address reviewer comments and fix bug in how the nested value as _re_created -- 
now uses the loc's type rather than the expression's type (which doesn't always 
match exactly).


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

https://reviews.llvm.org/D124932

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -2150,8 +2150,95 @@
   UnorderedElementsAre(Pair("check-1", "safe"), Pair("check-2", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, OptionalValueOptional) {
+  // Basic test that nested values are populated.  We nest an optional because
+  // its easy to use in a test, but the type of the nested value shouldn't
+  // matter.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo) {
+  if (foo && *foo) {
+foo->value();
+/*[[access]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("access", "safe")));
+
+  // Mutation is supported for nested values.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo) {
+  if (foo && *foo) {
+foo->reset();
+foo->value();
+/*[[reset]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("reset", "unsafe: input.cc:9:9")));
+}
+
+// Tests that structs can be nested. We use an optional field because its easy
+// to use in a test, but the type of the field shouldn't matter.
+TEST_P(UncheckedOptionalAccessTest, OptionalValueStruct) {
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+struct Foo {
+  $ns::$optional opt;
+};
+
+void target($ns::$optional foo) {
+  if (foo && foo->opt) {
+foo->opt.value();
+/*[[access]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("access", "safe")));
+}
+
+TEST_P(UncheckedOptionalAccessTest, OptionalValueInitialization) {
+  // FIXME: Fix when to initialize `value`. All unwrapping should be safe in
+  // this example, but `value` initialization is done multiple times during the
+  // fixpoint iterations and joining the environment won't correctly merge them.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo, bool b) {
+  if (!foo.has_value()) return;
+  if (b) {
+if (!foo->has_value()) return;
+// We have created `foo.value()`.
+foo->value();
+  } else {
+if (!foo->has_value()) return;
+// We have created `foo.value()` again, in a different environment.
+foo->value();
+  }
+  // Now we merge the two values. UncheckedOptionalAccessModel::merge() will
+  // throw away the "value" property.
+  foo->value();
+  /*[[merge]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("merge", "unsafe: input.cc:19:7")));
+}
+
 // FIXME: Add support for:
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
 // - invalidation (passing optional by non-const reference/pointer)
-// - nested `optional` values
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -167,10 +167,17 @@
 }
 
 /// Returns the symbolic value that represents the "has_value" property of the
-/// optional value `Val`. Returns null if `Val` is null.
-BoolValue *getHasValue(Value *Val) {
+/// optional value `Val`, creating a fresh one if none is set. Returns null if
+/// `Val` is null.
+BoolValue *getHasValue(Environment &Env, Value *Val) {
   if (auto *OptionalVal = cast_or_null(Val)) {
-return cast(OptionalVal->getProperty("has_value"));
+auto *HasValueVal =
+cast_or_null(OptionalVal->getProperty("has_value"));
+if (HasValueVal == nullptr) {
+  HasValueVal = &Env.makeAtomicBoolValue();
+  OptionalVal->setProperty("has_value", *HasValueVal);
+}
+return HasValueVal;
   }
   return nullptr;
 }
@@ -207,6 +214,51 @@
  .getDesugaredType(ASTCtx));
 }
 
+/// Tries to initialize the `optional`'s value (that is, contents), and return
+/// its location. Returns nullptr if the 

[PATCH] D125524: [BoundV2] ArrayBoundV2 checks if the extent is tainted

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp:208
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = rawOffset.getByteOffset();
-  if (isTainted(state, ByteOffset)) {
+  if (isTainted(state, *upperboundToCheck)) {
 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,

Could you please explain why we change `rawOffset` to `*upperBoundToCheck`? And 
perhaps the same explanation could infiltrate into the checker's code itself as 
a comment to `upperbound`.



Comment at: clang/test/Analysis/taint-diagnostic-visitor.c:46-48
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted 
allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}

Could we get rid of the seemingly unrelated malloc taint report by using an 
array on the stack?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125524

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


[PATCH] D124932: [clang][dataflow] Track `optional` contents in `optional` model.

2022-05-13 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 429211.
ymandel added a comment.

remove stray FIXME from previous diff


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

https://reviews.llvm.org/D124932

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -2150,8 +2150,95 @@
   UnorderedElementsAre(Pair("check-1", "safe"), Pair("check-2", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, OptionalValueOptional) {
+  // Basic test that nested values are populated.  We nest an optional because
+  // its easy to use in a test, but the type of the nested value shouldn't
+  // matter.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo) {
+  if (foo && *foo) {
+foo->value();
+/*[[access]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("access", "safe")));
+
+  // Mutation is supported for nested values.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo) {
+  if (foo && *foo) {
+foo->reset();
+foo->value();
+/*[[reset]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("reset", "unsafe: input.cc:9:9")));
+}
+
+// Tests that structs can be nested. We use an optional field because its easy
+// to use in a test, but the type of the field shouldn't matter.
+TEST_P(UncheckedOptionalAccessTest, OptionalValueStruct) {
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+struct Foo {
+  $ns::$optional opt;
+};
+
+void target($ns::$optional foo) {
+  if (foo && foo->opt) {
+foo->opt.value();
+/*[[access]]*/
+  }
+}
+  )",
+  UnorderedElementsAre(Pair("access", "safe")));
+}
+
+TEST_P(UncheckedOptionalAccessTest, OptionalValueInitialization) {
+  // FIXME: Fix when to initialize `value`. All unwrapping should be safe in
+  // this example, but `value` initialization is done multiple times during the
+  // fixpoint iterations and joining the environment won't correctly merge them.
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using Foo = $ns::$optional;
+
+void target($ns::$optional foo, bool b) {
+  if (!foo.has_value()) return;
+  if (b) {
+if (!foo->has_value()) return;
+// We have created `foo.value()`.
+foo->value();
+  } else {
+if (!foo->has_value()) return;
+// We have created `foo.value()` again, in a different environment.
+foo->value();
+  }
+  // Now we merge the two values. UncheckedOptionalAccessModel::merge() will
+  // throw away the "value" property.
+  foo->value();
+  /*[[merge]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("merge", "unsafe: input.cc:19:7")));
+}
+
 // FIXME: Add support for:
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
 // - invalidation (passing optional by non-const reference/pointer)
-// - nested `optional` values
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -167,10 +167,17 @@
 }
 
 /// Returns the symbolic value that represents the "has_value" property of the
-/// optional value `Val`. Returns null if `Val` is null.
-BoolValue *getHasValue(Value *Val) {
+/// optional value `Val`, creating a fresh one if none is set. Returns null if
+/// `Val` is null.
+BoolValue *getHasValue(Environment &Env, Value *Val) {
   if (auto *OptionalVal = cast_or_null(Val)) {
-return cast(OptionalVal->getProperty("has_value"));
+auto *HasValueVal =
+cast_or_null(OptionalVal->getProperty("has_value"));
+if (HasValueVal == nullptr) {
+  HasValueVal = &Env.makeAtomicBoolValue();
+  OptionalVal->setProperty("has_value", *HasValueVal);
+}
+return HasValueVal;
   }
   return nullptr;
 }
@@ -207,6 +214,50 @@
  .getDesugaredType(ASTCtx));
 }
 
+/// Tries to initialize the `optional`'s value (that is, contents), and return
+/// its location. Returns nullptr if the value can't be represented.
+StorageLocation *maybeInitializeOptionalValueMember(QualType Q,
+StructValue &OptionalVal,
+ 

[PATCH] D123685: [clang][ASTImporter] Add isNewDecl

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429212.
martong added a comment.

- setNewDecl -> markAsNewDecl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123685

Files:
  clang/include/clang/AST/ASTImporterSharedState.h
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -7686,6 +7686,38 @@
   EXPECT_TRUE(ToX->getInClassInitializer());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, isNewDecl) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  void other() {
+bar();
+  }
+  )",
+  Lang_CXX11);
+  Decl *ToTU = getToTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  )",
+  Lang_CXX11);
+  auto *FromOther = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("other")));
+  ASSERT_TRUE(FromOther);
+
+  auto *ToOther = Import(FromOther, Lang_CXX11);
+  ASSERT_TRUE(ToOther);
+
+  auto *ToBar = FirstDeclMatcher().match(
+  ToTU, functionDecl(hasName("bar")));
+
+  EXPECT_TRUE(SharedStatePtr->isNewDecl(ToOther));
+  EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -285,6 +285,7 @@
   ToD = CreateFun(std::forward(args)...);
   // Keep track of imported Decls.
   Importer.RegisterImportedDecl(FromD, ToD);
+  Importer.SharedState->markAsNewDecl(ToD);
   InitializeImportedDecl(FromD, ToD);
   return false; // A new Decl is created.
 }
Index: clang/include/clang/AST/ASTImporterSharedState.h
===
--- clang/include/clang/AST/ASTImporterSharedState.h
+++ clang/include/clang/AST/ASTImporterSharedState.h
@@ -39,6 +39,9 @@
   /// never cleared (like ImportedFromDecls).
   llvm::DenseMap ImportErrors;
 
+  /// Set of the newly created declarations.
+  llvm::DenseSet NewDecls;
+
   // FIXME put ImportedFromDecls here!
   // And from that point we can better encapsulate the lookup table.
 
@@ -74,6 +77,10 @@
   void setImportDeclError(Decl *To, ImportError Error) {
 ImportErrors[To] = Error;
   }
+
+  bool isNewDecl(const Decl *ToD) const { return NewDecls.count(ToD); }
+
+  void markAsNewDecl(Decl *ToD) { NewDecls.insert(ToD); }
 };
 
 } // namespace clang


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -7686,6 +7686,38 @@
   EXPECT_TRUE(ToX->getInClassInitializer());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, isNewDecl) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  void other() {
+bar();
+  }
+  )",
+  Lang_CXX11);
+  Decl *ToTU = getToTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  )",
+  Lang_CXX11);
+  auto *FromOther = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("other")));
+  ASSERT_TRUE(FromOther);
+
+  auto *ToOther = Import(FromOther, Lang_CXX11);
+  ASSERT_TRUE(ToOther);
+
+  auto *ToBar = FirstDeclMatcher().match(
+  ToTU, functionDecl(hasName("bar")));
+
+  EXPECT_TRUE(SharedStatePtr->isNewDecl(ToOther));
+  EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -285,6 +285,7 @@
   ToD = CreateFun(std::forward(args)...);
   // Keep track of imported Decls.
   Importer.RegisterImportedDecl(FromD, ToD);
+  Importer.SharedState->markAsNewDecl(ToD);
   InitializeImportedDecl(FromD, ToD);
   return false; // A new Decl is created.
 }
Index: clang/include/clang/AST/ASTImporterSharedState.h
===
--- clang/include/clang/AST/ASTImporterSharedState.h
+++ clang/include/clang/AST/ASTImporterSharedState.h
@@ -39,6 +39,9 @@
   /// never cleared (like ImportedFromDecls).
   llvm::DenseMap ImportErrors;
 
+  /// Set of the newly created declarations.
+  llvm::DenseSet NewDecls;
+
   // FIXME put ImportedFromDecls here!
   // And from that point we can better encapsulate the lookup table.
 
@@ -74,6 +77,10 @@
   void setImportDeclError(Decl *To, Im

[PATCH] D125524: [BoundV2] ArrayBoundV2 checks if the extent is tainted

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp:208
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = rawOffset.getByteOffset();
-  if (isTainted(state, ByteOffset)) {
+  if (isTainted(state, *upperboundToCheck)) {
 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,

martong wrote:
> Could you please explain why we change `rawOffset` to `*upperBoundToCheck`? 
> And perhaps the same explanation could infiltrate into the checker's code 
> itself as a comment to `upperbound`.
In the test attached you can see that the extent is tainted, not the offset.
Thus checking the offset for taint won't suffice.
The bug condition should depend on the calculation itself, which is basically 
what is done here.



Comment at: clang/test/Analysis/taint-diagnostic-visitor.c:46-48
+  int *p = (int *)malloc(x + conj); // Generic taint checker forbids tainted 
allocation.
+  // expected-warning@-1 {{Untrusted data is used to specify the buffer size}}
+  // expected-note@-2{{Untrusted data is used to specify the buffer size}}

martong wrote:
> Could we get rid of the seemingly unrelated malloc taint report by using an 
> array on the stack?
No, we need the extent to be tainted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125524

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


[clang] a247ba9 - Suggest typo corrections for preprocessor directives

2022-05-13 Thread Aaron Ballman via cfe-commits

Author: Ken Matsui
Date: 2022-05-13T09:16:46-04:00
New Revision: a247ba9d15635d96225ef39c8c150c08f492e70a

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

LOG: Suggest typo corrections for preprocessor directives

When a preprocessor directive is unknown outside of a skipped
conditional block, we give an error diagnostic because we don't know
how to proceed with preprocessing. But when the directive is in a
skipped conditional block, we would not diagnose it on the theory that
the directive may be known to an implementation other than Clang.

Now, for unknown directives inside a skipped conditional block, we
diagnose the unknown directive as a warning if it is sufficiently
similar to a directive specific to preprocessor conditional blocks. For
example, we'll warn about `#esle` and suggest `#else` but we won't warn
about `#progma` because it's not a directive specific to preprocessor
conditional blocks.

Fixes #51598

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

Added: 
clang/test/Preprocessor/suggest-typoed-directive.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/include/clang/Lex/Preprocessor.h
clang/lib/Lex/PPDirectives.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e52d259608340..5b12400701c68 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -225,6 +225,13 @@ Improvements to Clang's diagnostics
 - Clang now checks for stack resource exhaustion when recursively parsing
   declarators in order to give a diagnostic before we run out of stack space.
   This fixes `Issue 51642 
`_.
+- Unknown preprocessor directives in a skipped conditional block are now given
+  a typo correction suggestion if the given directive is sufficiently similar
+  to another preprocessor conditional directive. For example, if ``#esle``
+  appears in a skipped block, we will warn about the unknown directive and
+  suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
+  suggested when in C2x or C++2b mode. Fixes
+  `Issue 51598 `_.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 3622da94f67e2..4cfd314c01270 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -430,8 +430,10 @@ def ext_pp_opencl_variadic_macros : Extension<
 def ext_pp_gnu_line_directive : Extension<
   "this style of line directive is a GNU extension">,
   InGroup;
-
-def err_pp_invalid_directive : Error<"invalid preprocessing directive">;
+def err_pp_invalid_directive : Error<
+  "invalid preprocessing directive%select{|, did you mean '#%1'?}0">;
+def warn_pp_invalid_directive : Warning<
+  err_pp_invalid_directive.Text>, InGroup>;
 def err_pp_directive_required : Error<
   "%0 must be used within a preprocessing directive">;
 def err_pp_file_not_found : Error<"'%0' file not found">, DefaultFatal;

diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index f11b166b21584..d394ad33c2372 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2238,6 +2238,16 @@ class Preprocessor {
   /// Return true if an error occurs parsing the arg list.
   bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
 
+  /// Provide a suggestion for a typoed directive. If there is no typo, then
+  /// just skip suggesting.
+  ///
+  /// \param Tok - Token that represents the directive
+  /// \param Directive - String reference for the directive name
+  /// \param EndLoc - End location for fixit
+  void SuggestTypoedDirective(const Token &Tok,
+  StringRef Directive,
+  const SourceLocation &EndLoc) const;
+
   /// We just read a \#if or related directive and decided that the
   /// subsequent tokens are in the \#if'd out portion of the
   /// file.  Lex the rest of the file, until we see an \#endif.  If \p

diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 7c7625ad50ba2..55045320fd591 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -266,6 +266,51 @@ static bool warnByDefaultOnWrongCase(StringRef Include) {
 .Default(false);
 }
 
+/// Find a similar string in `Candidates`.
+///
+/// \param LHS a string for a similar string in `Candidates`
+///
+/// \param Candidates the candidates to find a similar string.
+///
+/// \returns a simil

[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa247ba9d1563: Suggest typo corrections for preprocessor 
directives (authored by ken-matsui, committed by aaron.ballman).

Changed prior to commit:
  https://reviews.llvm.org/D124726?vs=429005&id=429221#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124726

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Preprocessor/suggest-typoed-directive.c

Index: clang/test/Preprocessor/suggest-typoed-directive.c
===
--- /dev/null
+++ clang/test/Preprocessor/suggest-typoed-directive.c
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=pre-c2x-cpp2b %s
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify=c2x-cpp2b %s
+// RUN: %clang_cc1 -x c++ -std=c++2b -fsyntax-only -verify=c2x-cpp2b %s
+
+// id:pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#if'?}}
+// ifd:   pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#if'?}}
+// ifde:  pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#ifdef'?}}
+// elf:   pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elsif: pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elseif:pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elfidef:   not suggested to '#elifdef'
+// elfindef:  not suggested to '#elifdef'
+// elfinndef: not suggested to '#elifndef'
+// els:   pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#else'?}}
+// endi:  pre-c2x-cpp2b-warning@+12 {{invalid preprocessing directive, did you mean '#endif'?}}
+#ifdef UNDEFINED
+#id
+#ifd
+#ifde
+#elf
+#elsif
+#elseif
+#elfidef
+#elfindef
+#elfinndef
+#els
+#endi
+#endif
+// id:c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#if'?}}
+// ifd:   c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#if'?}}
+// ifde:  c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#ifdef'?}}
+// elf:   c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elsif: c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elseif:c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elif'?}}
+// elfidef:   c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elifdef'?}}
+// elfindef:  c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elifdef'?}}
+// elfinndef: c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#elifndef'?}}
+// els:   c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#else'?}}
+// endi:  c2x-cpp2b-warning@-12 {{invalid preprocessing directive, did you mean '#endif'?}}
+
+#ifdef UNDEFINED
+#i // no diagnostic
+#endif
+
+#if special_compiler
+#special_compiler_directive // no diagnostic
+#endif
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -266,6 +266,51 @@
 .Default(false);
 }
 
+/// Find a similar string in `Candidates`.
+///
+/// \param LHS a string for a similar string in `Candidates`
+///
+/// \param Candidates the candidates to find a similar string.
+///
+/// \returns a similar string if exists. If no similar string exists,
+/// returns None.
+static Optional findSimilarStr(
+StringRef LHS, const std::vector &Candidates) {
+  // We need to check if `Candidates` has the exact case-insensitive string
+  // because the Levenshtein distance match does not care about it.
+  for (StringRef C : Candidates) {
+if (LHS.equals_insensitive(C)) {
+  return C;
+}
+  }
+
+  // Keep going with the Levenshtein distance match.
+  // If the LHS size is less than 3, use the LHS size minus 1 and if not,
+  // use the LHS size divided by 3.
+  size_t Length = LHS.size();
+  size_t MaxDist = Length < 3 ? Length - 1 : Length / 3;
+
+  Optional> SimilarStr = None;
+  for (StringRef C : Candidates) {
+size_t CurDist = LHS.edit_distance(C, true);
+if (CurDist <= MaxDist) {
+  if (!SimilarStr.hasValue()) {
+// The first similar string found.
+SimilarStr = {C, CurDist};
+  } else if (CurDist < SimilarStr->second) {
+// More similar string found.
+SimilarStr = {C, CurDist};
+  }
+}
+  }
+
+  if (SimilarStr.hasValue()) {
+return SimilarStr-

[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

LGTM, thank you for this! I adjusted the release note and commit message 
somewhat when landing to make sure they were detailed enough.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124726

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


[clang] 3946de0 - [MSVC] Add support for pragma function

2022-05-13 Thread Stephen Long via cfe-commits

Author: Stephen Long
Date: 2022-05-13T06:39:47-07:00
New Revision: 3946de0456fcbcd3a6c9f0d09d16d46c7987e0d7

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

LOG: [MSVC] Add support for pragma function

MSVC pragma function tells the compiler to generate calls to functions in the 
pragma function list, instead of using the builtin. Needs 
https://reviews.llvm.org/D124701

https://docs.microsoft.com/en-us/cpp/preprocessor/function-c-cpp?view=msvc-170

Reviewed By: aaron.ballman

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

Added: 
clang/test/CodeGen/pragma-ms-function.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParsePragma.cpp
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/Preprocessor/pragma_microsoft.c
clang/test/Preprocessor/pragma_microsoft.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5b12400701c68..2a43880c2fd74 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -278,6 +278,9 @@ Removed Compiler Flags
 
 New Pragmas in Clang
 
+- Added support for MSVC's ``#pragma function``, which tells the compiler to
+  generate calls to functions listed in the pragma instead of using the
+  builtins.
 
 - ...
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d8f87747e58d0..dfca233033a9f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -988,6 +988,9 @@ def err_invalid_super_scope : Error<"invalid use of 
'__super', "
 def err_super_in_lambda_unsupported : Error<
   "use of '__super' inside a lambda is unsupported">;
 
+def err_pragma_expected_file_scope : Error<
+  "'#pragma %0' can only appear at file scope">;
+
 def warn_pragma_unused_undeclared_var : Warning<
   "undeclared variable %0 used as an argument for '#pragma unused'">,
   InGroup;

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index caa58d9260628..4e4fcb53474ec 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -196,6 +196,7 @@ class Parser : public CodeCompletionHandler {
   std::unique_ptr MSSection;
   std::unique_ptr MSRuntimeChecks;
   std::unique_ptr MSIntrinsic;
+  std::unique_ptr MSFunction;
   std::unique_ptr MSOptimize;
   std::unique_ptr MSFenvAccess;
   std::unique_ptr CUDAForceHostDeviceHandler;
@@ -722,6 +723,8 @@ class Parser : public CodeCompletionHandler {
  SourceLocation PragmaLocation);
   bool HandlePragmaMSInitSeg(StringRef PragmaName,
  SourceLocation PragmaLocation);
+  bool HandlePragmaMSFunction(StringRef PragmaName,
+  SourceLocation PragmaLocation);
 
   /// Handle the annotation token produced for
   /// #pragma align...

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 27603f0b891f3..13d403bf8db94 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -755,6 +755,9 @@ class Sema final {
   /// optimizations are currently "on", this is set to an invalid location.
   SourceLocation OptimizeOffPragmaLocation;
 
+  /// Set of no-builtin functions listed by \#pragma function.
+  llvm::SmallSetVector MSFunctionNoBuiltins;
+
   /// Flag indicating if Sema is building a recovery call expression.
   ///
   /// This flag is used to avoid building recovery call expressions
@@ -10322,6 +10325,11 @@ class Sema final {
   /// Called on well formed \#pragma clang optimize.
   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
 
+  /// Call on well formed \#pragma function.
+  void
+  ActOnPragmaMSFunction(SourceLocation Loc,
+const llvm::SmallVectorImpl &NoBuiltins);
+
   /// Get the location for the currently active "\#pragma clang optimize
   /// off". If this location is invalid, then the state of the pragma is "on".
   SourceLocation getOptimizeOffPragmaLocation() const {
@@ -10338,6 +10346,11 @@ class Sema final {
   /// attribute to be added (usually because of a pragma).
   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
 
+  /// Only called on function definitions; if there is a pragma in scope
+  /// with the effect of a range-based no_builtin, consider marking the 
function
+  /// with attribute no_builtin.
+  void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
+
   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
   void AddAlignedAttr(Decl *D, 

[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-13 Thread Stephen Long via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3946de0456fc: [MSVC] Add support for pragma function 
(authored by steplong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/pragma-ms-function.c
  clang/test/Preprocessor/pragma_microsoft.c
  clang/test/Preprocessor/pragma_microsoft.cpp

Index: clang/test/Preprocessor/pragma_microsoft.cpp
===
--- clang/test/Preprocessor/pragma_microsoft.cpp
+++ clang/test/Preprocessor/pragma_microsoft.cpp
@@ -1,3 +1,7 @@
 // RUN: %clang_cc1 %s -fsyntax-only -std=c++11 -verify -fms-extensions
 
 #pragma warning(push, 4_D) // expected-warning {{requires a level between 0 and 4}}
+
+extern "C" {
+#pragma function(memset) // no-warning
+}
Index: clang/test/Preprocessor/pragma_microsoft.c
===
--- clang/test/Preprocessor/pragma_microsoft.c
+++ clang/test/Preprocessor/pragma_microsoft.c
@@ -201,6 +201,27 @@
 #pragma clang diagnostic pop
 #pragma intrinsic(asdf) // expected-warning {{'asdf' is not a recognized builtin; consider including }}
 
+// Test pragma function
+#pragma function(memset) // no-warning
+#pragma function(memcpy, strlen, strlen) // no-warning
+#pragma function()   // no-warning
+#pragma function(asdf)   // expected-warning {{'asdf' is not a recognized builtin; consider including }}
+#pragma function(main)   // expected-warning {{'main' is not a recognized builtin; consider including }}
+#pragma function(// expected-warning {{missing ')' after}}
+#pragma function(int)// expected-warning {{missing ')' after}}
+#pragma function(strcmp) asdf// expected-warning {{extra tokens at end}}
+
+#define __INTRIN_H   // there should be no notes after defining __INTRIN_H
+#pragma function(asdf)   // expected-warning-re {{'asdf' is not a recognized builtin{{$
+#pragma function(memset) // no-warning
+#undef __INTRIN_H
+#pragma function(asdf) // expected-warning {{'asdf' is not a recognized builtin; consider including }}
+
+// MSVC accepts this, but we decide to reject it based on the MS docs saying the pragma must appear at the global level
+void pragma_function_foo() {
+#pragma function(memset) // expected-error {{'#pragma function' can only appear at file scope}}
+}
+
 #pragma optimize  // expected-warning{{missing '(' after '#pragma optimize'}}
 #pragma optimize( // expected-warning{{expected string literal in '#pragma optimize'}}
 #pragma optimize(a// expected-warning{{expected string literal in '#pragma optimize'}}
Index: clang/test/CodeGen/pragma-ms-function.c
===
--- /dev/null
+++ clang/test/CodeGen/pragma-ms-function.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -emit-llvm -fms-extensions -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+void foo1(char *s, char *d, size_t n) {
+  bar(s);
+  memset(s, 0, n);
+  memcpy(d, s, n);
+}
+
+#pragma function(strlen, memset)
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+void foo2(char *s, char *d, size_t n) {
+  bar(s);
+  memset(s, 1, n);
+  memcpy(d, s, n);
+}
+
+#pragma function(memcpy)
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+void foo3(char *s, char *d, size_t n) {
+  bar(s);
+  memset(s, 2, n);
+  memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -10218,10 +10218,12 @@
   // marking the function.
   AddCFAuditedAttribute(NewFD);
 
-  // If this is a function definition, check if we have to apply optnone due to
-  // a pragma.
-  if(D.isFunctionDefinition())
+  // If this is a function definition, check if w

[PATCH] D125422: Comment parsing: Specify argument numbers for some block commands

2022-05-13 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Hello,

one of your three commits in 
https://github.com/llvm/llvm-project/compare/562ce1592456...d2396d896ee1 broke 
building on mac:

- http://45.33.8.238/macm1/35247/step_4.txtp
- https://green.lab.llvm.org/green/job/clang-stage1-RA/

Please take a look, and revert for now if it takes a while to fix.

(Here's the error:

  In file included from ../../clang/lib/AST/CommentParser.cpp:9:
  In file included from ../../clang/include/clang/AST/CommentParser.h:16:
  In file included from ../../clang/include/clang/AST/Comment.h:17:
  In file included from ../../clang/include/clang/AST/DeclObjC.h:16:
  In file included from ../../clang/include/clang/AST/Decl.h:19:
  In file included from ../../clang/include/clang/AST/DeclBase.h:18:
  In file included from ../../clang/include/clang/AST/DeclarationName.h:16:
  In file included from ../../clang/include/clang/AST/Type.h:21:
  In file included from ../../clang/include/clang/AST/NestedNameSpecifier.h:18:
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: error: use of overloaded 
operator '<<' is ambiguous (with operand types 'const 
clang::StreamingDiagnostic' and 'typename remove_reference::type' (aka 'unsigned long'))
  DB << std::move(V);
  ~~ ^  
  ../../clang/lib/AST/CommentParser.cpp:417:57: note: in instantiation of 
function template specialization 'clang::DiagnosticBuilder::operator<<' requested here
  << CommandTok.is(tok::at_command) << Info->Name << Args.size()
  ^
  ../../clang/include/clang/Basic/Diagnostic.h:1400:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1406:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1422:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1428:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned long)
  DB << std::move(V);
 ^
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, int)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, long long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, __int128)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned int)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned long long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned __int128)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(long long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(__int128, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned int, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned long long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned __int128, unsigned long)

)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125422

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


[PATCH] D125422: Comment parsing: Specify argument numbers for some block commands

2022-05-13 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looking at that error some more, it must've been D125429 
. Moving the comment over there, sorry for 
the noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125422

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


[PATCH] D125429: Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-13 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Hello, this broke building on mac:

- http://45.33.8.238/macm1/35247/step_4.txtp
- https://green.lab.llvm.org/green/job/clang-stage1-RA/

Please take a look, and revert for now if it takes a while to fix.

(Here's the error:

  In file included from ../../clang/lib/AST/CommentParser.cpp:9:
  In file included from ../../clang/include/clang/AST/CommentParser.h:16:
  In file included from ../../clang/include/clang/AST/Comment.h:17:
  In file included from ../../clang/include/clang/AST/DeclObjC.h:16:
  In file included from ../../clang/include/clang/AST/Decl.h:19:
  In file included from ../../clang/include/clang/AST/DeclBase.h:18:
  In file included from ../../clang/include/clang/AST/DeclarationName.h:16:
  In file included from ../../clang/include/clang/AST/Type.h:21:
  In file included from ../../clang/include/clang/AST/NestedNameSpecifier.h:18:
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: error: use of overloaded 
operator '<<' is ambiguous (with operand types 'const 
clang::StreamingDiagnostic' and 'typename remove_reference::type' (aka 'unsigned long'))
  DB << std::move(V);
  ~~ ^  
  ../../clang/lib/AST/CommentParser.cpp:417:57: note: in instantiation of 
function template specialization 'clang::DiagnosticBuilder::operator<<' requested here
  << CommandTok.is(tok::at_command) << Info->Name << Args.size()
  ^
  ../../clang/include/clang/Basic/Diagnostic.h:1400:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1406:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1422:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1428:35: note: candidate function
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
^
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned long)
  DB << std::move(V);
 ^
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, int)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, long long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, __int128)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned int)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned long long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(int, unsigned __int128)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(long long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(__int128, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned int, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned long long, unsigned long)
  ../../clang/include/clang/Basic/Diagnostic.h:1353:8: note: built-in candidate 
operator<<(unsigned __int128, unsigned long)

)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125429

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


[clang] e0fcdf5 - Revert "In MSVC compatibility mode, friend function declarations behave as function declarations"

2022-05-13 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-05-13T09:48:01-04:00
New Revision: e0fcdf5496ca686c8cebb63b63af86e666b42ab3

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

LOG: Revert "In MSVC compatibility mode, friend function declarations behave as 
function declarations"

This reverts commit ad47114ad8500c78046161d492ac13a8e3e610eb.
See discussion on https://reviews.llvm.org/D124613.

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 
clang/test/SemaCXX/ms-friend-function-decl.cpp



diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d599cd619420b..315f328fca6a1 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9632,15 +9632,11 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, 
DeclContext *DC,
 }
 
 if (isFriend) {
-  // In MSVC mode for older versions of the standard, friend function
-  // declarations behave as declarations
-  bool PerformFriendInjection =
-  getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20;
   if (FunctionTemplate) {
-FunctionTemplate->setObjectOfFriendDecl(PerformFriendInjection);
+FunctionTemplate->setObjectOfFriendDecl();
 FunctionTemplate->setAccess(AS_public);
   }
-  NewFD->setObjectOfFriendDecl(PerformFriendInjection);
+  NewFD->setObjectOfFriendDecl();
   NewFD->setAccess(AS_public);
 }
 

diff  --git a/clang/test/SemaCXX/ms-friend-function-decl.cpp 
b/clang/test/SemaCXX/ms-friend-function-decl.cpp
deleted file mode 100644
index d146305800738..0
--- a/clang/test/SemaCXX/ms-friend-function-decl.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
-// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern 
%s
-#if __cplusplus < 202002L
-// expected-no-diagnostics
-#endif
-
-namespace ns {
-
-class C {
-public:
-  template 
-  friend void funtemp();
-
-  friend void fun();
-
-  void test() {
-::ns::fun(); // modern-error {{no member named 'fun' in namespace 'ns'}}
-
-// modern-error@+3 {{no member named 'funtemp' in namespace 'ns'}}
-// modern-error@+2 {{expected '(' for function-style cast or type 
construction}}
-// modern-error@+1 {{expected expression}}
-::ns::funtemp();
-  }
-};
-
-void fun() {
-}
-
-template 
-void funtemp() {}
-
-} // namespace ns
-
-class Glob {
-public:
-  friend void funGlob();
-
-  void test() {
-funGlob(); // modern-error {{use of undeclared identifier 'funGlob'}}
-  }
-};
-
-void funGlob() {
-}

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 2cda013a45edc..856010cd4d036 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -2658,10 +2658,7 @@ TEST_P(ImportFriendFunctions, Lookup) {
   getTuDecl("struct X { friend void f(); };", Lang_CXX03, "input0.cc");
   auto *FromD = FirstDeclMatcher().match(FromTU, 
FunctionPattern);
   ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
-FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   {
 auto FromName = FromD->getDeclName();
 auto *Class = FirstDeclMatcher().match(FromTU, 
ClassPattern);
@@ -2705,10 +2702,7 @@ TEST_P(ImportFriendFunctions, LookupWithProtoAfter) {
   auto *FromNormal =
   LastDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
-FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
 
@@ -2799,10 +2793,7 @@ TEST_P(ImportFriendFunctions, ImportFriendChangesLookup) 
{
 
   ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   
ASSERT_FALSE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  // Before CXX20, MSVC treats friend function declarations as function
-  // declarations
-  ASSERT_EQ(FromFriendTU->getLangOpts().MSVCCompat,
-FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  ASSERT_FALSE(FromFriendF->isInIdentifierNamespace(

[PATCH] D124613: In MSVC compatibility mode, friend function declarations behave as function declarations

2022-05-13 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks, reverted in e0fcdf5496ca686c8cebb63b63af86e666b42ab3 
 for now.

In D124613#3511098 , 
@frederic-tingaud-sonarsource wrote:

> I realized that this current patch does in fact mimic MSVC behavior up to its 
> mishandling of compliant code. I understand that it is not in the spirit of 
> clang's MSVC compatibility to have that, but the fixed version I was about to 
> propose would stray away from MSVC behavior, which doesn't really make sense 
> either.
> So instead I think the right approach should be to revert and see later 
> whether we could put it back under the hood of another flag.
> Is there currently a flag that could be used for "potentially C++ compliant 
> breaking MSVC compatibility"? If there isn't, would it make sense to propose 
> one?

I'm not sure we want to add this. The current setup seems to be working 
reasonably well, and adding a 3rd ms compat flag (in addition to 
-fms-extensions and -fms-compatibility) seems like a fairly expensive thing 
(from a testing pov) compared to the benefit: Your clients will have to update 
their code for this for msvc with c++20 anyways.

How difficult is it for your clients to make their code standards compliant for 
this particular thing? How many instances would they have to update?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124613

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


[PATCH] D125517: [Frontend] [Coroutines] Emit error when we found incompatible allocation function in promise_type

2022-05-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaCoroutine.cpp:1312
+
+  bool PromiseContainNew = [this, &PromiseType]() -> bool {
+DeclarationName NewName =

Slight preference to just have this as a part of LookupAllocationFunction.



Comment at: clang/lib/Sema/SemaCoroutine.cpp:1329
+if (PromiseContainNew)
+  S.FindAllocationFunctions(Loc, SourceRange(),
+/*NewScope*/ Sema::AFS_Class,

It looks like the NewScope is the only difference between these?  I wonder if 
it might be better off doing the PromiseContainsNew work to just set a variable 
to THAT and use it later?


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

https://reviews.llvm.org/D125517

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-13 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

Thank you for your support!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124726

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: steakhal, NoQ, mikhail.ramalho.
Herald added subscribers: manas, ASDenysPetrov, gamesh411, dkrupp, donat.nagy, 
Szelethus, 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.

Dependent patch adds UnarySymExpr, now I'd like to handle that for SMT
conversions like refutation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125547

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
  clang/test/Analysis/z3-crosscheck.c


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded 
from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -255,6 +255,20 @@
 llvm_unreachable("Unimplemented opcode");
   }
 
+  static inline llvm::SMTExprRef fromUnary(llvm::SMTSolverRef &Solver,
+   ASTContext &Ctx,
+   const llvm::SMTExprRef &Exp,
+   const UnaryOperator::Opcode Op) {
+switch (Op) {
+case UO_Minus:
+  return Solver->mkBVNeg(Exp);
+case UO_Not:
+  return Solver->mkBVNot(Exp);
+default:;
+}
+llvm_unreachable("Unimplemented opcode");
+  }
+
   /// Construct an SMTSolverRef from a QualType FromTy to a QualType ToTy,
   /// and their bit widths.
   static inline llvm::SMTExprRef fromCast(llvm::SMTSolverRef &Solver,
@@ -446,6 +460,17 @@
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+
+  QualType FromTy;
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &FromTy, hasComparison);
+
+  return fromUnary(Solver, Ctx, Exp, USE->getOpcode());
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -255,6 +255,20 @@
 llvm_unreachable("Unimplemented opcode");
   }
 
+  static inline llvm::SMTExprRef fromUnary(llvm::SMTSolverRef &Solver,
+   ASTContext &Ctx,
+   const llvm::SMTExprRef &Exp,
+   const UnaryOperator::Opcode Op) {
+switch (Op) {
+case UO_Minus:
+  return Solver->mkBVNeg(Exp);
+case UO_Not:
+  return Solver->mkBVNot(Exp);
+default:;
+}
+llvm_unreachable("Unimplemented opcode");
+  }
+
   /// Construct an SMTSolverRef from a QualType FromTy to a QualType ToTy,
   /// and their bit widths.
   static inline llvm::SMTExprRef fromCast(llvm::SMTSolverRef &Solver,
@@ -446,6 +460,17 @@
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+
+  QualType FromTy;
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &FromTy, hasComparison);
+
+  return fromUnary(Solver, Ctx, Exp, USE->getOpcode());
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);
_

[PATCH] D125524: [BoundV2] ArrayBoundV2 checks if the extent is tainted

2022-05-13 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp:208
 if (state_exceedsUpperBound && state_withinUpperBound) {
-  SVal ByteOffset = rawOffset.getByteOffset();
-  if (isTainted(state, ByteOffset)) {
+  if (isTainted(state, *upperboundToCheck)) {
 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,

steakhal wrote:
> martong wrote:
> > Could you please explain why we change `rawOffset` to `*upperBoundToCheck`? 
> > And perhaps the same explanation could infiltrate into the checker's code 
> > itself as a comment to `upperbound`.
> In the test attached you can see that the extent is tainted, not the offset.
> Thus checking the offset for taint won't suffice.
> The bug condition should depend on the calculation itself, which is basically 
> what is done here.
Okay makes sense, but then please update the comment
```
// If we are under constrained and the index variables are tainted, report.
```
to mention the extent as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125524

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


[PATCH] D105255: [MLIR][OpenMP] Added target data, exit data, and enter data operation definition for MLIR.

2022-05-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo updated this revision to Diff 429235.
abidmalikwaterloo edited the summary of this revision.
abidmalikwaterloo added a comment.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.

Rebase the patch and clean some formatting as needed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105255

Files:
  clang/lib/Testing/CMakeLists.txt
  mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
  mlir/test/Dialect/OpenMP/ops.mlir

Index: mlir/test/Dialect/OpenMP/ops.mlir
===
--- mlir/test/Dialect/OpenMP/ops.mlir
+++ mlir/test/Dialect/OpenMP/ops.mlir
@@ -377,6 +377,31 @@
 return
 }
 
+// CHECK-LABEL: omp_target_data
+func @omp_target_data (%if_cond : i1, %device : si32,  %data1: memref, %data2: memref) -> () {
+
+// CHECK: omp.target_data
+"omp.target_data"(%if_cond, %device, %data1, %data2) ({
+   // CHECK: omp.terminator
+   //omp.terminator
+}) {operand_segment_sizes = dense<[1,1,1,1,0,0,0,0,0,0,0,0]>: vector<12xi32> } : ( i1, si32, memref, memref ) -> ()
+
+// CHECK: omp.target_enter_data
+"omp.target_enter_data"(%if_cond, %device) ({
+   // CHECK: omp.terminator
+   //omp.terminator
+}) {operand_segment_sizes = dense<[1,1,0,0,0,0,0,0,0,0]>: vector<10xi32>, nowait } : ( i1, si32 ) -> ()
+
+// CHECK:omp.target_exit_data
+"omp.target_exit_data"(%if_cond, %device)
+   {operand_segment_sizes = dense<[1,1,0,0,0,0,0,0,0,0]>: vector<10xi32>, nowait } : ( i1, si32 ) -> ()
+
+// CHECK: omp.barrier
+omp.barrier
+
+return
+}
+
 // CHECK: omp.reduction.declare
 // CHECK-LABEL: @add_f32
 // CHECK: : f32
Index: mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
===
--- mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -562,6 +562,177 @@
   let assemblyFormat = "attr-dict";
 }
 
+//===-===//
+// 2.12.2 target data Construct 
+//===-===//
+
+def Target_Data: OpenMP_Op<"target_data", [AttrSizedOperandSegments]>{
+  let summary = "target data construct";
+  let description = [{
+Map variables to a device data environment for the extent of the region.
+
+The omp target data directive maps variables to a device data 
+environment, and defines the lexical scope of the data environment 
+that is created. The omp target data directive can reduce data copies 
+to and from the offloading device when multiple target regions are using 
+the same data.
+
+The optional $if_expr parameter specifies a boolean result of a
+conditional check. If this value is 1 or is not provided then the target
+region runs on a device, if it is 0 then the target region is executed 
+on the host device.
+
+The optional $device parameter specifies the device number for the target 
+region.
+
+The optional $use_device_ptr specifies the device pointers to the 
+corresponding list items in the device data environment
+	
+The optional $use_device_addr specifies the adress of the objects in the 
+device data enviornment
+
+The $map_operands specifies operands with no map type
+
+The $map_to_operands specifies operands with  map type "to"
+
+The $map_from_operands specifies operands with map type "from"
+
+The $map_alloc_operands specifies operands with map type "alloc"
+
+The $map_release_operands specifies operands with map type "release"
+
+The $map_delete_operands specifies operands with map type "delete"
+
+The $map_type_modifier vector specifies the modifier for each map type 
+operand
+  }];
+
+  let arguments = (ins Optional:$if_expr,
+ Optional:$device,
+ Variadic:$use_device_ptr,
+ Variadic:$use_device_addr,
+ Variadic:$map_operands,
+ Variadic:$map_to_operands,
+ Variadic:$map_from_operands,
+ Variadic:$map_to_from_operands,
+ Variadic:$map_alloc_operands,
+ Variadic:$map_release_operands,
+ Variadic:$map_delete_operands,
+ VectorOf<[AnyInteger]>:$map_type_modifier);
+
+  let regions = (region AnyRegion:$region);
+}
+
+//===-===//
+// 2.12.3 target enter data Construct
+//===-===//
+
+def Target_EnterDataOp: OpenMP_Op<"target_enter_data", 
+ [AttrSizedOperandSegments]>{
+  let  summary = "target enter data construct";
+  let description = [{
+The target enter data directive specifies that variables are mapped to 
+a device data environment. The target enter

[PATCH] D125429: Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-13 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Hmm, didn't see this on Linux. I'll try to disambiguate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125429

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a subscriber: arphaman.
dexonsmith added a comment.

In D122895#3511376 , @aaron.ballman 
wrote:

> In D122895#3511312 , @aaron.ballman 
> wrote:
>
>> However, I think the blocks behavior is a bug based on this: 
>> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L728
>>  and I'd be more than happy to fix that, as I'm not checking that condition 
>> here: 
>> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L5579
>>  which seems like a pretty obvious thing to be checking for before warning 
>> about not having a strict prototype.
>
> I fixed this false positive bug in 4be105c98a9c7e083cd878ee1751e11160b97b4a 
> , so 
> blocks (and OpenCL) behavior should now be improved.

Thanks! I think that's the bigger issue of the two. @steven_wu or @arphaman 
will have more context though.

In D122895#3511312 , @aaron.ballman 
wrote:

> In D122895#3510165 , @dexonsmith 
> wrote:
>
>> For additional context to my questions above, even though open source clang 
>> hasn't been using `-Wstrict-prototypes`, Xcode has had it on-by-default in 
>> new projects since sometime in 2017, with project modernizations to turn it 
>> on for old projects.
>
> Thanks, that's very good to know! And also, thank you for raising the 
> questions here, I appreciate the discussion.
>
>> Warning on block and function definitions such as `^(){}` and `void f1() 
>> {}`, which are pedantically lacking a prototype but the compiler knows there 
>> are exactly zero parameters, would be super noisy for users.
>>
>> Unless I read the RFC too quickly, it doesn't look like it's adding any 
>> value, since these aren't going to change meaning. Is it possible to revert 
>> this part of the change?
>
> `-Wstrict-prototypes` is now a pedantic deprecation warning that fires any 
> time you form a function type which has no prototype, which was discussed in 
> the RFC 
> (https://discourse.llvm.org/t/rfc-enabling-wstrict-prototypes-by-default-in-c/60521/38?u=aaronballman):
>
>   Change -Wstrict-prototypes to diagnose functions without a prototype that 
> don’t change behavior in C2x, it remains off-by-default but is automatically 
> enabled by -pedantic as it’s still warning the user about a deprecation.
>
> However, I think the blocks behavior is a bug based on this: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L728
>  and I'd be more than happy to fix that, as I'm not checking that condition 
> here: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L5579
>  which seems like a pretty obvious thing to be checking for before warning 
> about not having a strict prototype.
>
> But I'm pretty insistent on warning about the other case as it does use 
> functions without a prototype and we need *some* blanket warning for use of a 
> deprecated feature for folks who want to be strictly conforming. It sounds 
> like Apple may want to no longer enable `-Wstrict-prototypes` by default as 
> it's shifted to be a more pedantic warning than it was before -- would that 
> be a viable option for you (can you use project modernizations to turn it 
> back off for old projects)?

Sure, I'm all for adding a new warning for users that want a pedantic warning. 
Can it be put behind a separate flag, such as `-Wstrict-prototypes-pedantic`, 
which isn't triggered by `-Wstrict-prototypes`?

Previously, `-Wstrict-prototypes` was useful for preventing actual bugs in code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

minor nits;
Thanks




Comment at: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h:258
 
+  static inline llvm::SMTExprRef fromUnary(llvm::SMTSolverRef &Solver,
+   ASTContext &Ctx,

I would prefer the `fromUnOp` similarly to how `fromBinOp` is called.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h:467-469
+  QualType FromTy;
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &FromTy, hasComparison);

If you discard the `FromTy`, you could have passed a nullptr there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

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


[clang] d364307 - Remove a stale FIXME comment; NFC

2022-05-13 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-13T10:23:47-04:00
New Revision: d364307542d19ec5b0f4f5ee9adc5a3b7c8639a5

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

LOG: Remove a stale FIXME comment; NFC

Added: 


Modified: 
clang/test/Sema/warn-strict-prototypes.m

Removed: 




diff  --git a/clang/test/Sema/warn-strict-prototypes.m 
b/clang/test/Sema/warn-strict-prototypes.m
index 38e4ffaba767..ba0f9e6101b6 100644
--- a/clang/test/Sema/warn-strict-prototypes.m
+++ b/clang/test/Sema/warn-strict-prototypes.m
@@ -14,9 +14,6 @@ void foo() { // expected-warning {{a function declaration 
without a prototype is
   void (^block)() = // expected-warning {{a block declaration without a 
prototype is deprecated}}
 ^void(int arg) { // no warning
   };
-  // FIXME: this should say "a block declaration" instead, but block literal
-  // expressions do not track their full declarator information, so we don't
-  // know it's a block when diagnosing.
   void (^block2)(void) = ^void() {
   };
   void (^block3)(void) = ^ { // no warning



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


[clang] 25862f5 - Try to disambiguate between overloads on Mac

2022-05-13 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2022-05-13T16:29:02+02:00
New Revision: 25862f53cce966cef2957825095861dec631d4f1

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

LOG: Try to disambiguate between overloads on Mac

Presumably Mac has a different understanding of how long `long` is.
Should fix a build error introduced by D125429 that's not visible on
other architectures.

Added: 


Modified: 
clang/lib/AST/CommentParser.cpp

Removed: 




diff  --git a/clang/lib/AST/CommentParser.cpp b/clang/lib/AST/CommentParser.cpp
index 7bac1fb99b88..d78b3ace2bb8 100644
--- a/clang/lib/AST/CommentParser.cpp
+++ b/clang/lib/AST/CommentParser.cpp
@@ -414,7 +414,7 @@ InlineCommandComment *Parser::parseInlineCommand() {
   if (Args.size() < Info->NumArgs) {
 Diag(CommandTok.getEndLocation().getLocWithOffset(1),
  diag::warn_doc_inline_command_not_enough_arguments)
-<< CommandTok.is(tok::at_command) << Info->Name << Args.size()
+<< CommandTok.is(tok::at_command) << Info->Name << 
(uint64_t)Args.size()
 << Info->NumArgs
 << SourceRange(CommandTok.getLocation(), CommandTok.getEndLocation());
   }



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


[PATCH] D125532: [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal marked an inline comment as done.
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp:268
+  QualType Ty = C.getSVal(Arg).getType(C.getASTContext());
+  reportBug(Ty.getAsString(), C);
+}

martong wrote:
> Would it make sense to call `Ty->dump(OS)` to a stream and then report the 
> string of the stream?
> That way we could see some more information. Or perhaps that could be done in 
> another introspection function.
It's way harder to match on such dumps. Those contain pointer addresses all 
over the place, making FileChecking a nightmare.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125532

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

The warnings for this case aren't great:

  int foo();
  
  int
  foo(int arg) {
return 5;
  }

results in:

  /tmp/test.c:1:5: warning: a function declaration without a prototype is 
deprecated in all versions of C and is not supported in C2x 
[-Wdeprecated-non-prototype]
  int foo();
  ^
  void
  /tmp/test.c:4:1: warning: a function declaration without a prototype is 
deprecated in all versions of C and is not supported in C2x 
[-Wdeprecated-non-prototype]
  foo(int arg) {
  ^

Two warnings for the problem, instead of a warning and a note, plus, the fix-it 
hint is incorrect, which the compiler should know, since we see that there are 
arguments expected.

I'd expect more like:

  /tmp/test.c:1:5: warning: a function declaration without a prototype is 
deprecated in all versions of C and is not supported in C2x 
[-Wdeprecated-non-prototype]
  int foo();
  /tmp/test.c:4:1: note: subsequent declaration specifies arguments.
  foo(int arg) {
  ^


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125094: [ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records

2022-05-13 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas updated this revision to Diff 429237.
pratlucas added a comment.

Adding frame access test coverage, adding check for FrameSetup flag and 
adjusting calculation of FP value.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125094

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
  llvm/lib/Target/ARM/ARMCallingConv.td
  llvm/lib/Target/ARM/ARMFrameLowering.cpp
  llvm/lib/Target/ARM/ARMMachineFunctionInfo.h
  llvm/lib/Target/ARM/ARMSubtarget.h
  llvm/lib/Target/ARM/Thumb1FrameLowering.cpp
  llvm/test/CodeGen/ARM/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/ARM/frame-chain.ll
  llvm/test/CodeGen/Thumb/frame-access.ll
  llvm/test/CodeGen/Thumb/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/Thumb/frame-chain.ll

Index: llvm/test/CodeGen/Thumb/frame-chain.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Thumb/frame-chain.ll
@@ -0,0 +1,305 @@
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all | FileCheck %s --check-prefixes=FP,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf | FileCheck %s --check-prefixes=FP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none | FileCheck %s --check-prefixes=NOFP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP-AAPCS
+
+define dso_local noundef i32 @leaf(i32 noundef %0) {
+; LEAF-FP-LABEL: leaf:
+; LEAF-FP:   @ %bb.0:
+; LEAF-FP-NEXT:.pad #4
+; LEAF-FP-NEXT:sub sp, #4
+; LEAF-FP-NEXT:str r0, [sp]
+; LEAF-FP-NEXT:adds r0, r0, #4
+; LEAF-FP-NEXT:add sp, #4
+; LEAF-FP-NEXT:bx lr
+;
+; LEAF-FP-AAPCS-LABEL: leaf:
+; LEAF-FP-AAPCS:   @ %bb.0:
+; LEAF-FP-AAPCS-NEXT:.save {lr}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:mov lr, r11
+; LEAF-FP-AAPCS-NEXT:.save {r11}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-FP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-FP-AAPCS-NEXT:.pad #4
+; LEAF-FP-AAPCS-NEXT:sub sp, #4
+; LEAF-FP-AAPCS-NEXT:str r0, [sp]
+; LEAF-FP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-FP-AAPCS-NEXT:add sp, #4
+; LEAF-FP-AAPCS-NEXT:pop {lr}
+; LEAF-FP-AAPCS-NEXT:mov r11, lr
+; LEAF-FP-AAPCS-NEXT:pop {r1}
+; LEAF-FP-AAPCS-NEXT:bx r1
+;
+; LEAF-NOFP-LABEL: leaf:
+; LEAF-NOFP:   @ %bb.0:
+; LEAF-NOFP-NEXT:.pad #4
+; LEAF-NOFP-NEXT:sub sp, #4
+; LEAF-NOFP-NEXT:str r0, [sp]
+; LEAF-NOFP-NEXT:adds r0, r0, #4
+; LEAF-NOFP-NEXT:add sp, #4
+; LEAF-NOFP-NEXT:bx lr
+;
+; LEAF-NOFP-AAPCS-LABEL: leaf:
+; LEAF-NOFP-AAPCS:   @ %bb.0:
+; LEAF-NOFP-AAPCS-NEXT:.save {lr}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov lr, r11
+; LEAF-NOFP-AAPCS-NEXT:.save {r11}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-NOFP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-NOFP-AAPCS-NEXT:.pad #4
+; LEAF-NOFP-AAPCS-NEXT:sub sp, #4
+; LEAF-NOFP-AAPCS-NEXT:str r0, [sp]
+; LEAF-NOFP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-NOFP-AAPCS-NEXT:add sp, #4
+; LEAF-NOFP-AAPCS-NEXT:pop {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov r11, lr
+; LEAF-NOFP-AAPCS-NEXT:pop {r1}
+; LEAF-NOFP-AAPCS-NEXT:bx r1
+  %2 = alloca i32, align 4
+  store i32 %0, i32* %2, align 4
+  %3 = load i32, i32* %2, align 4
+  %4 = add nsw i32 %3, 4
+  ret i32 %4
+}
+
+define dso_local noundef i32 @non_leaf(i32 noundef %0) {
+; FP-LABEL: non_leaf:
+; FP:   @ %bb.0:
+; FP-NEXT:.save {r7, lr}
+; FP-NEXT:push {r7, lr}
+; FP-NEXT:.setfp r7, sp
+; FP-NEXT:add r7, sp, #0
+; FP-NEXT:.pad #8
+; FP-NEXT:sub sp, #8
+; FP-NEXT:str r0, [sp, #4]
+; FP-NEXT:bl leaf
+; FP-NEXT:adds r0, r0, #1
+; FP-NEXT:add sp, #8
+; FP-NEXT:pop {r7}
+; FP-NEXT:pop {r1}
+; FP-NEXT: 

[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D122895#3511611 , @dexonsmith 
wrote:

> Previously, `-Wstrict-prototypes` was useful for preventing actual bugs in 
> code.

For example, it's important to have a warning that catches code like this:

  void f1(void (^block)());
  
  void f2(void) {
f1(^(int x) { /* do something with x */ });
  }

without triggering in cases that are pedantic.

(It also seems unfortunate to regress the false positive rate of this 
diagnostic before `-fstrict-prototypes` is available.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125429: Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-13 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

So we have overloads

  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 
int I);
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 
int64_t I);
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 
unsigned I);
  inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 
uint64_t I);

And it appears that `unsigned long` does not have a clear favorite here. Is 
that because `long` is 32-bit like on Windows, but at the same time it's not 
the same as `unsigned` which is also 32-bit? Could we resolve this somehow so 
that we don't have the next person writing inconspicuous code to run into this?

Perhaps we should overload on `(u)int32_t` instead `int`/`unsigned`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125429

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3511611 , @dexonsmith 
wrote:

> Sure, I'm all for adding a new warning for users that want a pedantic 
> warning. Can it be put behind a separate flag, such as 
> `-Wstrict-prototypes-pedantic`, which isn't triggered by 
> `-Wstrict-prototypes`?
>
> Previously, `-Wstrict-prototypes` was useful for preventing actual bugs in 
> code.

Doing that would then make `-Wstrict-prototypes` effectively a no-op (it would 
still control `-Wdeprecated-non-prototype` I suppose?), but there were also 
people who enabled `-Wstrict-prototypes` because they wanted the pedantic 
aspects of the warning in cases where it was firing, and those folks would then 
be losing warning coverage without knowing it. For example:

  void f(){}

In prior versions of Clang with `-Wstrict-prototypes` this would issue a `this 
old-style function definition is not preceded by a prototype` diagnostic, but 
would now be silenced entirely unless the user knew to turn on a different flag.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D125333: [OpenMP] Use the new OpenMP device static library when doing LTO

2022-05-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LG, nice!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125333

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


[PATCH] D125094: [ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records

2022-05-13 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas marked an inline comment as done.
pratlucas added inline comments.



Comment at: llvm/lib/Target/ARM/Thumb1FrameLowering.cpp:242
+  // Find last push instruction for GPRCS2 - spilling of high registers
+  // (r8-r11) could consist of multiple tPUSH and tMOVr instructions.
+  while (true) {

efriedma wrote:
> It seems sort of fragile to assume the entry block doesn't contain any tPUSH 
> instructions; we can use them in places other than the prologue.  Can we use 
> the FrameSetup flag?
This approach is fragile indeed, I guess the fact that high reg spills are less 
usual has helpep it go unnoticed for so long.
I've added the checks for the FrameSetup flag to make sure it doesn't run over 
into unrelated instructions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125094

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


[PATCH] D125395: [analyzer][solver] Handle UnarySymExpr in RangeConstraintSolver

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125395

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3511632 , @jyknight wrote:

> The warnings for this case aren't great:
>
>   int foo();
>   
>   int
>   foo(int arg) {
> return 5;
>   }

Yeah, that's not ideal, I'm looking into it to see if I can improve that 
scenario or not. Thankfully, IMO, such code is likely to be extremely rare. 
Most people writing that declaration either expect an arbitrary number of args 
(they really don't want the prototype) and so the definition is extremely 
suspect that it only accepts one, or they wrote the declaration assuming it 
would accept *no* args (the C++ behavior) and then the definition becomes 
flat-out a bug. Do you have evidence this code pattern appears with some 
frequency?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-05-13 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D122895#3511649 , @aaron.ballman 
wrote:

> In D122895#3511611 , @dexonsmith 
> wrote:
>
>> Sure, I'm all for adding a new warning for users that want a pedantic 
>> warning. Can it be put behind a separate flag, such as 
>> `-Wstrict-prototypes-pedantic`, which isn't triggered by 
>> `-Wstrict-prototypes`?
>>
>> Previously, `-Wstrict-prototypes` was useful for preventing actual bugs in 
>> code.
>
> Doing that would then make `-Wstrict-prototypes` effectively a no-op (it 
> would still control `-Wdeprecated-non-prototype` I suppose?),

Is it necessary to make `-Wstrict-prototypes` weaker in order to move the newer 
more pedantic cases to a different name?

> but there were also people who enabled `-Wstrict-prototypes` because they 
> wanted the pedantic aspects of the warning in cases where it was firing, and 
> those folks would then be losing warning coverage without knowing it. For 
> example:
>
>   void f(){}
>
> In prior versions of Clang with `-Wstrict-prototypes` this would issue a 
> `this old-style function definition is not preceded by a prototype` 
> diagnostic, but would now be silenced entirely unless the user knew to turn 
> on a different flag.

Oh, I thought that would catch bugs like this:

  void longfunctionname(){}
  void longfunctionnames(int x){ /* do something with x */ }
  
  void g(void) {
longfunctionname(7); // oops, meant to call longfunctionnames().
  }

but if it's entirely pedantic (if the call to `longfunctionname(7)` would fail 
to compile) then I agree it'd be better to silence it unless someone asks for 
`-pedantic`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[clang-tools-extra] 7e3ea55 - [clang-tidy] modernize-deprecated-headers check should respect extern "C" blocks

2022-05-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-13T16:54:13+02:00
New Revision: 7e3ea55da88a9d7feaa22f29d51f89fd0152a189

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

LOG: [clang-tidy] modernize-deprecated-headers check should respect extern "C" 
blocks

The check should not report includes wrapped by `extern "C" { ... }` blocks,
such as:

```lang=C++
#ifdef __cplusplus
extern "C" {
#endif

#include "assert.h"

#ifdef __cplusplus
}
#endif
```

This pattern comes up sometimes in header files designed to be consumed
by both C and C++ source files.
The check now reports false reports when the header file is consumed by
a C++ translation unit.

In this change, I'm not emitting the reports immediately from the
`PPCallback`, rather aggregating them for further processing.
After all preprocessing is done, the matcher will be called on the
`TranslationUnitDecl`, ensuring that the check callback is called only
once.

Within that callback, I'm recursively visiting each decls, looking for
`LinkageSpecDecls` which represent the `extern "C"` specifier.
After this, I'm dropping all the reports coming from inside of it.
After the visitation is done, I'm emitting the reports I'm left with.

For performance reasons, I'm sorting the `IncludeMarkers` by their
corresponding locations.
This makes the scan `O(log(N)` when looking up the `IncludeMarkers`
affected by the given `extern "C"` block. For this, I'm using
`lower_bound()` and `upper_bound()`.

Reviewed By: whisperity

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-deprecated-headers/mylib.h

clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-extern-c.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
index 0b44bdaafe23..dd991221faab 100644
--- a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
@@ -7,23 +7,37 @@
 
//===--===//
 
 #include "DeprecatedHeadersCheck.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 
+#include 
 #include 
 
 namespace clang {
 namespace tidy {
 namespace modernize {
+namespace detail {
+bool operator<(const IncludeMarker &LHS, const IncludeMarker &RHS) {
+  return LHS.DecomposedDiagLoc < RHS.DecomposedDiagLoc;
+}
+bool operator<(const IncludeMarker &LHS,
+   const std::pair &RHS) {
+  return LHS.DecomposedDiagLoc < RHS;
+}
+bool operator<(const std::pair &LHS,
+   const IncludeMarker &RHS) {
+  return LHS < RHS.DecomposedDiagLoc;
+}
 
-namespace {
 class IncludeModernizePPCallbacks : public PPCallbacks {
 public:
-  explicit IncludeModernizePPCallbacks(ClangTidyCheck &Check,
-   LangOptions LangOpts);
+  explicit IncludeModernizePPCallbacks(DeprecatedHeadersCheck &Check,
+   LangOptions LangOpts,
+   const SourceManager &SM);
 
   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
   StringRef FileName, bool IsAngled,
@@ -33,22 +47,98 @@ class IncludeModernizePPCallbacks : public PPCallbacks {
   SrcMgr::CharacteristicKind FileType) override;
 
 private:
-  ClangTidyCheck &Check;
+  DeprecatedHeadersCheck &Check;
   LangOptions LangOpts;
   llvm::StringMap CStyledHeaderToCxx;
   llvm::StringSet<> DeleteHeaders;
+  const SourceManager &SM;
+};
+
+class ExternCRefutationVisitor
+: public RecursiveASTVisitor {
+  std::vector &IncludesToBeProcessed;
+  const SourceManager &SM;
+
+public:
+  ExternCRefutationVisitor(std::vector &IncludesToBeProcessed,
+   SourceManager &SM)
+  : IncludesToBeProcessed(IncludesToBeProcessed), SM(SM) {}
+  bool shouldWalkTypesOfTypeLocs() const { return false; }
+  bool shouldVisitLambdaBody() const { return false; }
+
+  bool VisitLinkageSpecDecl(LinkageSpecDecl *LinkSpecDecl) const {
+if (LinkSpecDecl->getLanguage() != LinkageSpecDecl::lang_c ||
+!LinkSpecDecl->hasBraces())
+  return true;
+
+auto ExternCBlockBegin =
+SM.getDecomposedExpansionLoc(LinkSpecDecl->getBeginLoc());
+auto ExternCBlockEnd

[PATCH] D125209: [clang-tidy] modernize-deprecated-headers check should respect extern "C" blocks

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7e3ea55da88a: [clang-tidy] modernize-deprecated-headers 
check should respect extern "C" blocks (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125209

Files:
  clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
  clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-deprecated-headers/mylib.h
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-extern-c.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-extern-c.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-extern-c.cpp
@@ -0,0 +1,53 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s modernize-deprecated-headers %t \
+// RUN:   -- -header-filter='.*' -system-headers \
+// RUN:  -extra-arg-before=-isystem%S/Inputs/modernize-deprecated-headers
+
+#define EXTERN_C extern "C"
+
+extern "C++" {
+// We should still have the warnings here.
+#include 
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: including 'stdbool.h' has no effect in C++; consider removing it [modernize-deprecated-headers]
+}
+
+#include 
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: inclusion of deprecated C++ header 'assert.h'; consider using 'cassert' instead [modernize-deprecated-headers]
+// CHECK-FIXES: {{^}}#include {{$}}
+
+#include 
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: including 'stdbool.h' has no effect in C++; consider removing it [modernize-deprecated-headers]
+
+#include 
+// CHECK-MESSAGES: mylib.h:1:10: warning: inclusion of deprecated C++ header 'assert.h'; consider using 'cassert' instead [modernize-deprecated-headers]
+
+namespace wrapping {
+extern "C" {
+#include   // no-warning
+#include// no-warning
+#include  // no-warning
+}
+} // namespace wrapping
+
+extern "C" {
+namespace wrapped {
+#include   // no-warning
+#include// no-warning
+#include  // no-warning
+} // namespace wrapped
+}
+
+namespace wrapping {
+extern "C" {
+namespace wrapped {
+#include   // no-warning
+#include// no-warning
+#include  // no-warning
+} // namespace wrapped
+}
+} // namespace wrapping
+
+EXTERN_C {
+#include   // no-warning
+#include// no-warning
+#include  // no-warning
+}
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-deprecated-headers/mylib.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-deprecated-headers/mylib.h
@@ -0,0 +1 @@
+#include "assert.h"
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -170,6 +170,11 @@
   ` involving assignments in
   conditions. This fixes `Issue 35853 `_.
 
+- Fixed a false positive in :doc:`modernize-deprecated-headers
+  ` involving including
+  C header files from C++ files wrapped by ``extern "C" { ... }`` blocks.
+  Such includes will be ignored by now.
+
 - Improved :doc:`performance-inefficient-vector-operation
   ` to work when
   the vector is a member of a structure.
Index: clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
+++ clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
@@ -15,6 +15,22 @@
 namespace tidy {
 namespace modernize {
 
+namespace detail {
+class IncludeModernizePPCallbacks;
+class ExternCRefutationVisitor;
+struct IncludeMarker {
+  std::string Replacement;
+  StringRef FileName;
+  SourceRange ReplacementRange;
+  std::pair DecomposedDiagLoc;
+};
+bool operator<(const IncludeMarker &LHS, const IncludeMarker &RHS);
+bool operator<(const IncludeMarker &LHS,
+   const std::pair &RHS);
+bool operator<(const std::pair &LHS,
+   const IncludeMarker &RHS);
+} // namespace detail
+
 /// This check replaces deprecated C library headers with their C++ STL
 /// alternatives.
 ///
@@ -41,6 +57,14 @@
   }
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void onEndOfTranslationUnit() override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  friend class detail::IncludeModernizePPCallbacks;
+  friend class detail::ExternCRefutationVisitor;
+  std::vector IncludesToBeProcessed;
 };
 
 } // namespace moderniz

[PATCH] D125209: [clang-tidy] modernize-deprecated-headers check should respect extern "C" blocks

2022-05-13 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests: http://45.33.8.238/linux/76033/step_8.txt

Please take a look and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125209

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


[clang] d5ffc1e - [analyzer][NFC] Tighten some of the SValBuilder return types

2022-05-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-13T17:04:34+02:00
New Revision: d5ffc1ed8b629cd04bbd46ee6981529d9dafa48f

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

LOG: [analyzer][NFC] Tighten some of the SValBuilder return types

This is purely a cosmetic change.

Reviewed By: martong

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index 8452cf0a..d0bbf1750d7e 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -106,7 +106,7 @@ class SValBuilder {
   /// \param CastTy -- QualType, which `V` shall be cast to.
   /// \return SVal with simplified cast expression.
   /// \note: Currently only support integral casts.
-  SVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy);
+  nonloc::SymbolVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy);
 
 public:
   SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
@@ -340,17 +340,19 @@ class SValBuilder {
 return nonloc::LocAsInteger(BasicVals.getPersistentSValWithData(loc, 
bits));
   }
 
-  NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-const llvm::APSInt& rhs, QualType type);
+  nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
+   const llvm::APSInt &rhs, QualType type);
 
-  NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op,
-const SymExpr *lhs, QualType type);
+  nonloc::SymbolVal makeNonLoc(const llvm::APSInt &rhs,
+   BinaryOperator::Opcode op, const SymExpr *lhs,
+   QualType type);
 
-  NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-const SymExpr *rhs, QualType type);
+  nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
+   const SymExpr *rhs, QualType type);
 
   /// Create a NonLoc value for cast.
-  NonLoc makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy);
+  nonloc::SymbolVal makeNonLoc(const SymExpr *operand, QualType fromTy,
+   QualType toTy);
 
   nonloc::ConcreteInt makeTruthVal(bool b, QualType type) {
 return nonloc::ConcreteInt(BasicVals.getTruthValue(b, type));
@@ -363,7 +365,7 @@ class SValBuilder {
   /// Create NULL pointer, with proper pointer bit-width for given address
   /// space.
   /// \param type pointer type.
-  Loc makeNullWithType(QualType type) {
+  loc::ConcreteInt makeNullWithType(QualType type) {
 // We cannot use the `isAnyPointerType()`.
 assert((type->isPointerType() || type->isObjCObjectPointerType() ||
 type->isBlockPointerType() || type->isNullPtrType() ||
@@ -379,19 +381,19 @@ class SValBuilder {
 return loc::ConcreteInt(BasicVals.getZeroWithTypeSize(type));
   }
 
-  Loc makeLoc(SymbolRef sym) {
+  loc::MemRegionVal makeLoc(SymbolRef sym) {
 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
   }
 
-  Loc makeLoc(const MemRegion* region) {
+  loc::MemRegionVal makeLoc(const MemRegion *region) {
 return loc::MemRegionVal(region);
   }
 
-  Loc makeLoc(const AddrLabelExpr *expr) {
+  loc::GotoLabel makeLoc(const AddrLabelExpr *expr) {
 return loc::GotoLabel(expr->getLabel());
   }
 
-  Loc makeLoc(const llvm::APSInt& integer) {
+  loc::ConcreteInt makeLoc(const llvm::APSInt &integer) {
 return loc::ConcreteInt(BasicVals.getValue(integer));
   }
 
@@ -402,7 +404,7 @@ class SValBuilder {
   /// Make an SVal that represents the given symbol. This follows the 
convention
   /// of representing Loc-type symbols (symbolic pointers and references)
   /// as Loc values wrapping the symbol rather than as plain symbol values.
-  SVal makeSymbolVal(SymbolRef Sym) {
+  DefinedSVal makeSymbolVal(SymbolRef Sym) {
 if (Loc::isLocType(Sym->getType()))
   return makeLoc(Sym);
 return nonloc::SymbolVal(Sym);

diff  --git a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
index 12b46426c027..ea66bb3780f6 100644
--- a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -74,8 +74,10 @@ DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) 
{
   return UnknownVal();
 }
 
-NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-const

[PATCH] D125463: [analyzer][NFC] Tighten some of the SValBuilder return types

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd5ffc1ed8b62: [analyzer][NFC] Tighten some of the 
SValBuilder return types (authored by steakhal).

Changed prior to commit:
  https://reviews.llvm.org/D125463?vs=428918&id=429244#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125463

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp

Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -74,8 +74,10 @@
   return UnknownVal();
 }
 
-NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-const llvm::APSInt& rhs, QualType type) {
+nonloc::SymbolVal SValBuilder::makeNonLoc(const SymExpr *lhs,
+  BinaryOperator::Opcode op,
+  const llvm::APSInt &rhs,
+  QualType type) {
   // The Environment ensures we always get a persistent APSInt in
   // BasicValueFactory, so we don't need to get the APSInt from
   // BasicValueFactory again.
@@ -84,23 +86,24 @@
   return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
 }
 
-NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
-   BinaryOperator::Opcode op, const SymExpr *rhs,
-   QualType type) {
+nonloc::SymbolVal SValBuilder::makeNonLoc(const llvm::APSInt &lhs,
+  BinaryOperator::Opcode op,
+  const SymExpr *rhs, QualType type) {
   assert(rhs);
   assert(!Loc::isLocType(type));
   return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
 }
 
-NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-   const SymExpr *rhs, QualType type) {
+nonloc::SymbolVal SValBuilder::makeNonLoc(const SymExpr *lhs,
+  BinaryOperator::Opcode op,
+  const SymExpr *rhs, QualType type) {
   assert(lhs && rhs);
   assert(!Loc::isLocType(type));
   return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
 }
 
-NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
-   QualType fromTy, QualType toTy) {
+nonloc::SymbolVal SValBuilder::makeNonLoc(const SymExpr *operand,
+  QualType fromTy, QualType toTy) {
   assert(operand);
   assert(!Loc::isLocType(toTy));
   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
@@ -563,8 +566,7 @@
   std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
   if (!IsNotTruncated && IsTruncated) {
 // Symbol is truncated so we evaluate it as a cast.
-NonLoc CastVal = makeNonLoc(se, originalTy, castTy);
-return CastVal;
+return makeNonLoc(se, originalTy, castTy);
   }
   return evalCast(val, castTy, originalTy);
 }
@@ -1009,7 +1011,7 @@
   return V;
 }
 
-SVal clang::ento::SValBuilder::simplifySymbolCast(nonloc::SymbolVal V,
+nonloc::SymbolVal SValBuilder::simplifySymbolCast(nonloc::SymbolVal V,
   QualType CastTy) {
   // We use seven conditions to recognize a simplification case.
   // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type - `R`,
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -106,7 +106,7 @@
   /// \param CastTy -- QualType, which `V` shall be cast to.
   /// \return SVal with simplified cast expression.
   /// \note: Currently only support integral casts.
-  SVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy);
+  nonloc::SymbolVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy);
 
 public:
   SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
@@ -340,17 +340,19 @@
 return nonloc::LocAsInteger(BasicVals.getPersistentSValWithData(loc, bits));
   }
 
-  NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
-const llvm::APSInt& rhs, QualType type);
+  nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
+   const llvm::APSInt &rhs, QualType type);
 
-  NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op,
-const SymExpr *lhs, QualType type);
+  nonloc::SymbolVal makeNonLoc(const llvm::APSInt &rhs,
+   BinaryOperator::

[clang] a1025e6 - [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

2022-05-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-13T17:07:58+02:00
New Revision: a1025e6ffe9b43afb9c6569423c4ea1d0ba8ecf2

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

LOG: [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

In some rare cases the type of an SVal might be interesting.
This introspection function exposes this information in tests.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
clang/test/Analysis/expr-inspection.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
index 9253e9e6abfe..ea72d1dbb317 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@ class ExprInspectionChecker
   void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
   void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
+  void analyzerDumpSValType(const CallExpr *CE, CheckerContext &C) const;
   void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
   void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
   void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
@@ -98,6 +99,8 @@ bool ExprInspectionChecker::evalCall(const CallEvent &Call,
 &ExprInspectionChecker::analyzerDumpExtent)
   .Case("clang_analyzer_dumpElementCount",
 &ExprInspectionChecker::analyzerDumpElementCount)
+  .StartsWith("clang_analyzer_dumpSvalType",
+  &ExprInspectionChecker::analyzerDumpSValType)
   .StartsWith("clang_analyzer_dump",
   &ExprInspectionChecker::analyzerDump)
   .Case("clang_analyzer_getExtent",
@@ -255,6 +258,16 @@ void ExprInspectionChecker::analyzerExplain(const CallExpr 
*CE,
   reportBug(Ex.Visit(V), C);
 }
 
+void ExprInspectionChecker::analyzerDumpSValType(const CallExpr *CE,
+ CheckerContext &C) const {
+  const Expr *Arg = getArgExpr(CE, C);
+  if (!Arg)
+return;
+
+  QualType Ty = C.getSVal(Arg).getType(C.getASTContext());
+  reportBug(Ty.getAsString(), C);
+}
+
 void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
  CheckerContext &C) const {
   const Expr *Arg = getArgExpr(CE, C);

diff  --git a/clang/test/Analysis/expr-inspection.c 
b/clang/test/Analysis/expr-inspection.c
index 33c90f95bc78..e6dbbabff0ff 100644
--- a/clang/test/Analysis/expr-inspection.c
+++ b/clang/test/Analysis/expr-inspection.c
@@ -6,12 +6,16 @@
 
 void clang_analyzer_dump(int x);
 void clang_analyzer_dump_pointer(int *p);
+void clang_analyzer_dumpSvalType(int x);
+void clang_analyzer_dumpSvalType_pointer(int *p);
 void clang_analyzer_printState(void);
 void clang_analyzer_numTimesReached(void);
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
   clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dumpSvalType(x); // expected-warning {{int}}
+
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
@@ -53,4 +57,5 @@ struct S {
 void test_field_dumps(struct S s, struct S *p) {
   clang_analyzer_dump_pointer(&s.x); // expected-warning{{&s.x}}
   clang_analyzer_dump_pointer(&p->x); // 
expected-warning{{&SymRegion{reg_$1}.x}}
+  clang_analyzer_dumpSvalType_pointer(&s.x); // expected-warning {{int *}}
 }



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


[clang-tools-extra] e8cae48 - Revert "[clang-tidy] modernize-deprecated-headers check should respect extern "C" blocks"

2022-05-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-13T17:07:58+02:00
New Revision: e8cae487022c2216182ae1ec24f248f287a614b7

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

LOG: Revert "[clang-tidy] modernize-deprecated-headers check should respect 
extern "C" blocks"

This reverts commit 7e3ea55da88a9d7feaa22f29d51f89fd0152a189.

Looks like this breaks tests: http://45.33.8.238/linux/76033/step_8.txt

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-deprecated-headers/mylib.h

clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-extern-c.cpp



diff  --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
index dd991221faab..0b44bdaafe23 100644
--- a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp
@@ -7,37 +7,23 @@
 
//===--===//
 
 #include "DeprecatedHeadersCheck.h"
-#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 
-#include 
 #include 
 
 namespace clang {
 namespace tidy {
 namespace modernize {
-namespace detail {
-bool operator<(const IncludeMarker &LHS, const IncludeMarker &RHS) {
-  return LHS.DecomposedDiagLoc < RHS.DecomposedDiagLoc;
-}
-bool operator<(const IncludeMarker &LHS,
-   const std::pair &RHS) {
-  return LHS.DecomposedDiagLoc < RHS;
-}
-bool operator<(const std::pair &LHS,
-   const IncludeMarker &RHS) {
-  return LHS < RHS.DecomposedDiagLoc;
-}
 
+namespace {
 class IncludeModernizePPCallbacks : public PPCallbacks {
 public:
-  explicit IncludeModernizePPCallbacks(DeprecatedHeadersCheck &Check,
-   LangOptions LangOpts,
-   const SourceManager &SM);
+  explicit IncludeModernizePPCallbacks(ClangTidyCheck &Check,
+   LangOptions LangOpts);
 
   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
   StringRef FileName, bool IsAngled,
@@ -47,98 +33,22 @@ class IncludeModernizePPCallbacks : public PPCallbacks {
   SrcMgr::CharacteristicKind FileType) override;
 
 private:
-  DeprecatedHeadersCheck &Check;
+  ClangTidyCheck &Check;
   LangOptions LangOpts;
   llvm::StringMap CStyledHeaderToCxx;
   llvm::StringSet<> DeleteHeaders;
-  const SourceManager &SM;
-};
-
-class ExternCRefutationVisitor
-: public RecursiveASTVisitor {
-  std::vector &IncludesToBeProcessed;
-  const SourceManager &SM;
-
-public:
-  ExternCRefutationVisitor(std::vector &IncludesToBeProcessed,
-   SourceManager &SM)
-  : IncludesToBeProcessed(IncludesToBeProcessed), SM(SM) {}
-  bool shouldWalkTypesOfTypeLocs() const { return false; }
-  bool shouldVisitLambdaBody() const { return false; }
-
-  bool VisitLinkageSpecDecl(LinkageSpecDecl *LinkSpecDecl) const {
-if (LinkSpecDecl->getLanguage() != LinkageSpecDecl::lang_c ||
-!LinkSpecDecl->hasBraces())
-  return true;
-
-auto ExternCBlockBegin =
-SM.getDecomposedExpansionLoc(LinkSpecDecl->getBeginLoc());
-auto ExternCBlockEnd =
-SM.getDecomposedExpansionLoc(LinkSpecDecl->getEndLoc());
-
-auto Begin = IncludesToBeProcessed.begin();
-auto End = IncludesToBeProcessed.end();
-auto Low = std::lower_bound(Begin, End, ExternCBlockBegin);
-auto Up = std::upper_bound(Low, End, ExternCBlockEnd);
-IncludesToBeProcessed.erase(Low, Up);
-return true;
-  }
 };
-} // namespace detail
+} // namespace
 
 void DeprecatedHeadersCheck::registerPPCallbacks(
 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
-  PP->addPPCallbacks(::std::make_unique(
-  *this, getLangOpts(), PP->getSourceManager()));
-}
-void DeprecatedHeadersCheck::registerMatchers(
-ast_matchers::MatchFinder *Finder) {
-  // Even though the checker operates on a "preprocessor" level, we still need
-  // to act on a "TranslationUnit" to acquire the AST where we can walk each
-  // Decl and look for `extern "C"` blocks where we will suppress the report we
-  // collected during the preprocessing phase.
-  // The `onStartOfTranslationUnit()` won't suffice, since we need some handle
-  // to the `ASTContext`.
-  Finder->addMat

[PATCH] D125532: [analyzer] Introduce clang_analyzer_dumpSvalType introspection function

2022-05-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
steakhal marked an inline comment as done.
Closed by commit rGa1025e6ffe9b: [analyzer] Introduce 
clang_analyzer_dumpSvalType introspection function (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125532

Files:
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/test/Analysis/expr-inspection.c


Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -6,12 +6,16 @@
 
 void clang_analyzer_dump(int x);
 void clang_analyzer_dump_pointer(int *p);
+void clang_analyzer_dumpSvalType(int x);
+void clang_analyzer_dumpSvalType_pointer(int *p);
 void clang_analyzer_printState(void);
 void clang_analyzer_numTimesReached(void);
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
   clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dumpSvalType(x); // expected-warning {{int}}
+
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
@@ -53,4 +57,5 @@
 void test_field_dumps(struct S s, struct S *p) {
   clang_analyzer_dump_pointer(&s.x); // expected-warning{{&s.x}}
   clang_analyzer_dump_pointer(&p->x); // 
expected-warning{{&SymRegion{reg_$1}.x}}
+  clang_analyzer_dumpSvalType_pointer(&s.x); // expected-warning {{int *}}
 }
Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@
   void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
   void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
+  void analyzerDumpSValType(const CallExpr *CE, CheckerContext &C) const;
   void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
   void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
   void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
@@ -98,6 +99,8 @@
 &ExprInspectionChecker::analyzerDumpExtent)
   .Case("clang_analyzer_dumpElementCount",
 &ExprInspectionChecker::analyzerDumpElementCount)
+  .StartsWith("clang_analyzer_dumpSvalType",
+  &ExprInspectionChecker::analyzerDumpSValType)
   .StartsWith("clang_analyzer_dump",
   &ExprInspectionChecker::analyzerDump)
   .Case("clang_analyzer_getExtent",
@@ -255,6 +258,16 @@
   reportBug(Ex.Visit(V), C);
 }
 
+void ExprInspectionChecker::analyzerDumpSValType(const CallExpr *CE,
+ CheckerContext &C) const {
+  const Expr *Arg = getArgExpr(CE, C);
+  if (!Arg)
+return;
+
+  QualType Ty = C.getSVal(Arg).getType(C.getASTContext());
+  reportBug(Ty.getAsString(), C);
+}
+
 void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
  CheckerContext &C) const {
   const Expr *Arg = getArgExpr(CE, C);


Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -6,12 +6,16 @@
 
 void clang_analyzer_dump(int x);
 void clang_analyzer_dump_pointer(int *p);
+void clang_analyzer_dumpSvalType(int x);
+void clang_analyzer_dumpSvalType_pointer(int *p);
 void clang_analyzer_printState(void);
 void clang_analyzer_numTimesReached(void);
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
   clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dumpSvalType(x); // expected-warning {{int}}
+
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
@@ -53,4 +57,5 @@
 void test_field_dumps(struct S s, struct S *p) {
   clang_analyzer_dump_pointer(&s.x); // expected-warning{{&s.x}}
   clang_analyzer_dump_pointer(&p->x); // expected-warning{{&SymRegion{reg_$1}.x}}
+  clang_analyzer_dumpSvalType_pointer(&s.x); // expected-warning {{int *}}
 }
Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@
   void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
   void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
+  void analyzerDumpSVa

  1   2   >