[PATCH] D130551: [pseudo] Allow opaque nodes to represent terminals

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: hokein, usaxena95.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, alextsao1999.
Herald added a project: clang-tools-extra.

This allows incomplete code such as `namespace foo {` to be modeled as a
normal sequence with the missing } represented by an empty opaque node.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130551

Files:
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -604,6 +604,28 @@
 "[  5, end) └─} := tok[5]\n");
 }
 
+TEST_F(GLRTest, RecoverTerminal) {
+  build(R"bnf(
+_ := stmt
+
+stmt := IDENTIFIER ; [recover=Skip]
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) stmt := IDENTIFIER ; [recover=Skip]\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─; := \n");
+}
+
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -182,9 +182,13 @@
   for (const PlaceholderRecovery *Option : BestOptions) {
 const ForestNode &Placeholder =
 Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
-const GSS::Node *NewHead = Params.GSStack.addNode(
-*Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
-&Placeholder, {Option->RecoveryNode});
+LRTable::StateID OldState = Option->RecoveryNode->State;
+LRTable::StateID NewState =
+isToken(Option->Symbol)
+? *Lang.Table.getShiftState(OldState, Option->Symbol)
+: *Lang.Table.getGoToState(OldState, Option->Symbol);
+const GSS::Node *NewHead =
+Params.GSStack.addNode(NewState, &Placeholder, {Option->RecoveryNode});
 NewHeads.push_back(NewHead);
   }
   TokenIndex = RecoveryRange->End;


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -604,6 +604,28 @@
 "[  5, end) └─} := tok[5]\n");
 }
 
+TEST_F(GLRTest, RecoverTerminal) {
+  build(R"bnf(
+_ := stmt
+
+stmt := IDENTIFIER ; [recover=Skip]
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) stmt := IDENTIFIER ; [recover=Skip]\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─; := \n");
+}
+
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -182,9 +182,13 @@
   for (const PlaceholderRecovery *Option : BestOptions) {
 const ForestNode &Placeholder =
 Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
-const GSS::Node *NewHead = Params.GSStack.addNode(
-*Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
-&Placeholder, {Option->RecoveryNode});
+LRTable::StateID OldState = Option->RecoveryNode->State;
+LRTable::StateID NewState =
+isToken(Option->Symbol)
+? *Lang.Table.getShiftState(OldState, Option->Symbol)
+: *Lang.Table.getGoToState(OldState, Option->Symbol);
+const GSS::Node *NewHead =
+Params.GSStack.addNode(NewState, &Placeholder, {Option->RecoveryNode});
 NewHeads.push_back(NewHead);
   }
   TokenIndex = RecoveryRange->End;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

ChuanqiXu wrote:
> rusyaev-roman wrote:
> > ChuanqiXu wrote:
> > > rusyaev-roman wrote:
> > > > ChuanqiXu wrote:
> > > > > rusyaev-roman wrote:
> > > > > > ChuanqiXu wrote:
> > > > > > > rusyaev-roman wrote:
> > > > > > > > ChuanqiXu wrote:
> > > > > > > > > What if NRVO contains a value already? It is possible due to 
> > > > > > > > > the value of NRVO could be set by its children.
> > > > > > > > Actually this is intention. If the parent has already NRVO 
> > > > > > > > candidate, then it should be invalidated (or not). Let's 
> > > > > > > > consider the following examples:
> > > > > > > > 
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > X foo(bool b) {
> > > > > > > >X x;
> > > > > > > >X y;
> > > > > > > >if (b)
> > > > > > > >   return x;
> > > > > > > >else
> > > > > > > >   return y; // when we process this return statement, the 
> > > > > > > > parent has already NRVO and it will be invalidated (this is 
> > > > > > > > correct behavior)
> > > > > > > > }
> > > > > > > > ```
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > X foo(bool b) {
> > > > > > > >X x;
> > > > > > > >if (b)
> > > > > > > >   return x;
> > > > > > > >
> > > > > > > >X y;
> > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > already NRVO and it WON't be invalidated
> > > > > > > >//  (this is correct behavior), because a return slot will 
> > > > > > > > be available for it
> > > > > > > >return y;
> > > > > > > > }
> > > > > > > > ```
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > X foo(bool b) {
> > > > > > > >X x;
> > > > > > > >if (b)
> > > > > > > >   return x;
> > > > > > > > 
> > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > already NRVO and it WON't be invalidated (this is correct 
> > > > > > > > behavior)
> > > > > > > >return x;
> > > > > > > > }
> > > > > > > > ```
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > X foo(bool b, X x) {
> > > > > > > >X y;
> > > > > > > >
> > > > > > > >if (b)
> > > > > > > >   return x;
> > > > > > > > 
> > > > > > > >// when we process this return statement, the parent 
> > > > > > > > contains nullptr (invalid candidate) and it will be invalidated 
> > > > > > > > (this is correct behavior)
> > > > > > > >return y;
> > > > > > > > }
> > > > > > > > ```
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > X foo(bool b, X x) {
> > > > > > > >if (b)
> > > > > > > >   return x;
> > > > > > > > 
> > > > > > > >X y;
> > > > > > > >// when we process this return statement, the parent 
> > > > > > > > contains nullptr (invalid candidate) and it WON't be 
> > > > > > > > invalidated (this is correct behavior)
> > > > > > > >return y;
> > > > > > > > }
> > > > > > > > ```
> > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But I 
> > > > > > > recommend to comment that the children would maintain the 
> > > > > > > `ReturnSlots` of their parents. (This is anti-intuition)
> > > > > > > 
> > > > > > > Have you tested any larger projects? Like libc++, libstdc++ or 
> > > > > > > something like folly. I feel we need to do such tests to avoid we 
> > > > > > > get anything wrong.
> > > > > > I've already added a comment at the beginning of 
> > > > > > `updateNRVOCandidate` function where this point is mentioned: 
> > > > > > ```
> > > > > > //  ... Therefore, we need to clear return slots for other
> > > > > > //  variables defined before the current return statement in 
> > > > > > the current
> > > > > > //  scope and in outer scopes.
> > > > > > ```
> > > > > > If it's not enough, please let me know.
> > > > > > 
> > > > > > 
> > > > > > > Have you tested any larger projects?
> > > > > > 
> > > > > > Yes, I've built the `clang` itself and `compiler-rt` project. Then 
> > > > > > I've checked them to run 'check-all' (on built clang and 
> > > > > > compiler-rt). Everything  works.
> > > > > Great! Clang should be large enough.
> > > > Thanks a lot for the careful review!
> > > > 
> > > > @ChuanqiXu  , could you land this patch please?
> > > > 
> > > > Many thanks to @Izaron for the original implementation.
> > > Sure. What's your prefer Name and Mail address?
> > Thanks!
> > 
> > Roman Rusyaev 
> Oh, I forgot you need edit the ReleaseNotes at clang/docs/ReleaseNotes.rst
I'm going to add a description in `C++ Language Changes in Clang` paragraph.

It will look like:
```
- Improved ``copy elision` optimization. It's possible to apply ``NRVO`` for an 
object if at the moment when
  any return statement of this object is executed, the ``return slo

[clang] 8a13326 - [analyzer] ArrayInitLoopExpr with array of non-POD type

2022-07-26 Thread via cfe-commits

Author: isuckatcs
Date: 2022-07-26T09:07:22+02:00
New Revision: 8a13326d184c2829a51d7c00f467ded06412f858

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

LOG: [analyzer] ArrayInitLoopExpr with array of non-POD type

This patch introduces the evaluation of ArrayInitLoopExpr
in case of structured bindings and implicit copy/move
constructor. The idea is to call the copy constructor for
every element in the array. The parameter of the copy
constructor is also manually selected, as it is not a part
of the CFG.

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

Added: 


Modified: 
clang/include/clang/Analysis/ConstructionContext.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/lib/Analysis/CFG.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
clang/test/Analysis/array-init-loop.cpp
clang/test/Analysis/ctor.mm
clang/test/Analysis/uninit-structured-binding-array.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/ConstructionContext.h 
b/clang/include/clang/Analysis/ConstructionContext.h
index a437160e07789..7ff1a007f8eed 100644
--- a/clang/include/clang/Analysis/ConstructionContext.h
+++ b/clang/include/clang/Analysis/ConstructionContext.h
@@ -298,6 +298,11 @@ class ConstructionContext {
const ConstructionContextLayer *TopLayer);
 
   Kind getKind() const { return K; }
+
+  virtual const ArrayInitLoopExpr *getArrayInitLoop() const { return nullptr; }
+
+  // Only declared to silence -Wnon-virtual-dtor warnings.
+  virtual ~ConstructionContext() = default;
 };
 
 /// An abstract base class for local variable constructors.
@@ -314,6 +319,12 @@ class VariableConstructionContext : public 
ConstructionContext {
 public:
   const DeclStmt *getDeclStmt() const { return DS; }
 
+  const ArrayInitLoopExpr *getArrayInitLoop() const override {
+const auto *Var = cast(DS->getSingleDecl());
+
+return dyn_cast(Var->getInit());
+  }
+
   static bool classof(const ConstructionContext *CC) {
 return CC->getKind() >= VARIABLE_BEGIN &&
CC->getKind() <= VARIABLE_END;
@@ -381,6 +392,10 @@ class ConstructorInitializerConstructionContext : public 
ConstructionContext {
 public:
   const CXXCtorInitializer *getCXXCtorInitializer() const { return I; }
 
+  const ArrayInitLoopExpr *getArrayInitLoop() const override {
+return dyn_cast(I->getInit());
+  }
+
   static bool classof(const ConstructionContext *CC) {
 return CC->getKind() >= INITIALIZER_BEGIN &&
CC->getKind() <= INITIALIZER_END;

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 116a5970c341f..8773e171369fd 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -622,6 +622,11 @@ class ExprEngine {
   getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr 
*E,
const LocationContext *LCtx);
 
+  /// Retreives the size of the array in the pending ArrayInitLoopExpr.
+  static Optional getPendingInitLoop(ProgramStateRef State,
+   const CXXConstructExpr *E,
+   const LocationContext *LCtx);
+
   /// By looking at a certain item that may be potentially part of an object's
   /// ConstructionContext, retrieve such object's location. A particular
   /// statement can be transparently passed as \p Item in most cases.
@@ -816,7 +821,9 @@ class ExprEngine {
 
   /// Checks whether our policies allow us to inline a non-POD type array
   /// construction.
-  bool shouldInlineArrayConstruction(const ArrayType *Type);
+  bool shouldInlineArrayConstruction(const ProgramStateRef State,
+ const CXXConstructExpr *CE,
+ const LocationContext *LCtx);
 
   /// Checks whether we construct an array of non-POD type, and decides if the
   /// constructor should be inkoved once again.
@@ -916,6 +923,16 @@ class ExprEngine {
   const CXXConstructExpr *E,
   const LocationContext *LCtx);
 
+  /// Sets the size of the array in a pending ArrayInitLoopExpr.
+  static ProgramStateRef setPendingInitLoop(ProgramStateRef State,
+const CXXConstructExpr *E,
+const LocationContext *LCtx,
+unsigned Idx);
+
+  static ProgramStateRef removePendi

[PATCH] D129496: [analyzer] ArrayInitLoopExpr with array of non-POD type.

2022-07-26 Thread Domján Dániel via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8a13326d184c: [analyzer] ArrayInitLoopExpr with array of 
non-POD type (authored by isuckatcs).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129496

Files:
  clang/include/clang/Analysis/ConstructionContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/Analysis/CFG.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  clang/test/Analysis/array-init-loop.cpp
  clang/test/Analysis/ctor.mm
  clang/test/Analysis/uninit-structured-binding-array.cpp

Index: clang/test/Analysis/uninit-structured-binding-array.cpp
===
--- clang/test/Analysis/uninit-structured-binding-array.cpp
+++ clang/test/Analysis/uninit-structured-binding-array.cpp
@@ -292,3 +292,97 @@
   clang_analyzer_eval(e == 5); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(f == 6); // expected-warning{{UNKNOWN}}
 }
+
+struct S {
+  int a = 1;
+  int b = 2;
+};
+
+void non_pod_val(void) {
+  S arr[2];
+
+  auto [x, y] = arr;
+
+  clang_analyzer_eval(x.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 2); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 2); // expected-warning{{TRUE}}
+}
+
+void non_pod_val_syntax_2(void) {
+  S arr[2];
+
+  auto [x, y](arr);
+
+  clang_analyzer_eval(x.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 2); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 2); // expected-warning{{TRUE}}
+}
+
+void non_pod_lref(void) {
+  S arr[2];
+
+  auto &[x, y] = arr;
+
+  clang_analyzer_eval(x.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 2); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 2); // expected-warning{{TRUE}}
+}
+
+void non_pod_rref(void) {
+  S arr[2];
+
+  auto &&[x, y] = arr;
+
+  clang_analyzer_eval(x.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 2); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 2); // expected-warning{{TRUE}}
+}
+
+struct SUD {
+  inline static int c = 0;
+
+  int a = 1;
+  int b = 2;
+
+  SUD() { ++c; };
+
+  SUD(const SUD ©) {
+a = copy.a + 1;
+b = copy.b + 1;
+  }
+};
+
+void non_pod_user_defined_val(void) {
+  SUD arr[2];
+
+  auto [x, y] = arr;
+
+  clang_analyzer_eval(x.a == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 3); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 3); // expected-warning{{TRUE}}
+}
+
+void non_pod_user_defined_val_syntax_2(void) {
+  SUD::c = 0;
+  SUD arr[2];
+
+  auto [x, y](arr);
+
+  clang_analyzer_eval(SUD::c == 2); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(x.a == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x.b == 3); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y.a == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y.b == 3); // expected-warning{{TRUE}}
+}
Index: clang/test/Analysis/ctor.mm
===
--- clang/test/Analysis/ctor.mm
+++ clang/test/Analysis/ctor.mm
@@ -439,16 +439,16 @@
 
 NonPOD b = a;
 
-clang_analyzer_eval(b.values[0].x == 1); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(b.values[1].x == 2); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(b.values[2].x == 3); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(b.values[0].x == 1); // expected-warning{{TRUE}}
+clang_analyzer_eval(b.values[1].x == 2); // expected-warning{{TRUE}}
+clang_analyzer_eval(b.values[2].x == 3); // expected-warning{{TRUE}}
 
 NonPOD c;
 c = b;
 
-clang_analyzer_eval(c.values[0].x == 1); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(c.values[1].x == 2); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(c.values[2].x == 3); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(c.values[0].x == 1); // expected-warning{{TRUE}}
+clang_analyzer_eval(c.values[1].x == 2); // expected-warning{{TRUE}}
+clang_analyzer_eval(c.values[2].x == 3); // expected-warning{{TRUE}}
   }
 
   struct NestedNonPOD {
@@ -502,16 +502,16 @@
 
 NonPODDefaulted b = a;
 
-clang_analyzer_eval(b.values[0].x == 1); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(b.values[1].x == 2); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(b.values[2].

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

rusyaev-roman wrote:
> ChuanqiXu wrote:
> > rusyaev-roman wrote:
> > > ChuanqiXu wrote:
> > > > rusyaev-roman wrote:
> > > > > ChuanqiXu wrote:
> > > > > > rusyaev-roman wrote:
> > > > > > > ChuanqiXu wrote:
> > > > > > > > rusyaev-roman wrote:
> > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > What if NRVO contains a value already? It is possible due 
> > > > > > > > > > to the value of NRVO could be set by its children.
> > > > > > > > > Actually this is intention. If the parent has already NRVO 
> > > > > > > > > candidate, then it should be invalidated (or not). Let's 
> > > > > > > > > consider the following examples:
> > > > > > > > > 
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > X foo(bool b) {
> > > > > > > > >X x;
> > > > > > > > >X y;
> > > > > > > > >if (b)
> > > > > > > > >   return x;
> > > > > > > > >else
> > > > > > > > >   return y; // when we process this return statement, the 
> > > > > > > > > parent has already NRVO and it will be invalidated (this is 
> > > > > > > > > correct behavior)
> > > > > > > > > }
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > X foo(bool b) {
> > > > > > > > >X x;
> > > > > > > > >if (b)
> > > > > > > > >   return x;
> > > > > > > > >
> > > > > > > > >X y;
> > > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > > already NRVO and it WON't be invalidated
> > > > > > > > >//  (this is correct behavior), because a return slot will 
> > > > > > > > > be available for it
> > > > > > > > >return y;
> > > > > > > > > }
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > X foo(bool b) {
> > > > > > > > >X x;
> > > > > > > > >if (b)
> > > > > > > > >   return x;
> > > > > > > > > 
> > > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > > already NRVO and it WON't be invalidated (this is correct 
> > > > > > > > > behavior)
> > > > > > > > >return x;
> > > > > > > > > }
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > X foo(bool b, X x) {
> > > > > > > > >X y;
> > > > > > > > >
> > > > > > > > >if (b)
> > > > > > > > >   return x;
> > > > > > > > > 
> > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > contains nullptr (invalid candidate) and it will be 
> > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > >return y;
> > > > > > > > > }
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > X foo(bool b, X x) {
> > > > > > > > >if (b)
> > > > > > > > >   return x;
> > > > > > > > > 
> > > > > > > > >X y;
> > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > contains nullptr (invalid candidate) and it WON't be 
> > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > >return y;
> > > > > > > > > }
> > > > > > > > > ```
> > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But I 
> > > > > > > > recommend to comment that the children would maintain the 
> > > > > > > > `ReturnSlots` of their parents. (This is anti-intuition)
> > > > > > > > 
> > > > > > > > Have you tested any larger projects? Like libc++, libstdc++ or 
> > > > > > > > something like folly. I feel we need to do such tests to avoid 
> > > > > > > > we get anything wrong.
> > > > > > > I've already added a comment at the beginning of 
> > > > > > > `updateNRVOCandidate` function where this point is mentioned: 
> > > > > > > ```
> > > > > > > //  ... Therefore, we need to clear return slots for other
> > > > > > > //  variables defined before the current return statement in 
> > > > > > > the current
> > > > > > > //  scope and in outer scopes.
> > > > > > > ```
> > > > > > > If it's not enough, please let me know.
> > > > > > > 
> > > > > > > 
> > > > > > > > Have you tested any larger projects?
> > > > > > > 
> > > > > > > Yes, I've built the `clang` itself and `compiler-rt` project. 
> > > > > > > Then I've checked them to run 'check-all' (on built clang and 
> > > > > > > compiler-rt). Everything  works.
> > > > > > Great! Clang should be large enough.
> > > > > Thanks a lot for the careful review!
> > > > > 
> > > > > @ChuanqiXu  , could you land this patch please?
> > > > > 
> > > > > Many thanks to @Izaron for the original implementation.
> > > > Sure. What's your prefer Name and Mail address?
> > > Thanks!
> > > 
> > > Roman Rusyaev 
> > Oh, I forgot you need edit the ReleaseNotes at clang/docs/ReleaseNotes.rst
> I'm going to add a descri

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added a comment.

@ChuanqiXu , the release notes were updated. Could you check and merge please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119792

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


[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

ChuanqiXu wrote:
> rusyaev-roman wrote:
> > ChuanqiXu wrote:
> > > rusyaev-roman wrote:
> > > > ChuanqiXu wrote:
> > > > > rusyaev-roman wrote:
> > > > > > ChuanqiXu wrote:
> > > > > > > rusyaev-roman wrote:
> > > > > > > > ChuanqiXu wrote:
> > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > What if NRVO contains a value already? It is possible due 
> > > > > > > > > > > to the value of NRVO could be set by its children.
> > > > > > > > > > Actually this is intention. If the parent has already NRVO 
> > > > > > > > > > candidate, then it should be invalidated (or not). Let's 
> > > > > > > > > > consider the following examples:
> > > > > > > > > > 
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > X foo(bool b) {
> > > > > > > > > >X x;
> > > > > > > > > >X y;
> > > > > > > > > >if (b)
> > > > > > > > > >   return x;
> > > > > > > > > >else
> > > > > > > > > >   return y; // when we process this return statement, 
> > > > > > > > > > the parent has already NRVO and it will be invalidated 
> > > > > > > > > > (this is correct behavior)
> > > > > > > > > > }
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > X foo(bool b) {
> > > > > > > > > >X x;
> > > > > > > > > >if (b)
> > > > > > > > > >   return x;
> > > > > > > > > >
> > > > > > > > > >X y;
> > > > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > > > already NRVO and it WON't be invalidated
> > > > > > > > > >//  (this is correct behavior), because a return slot 
> > > > > > > > > > will be available for it
> > > > > > > > > >return y;
> > > > > > > > > > }
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > X foo(bool b) {
> > > > > > > > > >X x;
> > > > > > > > > >if (b)
> > > > > > > > > >   return x;
> > > > > > > > > > 
> > > > > > > > > >// when we process this return statement, the parent has 
> > > > > > > > > > already NRVO and it WON't be invalidated (this is correct 
> > > > > > > > > > behavior)
> > > > > > > > > >return x;
> > > > > > > > > > }
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > >X y;
> > > > > > > > > >
> > > > > > > > > >if (b)
> > > > > > > > > >   return x;
> > > > > > > > > > 
> > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > contains nullptr (invalid candidate) and it will be 
> > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > >return y;
> > > > > > > > > > }
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > >if (b)
> > > > > > > > > >   return x;
> > > > > > > > > > 
> > > > > > > > > >X y;
> > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > contains nullptr (invalid candidate) and it WON't be 
> > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > >return y;
> > > > > > > > > > }
> > > > > > > > > > ```
> > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But I 
> > > > > > > > > recommend to comment that the children would maintain the 
> > > > > > > > > `ReturnSlots` of their parents. (This is anti-intuition)
> > > > > > > > > 
> > > > > > > > > Have you tested any larger projects? Like libc++, libstdc++ 
> > > > > > > > > or something like folly. I feel we need to do such tests to 
> > > > > > > > > avoid we get anything wrong.
> > > > > > > > I've already added a comment at the beginning of 
> > > > > > > > `updateNRVOCandidate` function where this point is mentioned: 
> > > > > > > > ```
> > > > > > > > //  ... Therefore, we need to clear return slots for other
> > > > > > > > //  variables defined before the current return statement 
> > > > > > > > in the current
> > > > > > > > //  scope and in outer scopes.
> > > > > > > > ```
> > > > > > > > If it's not enough, please let me know.
> > > > > > > > 
> > > > > > > > 
> > > > > > > > > Have you tested any larger projects?
> > > > > > > > 
> > > > > > > > Yes, I've built the `clang` itself and `compiler-rt` project. 
> > > > > > > > Then I've checked them to run 'check-all' (on built clang and 
> > > > > > > > compiler-rt). Everything  works.
> > > > > > > Great! Clang should be large enough.
> > > > > > Thanks a lot for the careful review!
> > > > > > 
> > > > > > @ChuanqiXu  , could you land this patch please?
> > > > > > 
> > > > > > Many thanks t

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

rusyaev-roman wrote:
> ChuanqiXu wrote:
> > rusyaev-roman wrote:
> > > ChuanqiXu wrote:
> > > > rusyaev-roman wrote:
> > > > > ChuanqiXu wrote:
> > > > > > rusyaev-roman wrote:
> > > > > > > ChuanqiXu wrote:
> > > > > > > > rusyaev-roman wrote:
> > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > What if NRVO contains a value already? It is possible 
> > > > > > > > > > > > due to the value of NRVO could be set by its children.
> > > > > > > > > > > Actually this is intention. If the parent has already 
> > > > > > > > > > > NRVO candidate, then it should be invalidated (or not). 
> > > > > > > > > > > Let's consider the following examples:
> > > > > > > > > > > 
> > > > > > > > > > > 
> > > > > > > > > > > ```
> > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > >X x;
> > > > > > > > > > >X y;
> > > > > > > > > > >if (b)
> > > > > > > > > > >   return x;
> > > > > > > > > > >else
> > > > > > > > > > >   return y; // when we process this return statement, 
> > > > > > > > > > > the parent has already NRVO and it will be invalidated 
> > > > > > > > > > > (this is correct behavior)
> > > > > > > > > > > }
> > > > > > > > > > > ```
> > > > > > > > > > > 
> > > > > > > > > > > ```
> > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > >X x;
> > > > > > > > > > >if (b)
> > > > > > > > > > >   return x;
> > > > > > > > > > >
> > > > > > > > > > >X y;
> > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > has already NRVO and it WON't be invalidated
> > > > > > > > > > >//  (this is correct behavior), because a return slot 
> > > > > > > > > > > will be available for it
> > > > > > > > > > >return y;
> > > > > > > > > > > }
> > > > > > > > > > > ```
> > > > > > > > > > > 
> > > > > > > > > > > ```
> > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > >X x;
> > > > > > > > > > >if (b)
> > > > > > > > > > >   return x;
> > > > > > > > > > > 
> > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > has already NRVO and it WON't be invalidated (this is 
> > > > > > > > > > > correct behavior)
> > > > > > > > > > >return x;
> > > > > > > > > > > }
> > > > > > > > > > > ```
> > > > > > > > > > > 
> > > > > > > > > > > ```
> > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > >X y;
> > > > > > > > > > >
> > > > > > > > > > >if (b)
> > > > > > > > > > >   return x;
> > > > > > > > > > > 
> > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > contains nullptr (invalid candidate) and it will be 
> > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > >return y;
> > > > > > > > > > > }
> > > > > > > > > > > ```
> > > > > > > > > > > 
> > > > > > > > > > > ```
> > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > >if (b)
> > > > > > > > > > >   return x;
> > > > > > > > > > > 
> > > > > > > > > > >X y;
> > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > contains nullptr (invalid candidate) and it WON't be 
> > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > >return y;
> > > > > > > > > > > }
> > > > > > > > > > > ```
> > > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But I 
> > > > > > > > > > recommend to comment that the children would maintain the 
> > > > > > > > > > `ReturnSlots` of their parents. (This is anti-intuition)
> > > > > > > > > > 
> > > > > > > > > > Have you tested any larger projects? Like libc++, libstdc++ 
> > > > > > > > > > or something like folly. I feel we need to do such tests to 
> > > > > > > > > > avoid we get anything wrong.
> > > > > > > > > I've already added a comment at the beginning of 
> > > > > > > > > `updateNRVOCandidate` function where this point is mentioned: 
> > > > > > > > > ```
> > > > > > > > > //  ... Therefore, we need to clear return slots for other
> > > > > > > > > //  variables defined before the current return statement 
> > > > > > > > > in the current
> > > > > > > > > //  scope and in outer scopes.
> > > > > > > > > ```
> > > > > > > > > If it's not enough, please let me know.
> > > > > > > > > 
> > > > > > > > > 
> > > > > > > > > > Have you tested any larger projects?
> > > > > > > > > 
> > > > > > > > > Yes, I've built the `clang` itself and `compiler-rt` project. 
> > > > > > > > > Then I've checked them to run 'check-all' (on built clang and 
> > > > > > > > > compile

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

rusyaev-roman wrote:
> rusyaev-roman wrote:
> > ChuanqiXu wrote:
> > > rusyaev-roman wrote:
> > > > ChuanqiXu wrote:
> > > > > rusyaev-roman wrote:
> > > > > > ChuanqiXu wrote:
> > > > > > > rusyaev-roman wrote:
> > > > > > > > ChuanqiXu wrote:
> > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > What if NRVO contains a value already? It is possible 
> > > > > > > > > > > > > due to the value of NRVO could be set by its children.
> > > > > > > > > > > > Actually this is intention. If the parent has already 
> > > > > > > > > > > > NRVO candidate, then it should be invalidated (or not). 
> > > > > > > > > > > > Let's consider the following examples:
> > > > > > > > > > > > 
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > >X x;
> > > > > > > > > > > >X y;
> > > > > > > > > > > >if (b)
> > > > > > > > > > > >   return x;
> > > > > > > > > > > >else
> > > > > > > > > > > >   return y; // when we process this return 
> > > > > > > > > > > > statement, the parent has already NRVO and it will be 
> > > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > > > }
> > > > > > > > > > > > ```
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > >X x;
> > > > > > > > > > > >if (b)
> > > > > > > > > > > >   return x;
> > > > > > > > > > > >
> > > > > > > > > > > >X y;
> > > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > > has already NRVO and it WON't be invalidated
> > > > > > > > > > > >//  (this is correct behavior), because a return 
> > > > > > > > > > > > slot will be available for it
> > > > > > > > > > > >return y;
> > > > > > > > > > > > }
> > > > > > > > > > > > ```
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > >X x;
> > > > > > > > > > > >if (b)
> > > > > > > > > > > >   return x;
> > > > > > > > > > > > 
> > > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > > has already NRVO and it WON't be invalidated (this is 
> > > > > > > > > > > > correct behavior)
> > > > > > > > > > > >return x;
> > > > > > > > > > > > }
> > > > > > > > > > > > ```
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > >X y;
> > > > > > > > > > > >
> > > > > > > > > > > >if (b)
> > > > > > > > > > > >   return x;
> > > > > > > > > > > > 
> > > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > > contains nullptr (invalid candidate) and it will be 
> > > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > > >return y;
> > > > > > > > > > > > }
> > > > > > > > > > > > ```
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > >if (b)
> > > > > > > > > > > >   return x;
> > > > > > > > > > > > 
> > > > > > > > > > > >X y;
> > > > > > > > > > > >// when we process this return statement, the parent 
> > > > > > > > > > > > contains nullptr (invalid candidate) and it WON't be 
> > > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > > >return y;
> > > > > > > > > > > > }
> > > > > > > > > > > > ```
> > > > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But I 
> > > > > > > > > > > recommend to comment that the children would maintain the 
> > > > > > > > > > > `ReturnSlots` of their parents. (This is anti-intuition)
> > > > > > > > > > > 
> > > > > > > > > > > Have you tested any larger projects? Like libc++, 
> > > > > > > > > > > libstdc++ or something like folly. I feel we need to do 
> > > > > > > > > > > such tests to avoid we get anything wrong.
> > > > > > > > > > I've already added a comment at the beginning of 
> > > > > > > > > > `updateNRVOCandidate` function where this point is 
> > > > > > > > > > mentioned: 
> > > > > > > > > > ```
> > > > > > > > > > //  ... Therefore, we need to clear return slots for 
> > > > > > > > > > other
> > > > > > > > > > //  variables defined before the current return 
> > > > > > > > > > statement in the current
> > > > > > > > > > //  scope and in outer scopes.
> > > > > > > > > > ```
> > > > > > > > > > If it's not enough, please let me know.
> > > > > > > > > > 
> > > > > > >

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

rusyaev-roman wrote:
> rusyaev-roman wrote:
> > rusyaev-roman wrote:
> > > ChuanqiXu wrote:
> > > > rusyaev-roman wrote:
> > > > > ChuanqiXu wrote:
> > > > > > rusyaev-roman wrote:
> > > > > > > ChuanqiXu wrote:
> > > > > > > > rusyaev-roman wrote:
> > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > > What if NRVO contains a value already? It is 
> > > > > > > > > > > > > > possible due to the value of NRVO could be set by 
> > > > > > > > > > > > > > its children.
> > > > > > > > > > > > > Actually this is intention. If the parent has already 
> > > > > > > > > > > > > NRVO candidate, then it should be invalidated (or 
> > > > > > > > > > > > > not). Let's consider the following examples:
> > > > > > > > > > > > > 
> > > > > > > > > > > > > 
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > >X x;
> > > > > > > > > > > > >X y;
> > > > > > > > > > > > >if (b)
> > > > > > > > > > > > >   return x;
> > > > > > > > > > > > >else
> > > > > > > > > > > > >   return y; // when we process this return 
> > > > > > > > > > > > > statement, the parent has already NRVO and it will be 
> > > > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > > > > }
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > 
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > >X x;
> > > > > > > > > > > > >if (b)
> > > > > > > > > > > > >   return x;
> > > > > > > > > > > > >
> > > > > > > > > > > > >X y;
> > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > parent has already NRVO and it WON't be invalidated
> > > > > > > > > > > > >//  (this is correct behavior), because a return 
> > > > > > > > > > > > > slot will be available for it
> > > > > > > > > > > > >return y;
> > > > > > > > > > > > > }
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > 
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > >X x;
> > > > > > > > > > > > >if (b)
> > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > 
> > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > parent has already NRVO and it WON't be invalidated 
> > > > > > > > > > > > > (this is correct behavior)
> > > > > > > > > > > > >return x;
> > > > > > > > > > > > > }
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > 
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > >X y;
> > > > > > > > > > > > >
> > > > > > > > > > > > >if (b)
> > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > 
> > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > parent contains nullptr (invalid candidate) and it 
> > > > > > > > > > > > > will be invalidated (this is correct behavior)
> > > > > > > > > > > > >return y;
> > > > > > > > > > > > > }
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > 
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > >if (b)
> > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > 
> > > > > > > > > > > > >X y;
> > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > parent contains nullptr (invalid candidate) and it 
> > > > > > > > > > > > > WON't be invalidated (this is correct behavior)
> > > > > > > > > > > > >return y;
> > > > > > > > > > > > > }
> > > > > > > > > > > > > ```
> > > > > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. But 
> > > > > > > > > > > > I recommend to comment that the children would maintain 
> > > > > > > > > > > > the `ReturnSlots` of their parents. (This is 
> > > > > > > > > > > > anti-intuition)
> > > > > > > > > > > > 
> > > > > > > > > > > > Have you tested any larger projects? Like libc++, 
> > > > > > > > > > > > libstdc++ or something like folly. I feel we need to do 
> > > > > > > > > > > > such tests to avoid we get anything wrong.
> > > > > > > > > > > I've already added a comment at the beginning of 
> > > > > > > > > > > `updateNRVOCandidate` function where this point is 
> > > > > > > > > > > mentioned: 
> > > > > > > > > > > ```
> > > > > > > > > > > //  ... Therefore, we need to clear return slots for 
> > > > > > > > > > > other
> > > > > > > > > > 

[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-07-26 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng marked 9 inline comments as done.
kito-cheng added a comment.

@aaron.ballman thanks for your review!




Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:400
+  // Number of fields, greater than 1 if it's segment load/store.
+  uint8_t NF;
+};

aaron.ballman wrote:
> 
That the term used in RVV spec, so I keep this as `NF` :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

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


[clang] 996b092 - [analyzer] Lambda capture non-POD type array

2022-07-26 Thread via cfe-commits

Author: isuckatcs
Date: 2022-07-26T09:40:25+02:00
New Revision: 996b092c5e170786572e925345e502e5376feaee

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

LOG: [analyzer] Lambda capture non-POD type array

This patch introduces a new `ConstructionContext` for
lambda capture. This `ConstructionContext` allows the
analyzer to construct the captured object directly into
it's final region, and makes it possible to capture
non-POD arrays.

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

Added: 


Modified: 
clang/include/clang/Analysis/CFG.h
clang/include/clang/Analysis/ConstructionContext.h
clang/lib/Analysis/CFG.cpp
clang/lib/Analysis/ConstructionContext.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
clang/test/Analysis/array-init-loop.cpp
clang/test/Analysis/lambdas.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index d8e7e1e43d81..4f16a6361950 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -202,7 +202,8 @@ class CFGCXXRecordTypedCall : public CFGStmt {
  isa(C) ||
  isa(C) ||
  isa(C) ||
- isa(C)));
+ isa(C) ||
+ isa(C)));
 Data2.setPointer(const_cast(C));
   }
 

diff  --git a/clang/include/clang/Analysis/ConstructionContext.h 
b/clang/include/clang/Analysis/ConstructionContext.h
index 7ff1a007f8ee..67a091199b91 100644
--- a/clang/include/clang/Analysis/ConstructionContext.h
+++ b/clang/include/clang/Analysis/ConstructionContext.h
@@ -36,13 +36,14 @@ class ConstructionContextItem {
 ElidedDestructorKind,
 ElidableConstructorKind,
 ArgumentKind,
-STATEMENT_WITH_INDEX_KIND_BEGIN=ArgumentKind,
-STATEMENT_WITH_INDEX_KIND_END=ArgumentKind,
+LambdaCaptureKind,
+STATEMENT_WITH_INDEX_KIND_BEGIN = ArgumentKind,
+STATEMENT_WITH_INDEX_KIND_END = LambdaCaptureKind,
 STATEMENT_KIND_BEGIN = VariableKind,
-STATEMENT_KIND_END = ArgumentKind,
+STATEMENT_KIND_END = LambdaCaptureKind,
 InitializerKind,
-INITIALIZER_KIND_BEGIN=InitializerKind,
-INITIALIZER_KIND_END=InitializerKind
+INITIALIZER_KIND_BEGIN = InitializerKind,
+INITIALIZER_KIND_END = InitializerKind
   };
 
   LLVM_DUMP_METHOD static StringRef getKindAsString(ItemKind K) {
@@ -55,6 +56,8 @@ class ConstructionContextItem {
   case ElidedDestructorKind:return "elide destructor";
   case ElidableConstructorKind: return "elide constructor";
   case ArgumentKind:return "construct into argument";
+  case LambdaCaptureKind:
+return "construct into lambda captured variable";
   case InitializerKind: return "construct into member variable";
 };
 llvm_unreachable("Unknown ItemKind");
@@ -72,7 +75,7 @@ class ConstructionContextItem {
 
   bool hasIndex() const {
 return Kind >= STATEMENT_WITH_INDEX_KIND_BEGIN &&
-   Kind >= STATEMENT_WITH_INDEX_KIND_END;
+   Kind <= STATEMENT_WITH_INDEX_KIND_END;
   }
 
   bool hasInitializer() const {
@@ -127,6 +130,9 @@ class ConstructionContextItem {
   ConstructionContextItem(const CXXCtorInitializer *Init)
   : Data(Init), Kind(InitializerKind), Index(0) {}
 
+  ConstructionContextItem(const LambdaExpr *LE, unsigned Index)
+  : Data(LE), Kind(LambdaCaptureKind), Index(Index) {}
+
   ItemKind getKind() const { return Kind; }
 
   LLVM_DUMP_METHOD StringRef getKindAsString() const {
@@ -254,7 +260,8 @@ class ConstructionContext {
 CXX17ElidedCopyReturnedValueKind,
 RETURNED_VALUE_BEGIN = SimpleReturnedValueKind,
 RETURNED_VALUE_END = CXX17ElidedCopyReturnedValueKind,
-ArgumentKind
+ArgumentKind,
+LambdaCaptureKind
   };
 
 protected:
@@ -674,6 +681,42 @@ class ArgumentConstructionContext : public 
ConstructionContext {
   }
 };
 
+class LambdaCaptureConstructionContext : public ConstructionContext {
+  // The lambda of which the initializer we capture.
+  const LambdaExpr *LE;
+
+  // Index of the captured element in the captured list.
+  unsigned Index;
+
+  friend class ConstructionContext; // Allows to create<>() itself.
+
+  explicit LambdaCaptureConstructionContext(const LambdaExpr *LE,
+unsigned Index)
+  : ConstructionContext(LambdaCaptureKind), LE(LE), Index(Index) {}
+
+public:
+  const LambdaExpr *getLambdaExpr() const { return LE; }
+  unsigned getIndex() const { return Index; }
+
+  const Expr *getInitializer() const {
+return *(LE->capture_init_begin() + Index);
+  }
+
+  const FieldDecl *getFieldDecl() const {
+auto It = LE->getLambdaClass()->field_begin();
+std::advance(It, Ind

[PATCH] D129967: [analyzer] Lambda capture non-POD type array

2022-07-26 Thread Domján Dániel via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG996b092c5e17: [analyzer] Lambda capture non-POD type array 
(authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129967

Files:
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/Analysis/ConstructionContext.h
  clang/lib/Analysis/CFG.cpp
  clang/lib/Analysis/ConstructionContext.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/test/Analysis/array-init-loop.cpp
  clang/test/Analysis/lambdas.cpp

Index: clang/test/Analysis/lambdas.cpp
===
--- clang/test/Analysis/lambdas.cpp
+++ clang/test/Analysis/lambdas.cpp
@@ -400,7 +400,7 @@
 // CHECK: [B1]
 // CHECK:   1: x
 // CHECK:   2: [B1.1] (ImplicitCastExpr, NoOp, const struct X)
-// CHECK:   3: [B1.2] (CXXConstructExpr, struct X)
+// CHECK:   3: [B1.2] (CXXConstructExpr[B1.4]+0, struct X)
 // CHECK:   4: [x] {
 // CHECK:}
 // CHECK:   5: (void)[B1.4] (CStyleCastExpr, ToVoid, void)
@@ -408,4 +408,3 @@
 // CHECK:   Succs (1): B0
 // CHECK: [B0 (EXIT)]
 // CHECK:   Preds (1): B1
-
Index: clang/test/Analysis/array-init-loop.cpp
===
--- clang/test/Analysis/array-init-loop.cpp
+++ clang/test/Analysis/array-init-loop.cpp
@@ -160,6 +160,11 @@
   int i;
 };
 
+// The duplicate is required to emit a warning at 2 different places. 
+struct S3_duplicate {
+  int i;
+};
+
 void array_uninit_non_pod() {
   S3 arr[1];
 
@@ -170,24 +175,23 @@
   S2::c = 0;
   S2 arr[4];
 
-  // FIXME: These should be TRUE, but we fail to capture the array properly.
   auto l = [arr] { return arr[0].i; }();
-  clang_analyzer_eval(l == 2); // expected-warning{{TRUE}} // expected-warning{{FALSE}}
+  clang_analyzer_eval(l == 2); // expected-warning{{TRUE}}
 
   l = [arr] { return arr[1].i; }();
-  clang_analyzer_eval(l == 3); // expected-warning{{TRUE}} // expected-warning{{FALSE}}
+  clang_analyzer_eval(l == 3); // expected-warning{{TRUE}}
 
   l = [arr] { return arr[2].i; }();
-  clang_analyzer_eval(l == 4); // expected-warning{{TRUE}} // expected-warning{{FALSE}}
+  clang_analyzer_eval(l == 4); // expected-warning{{TRUE}}
 
   l = [arr] { return arr[3].i; }();
-  clang_analyzer_eval(l == 5); // expected-warning{{TRUE}} // expected-warning{{FALSE}}
+  clang_analyzer_eval(l == 5); // expected-warning{{TRUE}}
 }
 
 void lambda_uninit_non_pod() {
-  S3 arr[4];
+  S3_duplicate arr[4];
 
-  int l = [arr] { return arr[3].i; }();
+  int l = [arr] { return arr[3].i; }(); // expected-warning@164{{ in implicit constructor is garbage or undefined }}
 }
 
 // If this struct is being copy/move constructed by the implicit ctors, ArrayInitLoopExpr
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -290,6 +290,23 @@
 
   return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
 }
+case ConstructionContext::LambdaCaptureKind: {
+  CallOpts.IsTemporaryCtorOrDtor = true;
+
+  const auto *LCC = cast(CC);
+
+  SVal Base = loc::MemRegionVal(
+  MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), LCtx));
+
+  const auto *CE = dyn_cast_or_null(E);
+  if (getIndexOfElementToConstruct(State, CE, LCtx)) {
+CallOpts.IsArrayCtorOrDtor = true;
+Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx),
+Base);
+  }
+
+  return Base;
+}
 case ConstructionContext::ArgumentKind: {
   // Arguments are technically temporaries.
   CallOpts.IsTemporaryCtorOrDtor = true;
@@ -450,6 +467,17 @@
 
   return State;
 }
+case ConstructionContext::LambdaCaptureKind: {
+  const auto *LCC = cast(CC);
+
+  // If we capture and array, we want to store the super region, not a
+  // sub-region.
+  if (const auto *EL = dyn_cast_or_null(V.getAsRegion()))
+V = loc::MemRegionVal(EL->getSuperRegion());
+
+  return addObjectUnderConstruction(
+  State, {LCC->getLambdaExpr(), LCC->getIndex()}, LCtx, V);
+}
 case ConstructionContext::ArgumentKind: {
   const auto *ACC = cast(CC);
   if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
@@ -1105,19 +1133,40 @@
 
   // If we created a new MemRegion for the lambda, we should explicitly bind
   // the captures.
+  unsigned Idx = 0;
   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
e = LE->capture_init_end();
-   i != e; ++i, ++CurField) {
+   i !

[PATCH] D130553: [clang][lld][cmake] Simplify header dirs

2022-07-26 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 created this revision.
Ericson2314 added reviewers: beanz, sebastian-ne, mstorsjo.
Herald added a subscriber: mgorny.
Herald added a project: All.
Ericson2314 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We don't need to recompute the list LLVMConfig.cmake provides us.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130553

Files:
  clang/CMakeLists.txt
  lld/CMakeLists.txt


Index: lld/CMakeLists.txt
===
--- lld/CMakeLists.txt
+++ lld/CMakeLists.txt
@@ -70,13 +70,15 @@
   if (NOT LLVM_CONFIG_FOUND)
 # Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
 # path is removed.
-set(MAIN_INCLUDE_DIR "${LLVM_INCLUDE_DIR}")
+set(INCLUDE_DIRS ${LLVM_INCLUDE_DIRS})
 set(LLVM_OBJ_DIR "${LLVM_BINARY_DIR}")
 # N.B. this is just a default value, the CACHE PATHs below can be 
overridden.
 set(MAIN_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../llvm")
+  else()
+set(INCLUDE_DIRS "${LLVM_BINARY_DIR}/include" "${MAIN_INCLUDE_DIR}")
   endif()
 
-  set(LLVM_MAIN_INCLUDE_DIR "${MAIN_INCLUDE_DIR}" CACHE PATH "Path to 
llvm/include")
+  set(LLVM_INCLUDE_DIRS ${INCLUDE_DIRS} CACHE PATH "Path to llvm/include and 
any other header dirs needed")
   set(LLVM_BINARY_DIR "${LLVM_OBJ_ROOT}" CACHE PATH "Path to LLVM build tree")
   set(LLVM_MAIN_SRC_DIR "${MAIN_SRC_DIR}" CACHE PATH "Path to LLVM source 
tree")
 
@@ -95,7 +97,7 @@
 
   set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}")
 
-  include_directories("${LLVM_BINARY_DIR}/include" ${LLVM_INCLUDE_DIRS})
+  include_directories(${LLVM_INCLUDE_DIRS})
   link_directories(${LLVM_LIBRARY_DIRS})
 
   if(LLVM_INCLUDE_TESTS)
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -78,15 +78,17 @@
   if (NOT LLVM_CONFIG_FOUND)
 # Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
 # path is removed.
-set(MAIN_INCLUDE_DIR "${LLVM_INCLUDE_DIR}")
+set(INCLUDE_DIRS ${LLVM_INCLUDE_DIRS})
 set(LLVM_OBJ_DIR "${LLVM_BINARY_DIR}")
 # N.B. this is just a default value, the CACHE PATHs below can be 
overriden.
 set(MAIN_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../llvm")
 set(TOOLS_BINARY_DIR "${LLVM_TOOLS_BINARY_DIR}")
 set(LIBRARY_DIR "${LLVM_LIBRARY_DIR}")
+  else()
+set(INCLUDE_DIRS "${LLVM_BINARY_DIR}/include" "${MAIN_INCLUDE_DIR}")
   endif()
 
-  set(LLVM_MAIN_INCLUDE_DIR "${MAIN_INCLUDE_DIR}" CACHE PATH "Path to 
llvm/include")
+  set(LLVM_INCLUDE_DIRS ${INCLUDE_DIRS} CACHE PATH "Path to llvm/include and 
any other header dirs needed")
   set(LLVM_BINARY_DIR "${LLVM_OBJ_ROOT}" CACHE PATH "Path to LLVM build tree")
   set(LLVM_MAIN_SRC_DIR "${MAIN_SRC_DIR}" CACHE PATH "Path to LLVM source 
tree")
   set(LLVM_TOOLS_BINARY_DIR "${TOOLS_BINARY_DIR}" CACHE PATH "Path to 
llvm/bin")
@@ -128,7 +130,7 @@
 set(LLVM_INCLUDE_TESTS ON)
   endif()
 
-  include_directories("${LLVM_BINARY_DIR}/include" "${LLVM_MAIN_INCLUDE_DIR}")
+  include_directories(${LLVM_INCLUDE_DIRS})
   link_directories("${LLVM_LIBRARY_DIR}")
 
   set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )


Index: lld/CMakeLists.txt
===
--- lld/CMakeLists.txt
+++ lld/CMakeLists.txt
@@ -70,13 +70,15 @@
   if (NOT LLVM_CONFIG_FOUND)
 # Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
 # path is removed.
-set(MAIN_INCLUDE_DIR "${LLVM_INCLUDE_DIR}")
+set(INCLUDE_DIRS ${LLVM_INCLUDE_DIRS})
 set(LLVM_OBJ_DIR "${LLVM_BINARY_DIR}")
 # N.B. this is just a default value, the CACHE PATHs below can be overridden.
 set(MAIN_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../llvm")
+  else()
+set(INCLUDE_DIRS "${LLVM_BINARY_DIR}/include" "${MAIN_INCLUDE_DIR}")
   endif()
 
-  set(LLVM_MAIN_INCLUDE_DIR "${MAIN_INCLUDE_DIR}" CACHE PATH "Path to llvm/include")
+  set(LLVM_INCLUDE_DIRS ${INCLUDE_DIRS} CACHE PATH "Path to llvm/include and any other header dirs needed")
   set(LLVM_BINARY_DIR "${LLVM_OBJ_ROOT}" CACHE PATH "Path to LLVM build tree")
   set(LLVM_MAIN_SRC_DIR "${MAIN_SRC_DIR}" CACHE PATH "Path to LLVM source tree")
 
@@ -95,7 +97,7 @@
 
   set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}")
 
-  include_directories("${LLVM_BINARY_DIR}/include" ${LLVM_INCLUDE_DIRS})
+  include_directories(${LLVM_INCLUDE_DIRS})
   link_directories(${LLVM_LIBRARY_DIRS})
 
   if(LLVM_INCLUDE_TESTS)
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -78,15 +78,17 @@
   if (NOT LLVM_CONFIG_FOUND)
 # Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
 # path is removed.
-set(MAIN_INCLUDE_DIR "${LLVM_INCLUDE_DIR}")
+set(INCLUDE_DIRS ${LLVM_INCLUDE_DIRS})
 set(LLVM_OBJ_DIR

[PATCH] D130519: [clang][dataflow] Add explicit "AST" nodes for implications and iff

2022-07-26 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev accepted this revision.
sgatev added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:40-41
 
 // Synthetic boolean values are either atomic values or composites that
 // represent conjunctions, disjunctions, and negations.
 AtomicBool,





Comment at: clang/lib/Analysis/FlowSensitive/DebugSupport.cpp:110
+  auto R = debugString(BV.getRightSubValue(), Depth + 1);
+  S = formatv("(=\n{0}\n{1})", L, R);
+  break;

I think `<=>` would be more natural.



Comment at: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp:201
+
+  expectUnsatisfiable(solve({NotEquivalent}));
+}

Let's add a label: `!((X <=> Y) <=> ((X ^ Y) v (!X ^ !Y)))`



Comment at: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp:303
+
+  expectUnsatisfiable(solve({NotEquivalent}));
+}

Let's add a label: `!((X => Y) <=> (!X v Y))`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130519

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


[clang] 7a5cb15 - [RISCV] Lazily add RVV C intrinsics.

2022-07-26 Thread Kito Cheng via cfe-commits

Author: Kito Cheng
Date: 2022-07-26T15:47:47+08:00
New Revision: 7a5cb15ea6facd82756adafae76d60f36a0b60fd

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

LOG: [RISCV] Lazily add RVV C intrinsics.

Leverage the method OpenCL uses that adds C intrinsics when the lookup
failed. There is no need to define C intrinsics in the header file any
more. It could help to avoid the large header file to speed up the
compilation of RVV source code. Besides that, only the C intrinsics used
by the users will be added into the declaration table.

This patch is based on https://reviews.llvm.org/D103228 and inspired by
OpenCL implementation.

### Experimental Results

 TL;DR:

- Binary size of clang increase ~200k, which is +0.07%  for debug build and 
+0.13% for release build.
- Single file compilation speed up ~33x for debug build and ~8.5x for release 
build
- Regression time reduce ~10% (`ninja check-all`, enable all targets)

 Header size change
```
   |  size | LoC |
--
Before | 4,434,725 |  69,749 |
After  | 6,140 | 162 |
```

 Single File Compilation Time
Testcase:
```
#include 

vint32m1_t test_vadd_vv_vfloat32m1_t(vint32m1_t op1, vint32m1_t op2, size_t vl) 
{
  return vadd(op1, op2, vl);
}
```
# Debug build:
Before:
```
real0m19.352s
user0m19.252s
sys 0m0.092s
```

After:
```
real0m0.576s
user0m0.552s
sys 0m0.024s
```

~33x speed up for debug build

# Release build:
Before:
```
real0m0.773s
user0m0.741s
sys 0m0.032s
```

After:
```
real0m0.092s
user0m0.080s
sys 0m0.012s
```

~8.5x speed up for release build

 Regression time
Note: the failed case is `tools/llvm-debuginfod-find/debuginfod.test` which is 
unrelated to this patch.

# Debug build
Before:
```
Testing Time: 1358.38s
  Skipped  :11
  Unsupported  :   446
  Passed   : 75767
  Expectedly Failed:   190
  Failed   : 1
```
After
```
Testing Time: 1220.29s
  Skipped  :11
  Unsupported  :   446
  Passed   : 75767
  Expectedly Failed:   190
  Failed   : 1
```
# Release build
Before:
```
Testing Time: 381.98s
  Skipped  :12
  Unsupported  :  1407
  Passed   : 74765
  Expectedly Failed:   176
  Failed   : 1
```
After:
```
Testing Time: 346.25s
  Skipped  :12
  Unsupported  :  1407
  Passed   : 74765
  Expectedly Failed:   176
  Failed   : 1
```

 Binary size of clang

# Debug build
Before
```
   textdata bss dec hex filename
335261851   12726004 552812 348540667   14c64efb
bin/clang
```
After
```
   textdata bss dec hex filename
335442803   12798708 552940 348794451   14ca2e53
bin/clang
```
+253K, +0.07% code size

# Release build
Before
```
   textdata bss dec hex filename
144123975   8374648  483140 152981763   91e5103 bin/clang
```
After
```
   textdata bss dec hex filename
144255762   8447296  483268 153186326   9217016 bin/clang
```
+204K, +0.13%

Authored-by: Kito Cheng 
Co-Authored-by: Hsiangkai Wang 

Reviewed By: khchen, aaron.ballman

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

Added: 
clang/include/clang/Sema/RISCVIntrinsicManager.h
clang/lib/Sema/SemaRISCVVectorLookup.cpp
clang/test/Sema/riscv-bad-intrinsic-pragma.c
clang/test/Sema/riscv-intrinsic-pragma.c

Modified: 
clang/include/clang/Basic/CMakeLists.txt
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Support/RISCVVIntrinsicUtils.h
clang/lib/Parse/ParsePragma.cpp
clang/lib/Sema/CMakeLists.txt
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaLookup.cpp
clang/lib/Support/RISCVVIntrinsicUtils.cpp
clang/utils/TableGen/RISCVVEmitter.cpp
clang/utils/TableGen/TableGen.cpp
clang/utils/TableGen/TableGenBackends.h

Removed: 




diff  --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 8cd891385a483..b930842ae8cfd 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -90,3 +90,6 @@ clang_tablegen(riscv_vector_builtins.inc 
-gen-riscv-vector-builtins
 clang_tablegen(riscv_vector_builtin_cg.inc -gen-riscv-vector-builtin-codegen
   SOURCE riscv_vector.td
   TARGET ClangRISCVVectorBuiltinCG)
+clang_tablegen(riscv_vector_builtin_sema.inc -gen-riscv-vector-builtin-sema
+  SOURCE riscv_vector.td
+  TARGET ClangRISCVVectorBuiltinSema)

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 7b65a

[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-07-26 Thread Kito Cheng 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.
kito-cheng marked an inline comment as done.
Closed by commit rG7a5cb15ea6fa: [RISCV] Lazily add RVV C intrinsics. (authored 
by kito-cheng).

Changed prior to commit:
  https://reviews.llvm.org/D111617?vs=444188&id=447601#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

Files:
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/RISCVIntrinsicManager.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/test/Sema/riscv-bad-intrinsic-pragma.c
  clang/test/Sema/riscv-intrinsic-pragma.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -110,6 +110,7 @@
 void EmitRVVHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitRVVBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
 void EmitCdeHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitCdeBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -88,6 +88,7 @@
   GenRISCVVectorHeader,
   GenRISCVVectorBuiltins,
   GenRISCVVectorBuiltinCG,
+  GenRISCVVectorBuiltinSema,
   GenAttrDocs,
   GenDiagDocs,
   GenOptDocs,
@@ -243,6 +244,8 @@
"Generate riscv_vector_builtins.inc for clang"),
 clEnumValN(GenRISCVVectorBuiltinCG, "gen-riscv-vector-builtin-codegen",
"Generate riscv_vector_builtin_cg.inc for clang"),
+clEnumValN(GenRISCVVectorBuiltinSema, "gen-riscv-vector-builtin-sema",
+   "Generate riscv_vector_builtin_sema.inc for clang"),
 clEnumValN(GenAttrDocs, "gen-attr-docs",
"Generate attribute documentation"),
 clEnumValN(GenDiagDocs, "gen-diag-docs",
@@ -458,6 +461,9 @@
   case GenRISCVVectorBuiltinCG:
 EmitRVVBuiltinCG(Records, OS);
 break;
+  case GenRISCVVectorBuiltinSema:
+EmitRVVBuiltinSema(Records, OS);
+break;
   case GenAttrDocs:
 EmitClangAttrDocs(Records, OS);
 break;
Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
@@ -29,6 +30,59 @@
 using namespace clang::RISCV;
 
 namespace {
+struct SemaRecord {
+  // Intrinsic name, e.g. vadd_vv
+  std::string Name;
+
+  // Overloaded intrinsic name, could be empty if can be computed from Name
+  // e.g. vadd
+  std::string OverloadedName;
+
+  // Supported type, mask of BasicType.
+  unsigned TypeRangeMask;
+
+  // Supported LMUL.
+  unsigned Log2LMULMask;
+
+  // Required extensions for this intrinsic.
+  unsigned RequiredExtensions;
+
+  // Prototype for this intrinsic.
+  SmallVector Prototype;
+
+  // Prototype for masked intrinsic.
+  SmallVector MaskedPrototype;
+
+  // Suffix of intrinsic name.
+  SmallVector Suffix;
+
+  // Suffix of overloaded intrinsic name.
+  SmallVector OverloadedSuffix;
+
+  // Number of field, large than 1 if it's segment load/store.
+  unsigned NF;
+};
+
+// Compressed function signature table.
+class SemaSignatureTable {
+private:
+  std::vector SignatureTable;
+
+  void insert(ArrayRef Signature);
+
+public:
+  static constexpr unsigned INVALID_INDEX = ~0U;
+
+  // Create compressed signature table from SemaRecords.
+  void init(ArrayRef SemaRecords);
+
+  // Query the Signature, return INVALID_INDEX if not found.
+  unsigned getIndex(ArrayRef Signature);
+
+  /// Print signature table in RVVHeader Record to \p OS
+  void print(raw_ostream &OS);
+};
+
 class RVVEmitter {
 private:
   RecordKeeper &Records;
@@ -45,22 +99,22 @@
   /// Emit all th

[PATCH] D126744: [RISCV][Clang] Support policy functions for vneg, vnot, vncvt, vwcvt, vwcvtu, vfabs and vfneg.

2022-07-26 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng accepted this revision.
kito-cheng added a comment.
This revision is now accepted and ready to land.

LGTM, and verified with internal testsuite :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126744

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


[PATCH] D126745: [RISCV][Clang] Support policy functions for vmerge, vfmerge and vcompress.

2022-07-26 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng accepted this revision.
kito-cheng added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: nlopes.

LGTM, and verified with internal testsuite :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126745

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


[PATCH] D126748: [RISCV][Clang] Support policy functions for Vector Reduction Instructions.

2022-07-26 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng accepted this revision.
kito-cheng added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: nlopes.

LGTM, and verified with internal testsuite :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126748

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


[PATCH] D126750: [RISCV][Clang] Support policy function for all vector segment load.

2022-07-26 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng accepted this revision.
kito-cheng added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: nlopes.

LGTM, and verified with internal testsuite :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126750

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


[PATCH] D126750: [RISCV][Clang] Support policy function for all vector segment load.

2022-07-26 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

While at it, could you switch those UndefValue with PoisonValue if possible?  
Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126750

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


[PATCH] D126748: [RISCV][Clang] Support policy functions for Vector Reduction Instructions.

2022-07-26 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

While at it, could you switch those UndefValue with PoisonValue if possible?  
Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126748

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


[PATCH] D126745: [RISCV][Clang] Support policy functions for vmerge, vfmerge and vcompress.

2022-07-26 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

While at it, could you switch those UndefValue with PoisonValue if possible?  
Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126745

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


[PATCH] D130145: [AArch64] Simplify BTI/PAC-RET module flags

2022-07-26 Thread Daniel Kiss via Phabricator via cfe-commits
danielkiss accepted this revision.
danielkiss added a comment.
This revision is now accepted and ready to land.

AutoUpgrade is added due to similar issue at a user.
LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130145

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


[PATCH] D130522: [clang][dataflow] Fix SAT solver crashes on `X ^ X` and `X v X`

2022-07-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr updated this revision to Diff 447609.
gribozavr added a comment.

Actually visit a subexpression


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130522

Files:
  clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
  clang/unittests/Analysis/FlowSensitive/SolverTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
@@ -120,7 +120,7 @@
   expectUnsatisfiable(solve({NotXAndY, XAndY}));
 }
 
-TEST(SolverTest, DisjunctionSameVars) {
+TEST(SolverTest, DisjunctionSameVarWithNegation) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
   auto NotX = Ctx.neg(X);
@@ -130,6 +130,15 @@
   expectSatisfiable(solve({XOrNotX}), _);
 }
 
+TEST(SolverTest, DisjunctionSameVar) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto XOrX = Ctx.disj(X, X);
+
+  // X v X
+  expectSatisfiable(solve({XOrX}), _);
+}
+
 TEST(SolverTest, ConjunctionSameVarsConflict) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
@@ -140,6 +149,15 @@
   expectUnsatisfiable(solve({XAndNotX}));
 }
 
+TEST(SolverTest, ConjunctionSameVar) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto XAndX = Ctx.conj(X, X);
+
+  // X ^ X
+  expectSatisfiable(solve({XAndX}), _);
+}
+
 TEST(SolverTest, PureVar) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
Index: clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
===
--- clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
+++ clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
@@ -263,30 +263,52 @@
   const Variable LeftSubVar = GetVar(&C->getLeftSubValue());
   const Variable RightSubVar = GetVar(&C->getRightSubValue());
 
-  // `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar));
-  Formula.addClause(negLit(Var), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
-
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&C->getLeftSubValue());
-  UnprocessedSubVals.push(&C->getRightSubValue());
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A ^ A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
+
+// Visit a sub-value of `Val` (pick any, they are identical).
+UnprocessedSubVals.push(&C->getLeftSubValue());
+  } else {
+// `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
+// which is already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(negLit(Var), posLit(RightSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
+
+// Visit the sub-values of `Val`.
+UnprocessedSubVals.push(&C->getLeftSubValue());
+UnprocessedSubVals.push(&C->getRightSubValue());
+  }
 } else if (auto *D = dyn_cast(Val)) {
   const Variable LeftSubVar = GetVar(&D->getLeftSubValue());
   const Variable RightSubVar = GetVar(&D->getRightSubValue());
 
-  // `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar));
-  Formula.addClause(posLit(Var), negLit(RightSubVar));
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A v A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
 
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&D->getLeftSubValue());
-  UnprocessedSubVals.push(&D->getRightSubValue());
+// Visit a sub-value of `Val` (pick any, they are identical).
+UnprocessedSubVals.push(&D->getLeftSubValue());
+  } else {
+// `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v

[clang] a618d5e - [analyzer] Structured binding to tuple-like types

2022-07-26 Thread via cfe-commits

Author: isuckatcs
Date: 2022-07-26T10:24:29+02:00
New Revision: a618d5e0dd5d6fee5d73e823dbf8301663be0b4f

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

LOG: [analyzer] Structured binding to tuple-like types

Introducing support for creating structured binding
to tuple-like types.

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

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

Modified: 
clang/lib/Analysis/CFG.cpp
clang/lib/Analysis/LiveVariables.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/Analysis/live-bindings-test.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 3937fffcff5a..84178ff488a5 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2932,6 +2932,20 @@ CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
 }
   }
 
+  // If we bind to a tuple-like type, we iterate over the HoldingVars, and
+  // create a DeclStmt for each of them.
+  if (const auto *DD = dyn_cast(VD)) {
+for (auto BD : llvm::reverse(DD->bindings())) {
+  if (auto *VD = BD->getHoldingVar()) {
+DeclGroupRef DG(VD);
+DeclStmt *DSNew =
+new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
+cfg->addSyntheticDeclStmt(DSNew, DS);
+Block = VisitDeclSubExpr(DSNew);
+  }
+}
+  }
+
   autoCreateBlock();
   appendStmt(Block, DS);
 

diff  --git a/clang/lib/Analysis/LiveVariables.cpp 
b/clang/lib/Analysis/LiveVariables.cpp
index 6c601c290c92..ff7f3ebe28f8 100644
--- a/clang/lib/Analysis/LiveVariables.cpp
+++ b/clang/lib/Analysis/LiveVariables.cpp
@@ -72,6 +72,11 @@ bool LiveVariables::LivenessValues::isLive(const VarDecl *D) 
const {
 bool alive = false;
 for (const BindingDecl *BD : DD->bindings())
   alive |= liveBindings.contains(BD);
+
+// Note: the only known case this condition is necessary, is when a bindig
+// to a tuple-like structure is created. The HoldingVar initializers have a
+// DeclRefExpr to the DecompositionDecl.
+alive |= liveDecls.contains(DD);
 return alive;
   }
   return liveDecls.contains(D);
@@ -343,8 +348,12 @@ void TransferFunctions::VisitBinaryOperator(BinaryOperator 
*B) {
 
   if (const BindingDecl* BD = dyn_cast(D)) {
 Killed = !BD->getType()->isReferenceType();
-if (Killed)
+if (Killed) {
+  if (const auto *HV = BD->getHoldingVar())
+val.liveDecls = LV.DSetFact.remove(val.liveDecls, HV);
+
   val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
+}
   } else if (const auto *VD = dyn_cast(D)) {
 Killed = writeShouldKill(VD);
 if (Killed)
@@ -371,8 +380,12 @@ void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
   const Decl* D = DR->getDecl();
   bool InAssignment = LV.inAssignment[DR];
   if (const auto *BD = dyn_cast(D)) {
-if (!InAssignment)
+if (!InAssignment) {
+  if (const auto *HV = BD->getHoldingVar())
+val.liveDecls = LV.DSetFact.add(val.liveDecls, HV);
+
   val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
+}
   } else if (const auto *VD = dyn_cast(D)) {
 if (!InAssignment && !isAlwaysAlive(VD))
   val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
@@ -382,8 +395,16 @@ void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
   for (const auto *DI : DS->decls()) {
 if (const auto *DD = dyn_cast(DI)) {
-  for (const auto *BD : DD->bindings())
+  for (const auto *BD : DD->bindings()) {
+if (const auto *HV = BD->getHoldingVar())
+  val.liveDecls = LV.DSetFact.remove(val.liveDecls, HV);
+
 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
+  }
+
+  // When a bindig to a tuple-like structure is created, the HoldingVar
+  // initializers have a DeclRefExpr to the DecompositionDecl.
+  val.liveDecls = LV.DSetFact.remove(val.liveDecls, DD);
 } else if (const auto *VD = dyn_cast(DI)) {
   if (!isAlwaysAlive(VD))
 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index bb2fdc83c8f8..936d4ed7c89b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2788,7 +2788,10 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
 
 SVal Base = state->getLValue(DD, LCtx);
 if (DD->getType()->isReferenceType()) {
-  Base = state->getSVal(Base.getAsRegion());
+  if (const MemRegion *R = Base.getAsRegion())
+Base = state->getSVal(R);
+  else
+Base = UnknownVal();
 

[PATCH] D128837: [analyzer] Structured binding to tuple-like types

2022-07-26 Thread Domján Dániel via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa618d5e0dd5d: [analyzer] Structured binding to tuple-like 
types (authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128837

Files:
  clang/lib/Analysis/CFG.cpp
  clang/lib/Analysis/LiveVariables.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/live-bindings-test.cpp
  clang/test/Analysis/uninit-structured-binding-tuple.cpp

Index: clang/test/Analysis/uninit-structured-binding-tuple.cpp
===
--- /dev/null
+++ clang/test/Analysis/uninit-structured-binding-tuple.cpp
@@ -0,0 +1,580 @@
+// RUN: %clang_analyze_cc1 -Wno-ignored-reference-qualifiers -analyzer-checker=core,debug.ExprInspection -std=c++17 -verify %s
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void clang_analyzer_eval(bool);
+
+namespace std {
+template 
+struct tuple_size {
+};
+
+template 
+struct tuple_element {
+};
+
+// The std::pair in our system header simulator is not tuple-like, so a tuple-like mock is created here
+template 
+struct mock_pair {
+  T1 first;
+  T2 second;
+};
+template 
+struct tuple_size> {
+  static const std::size_t value = 2;
+};
+
+template 
+struct tuple_element<0, mock_pair> {
+  using type = T1;
+};
+
+template 
+struct tuple_element<1, mock_pair> {
+  using type = T2;
+};
+
+template 
+using tuple_element_t = typename tuple_element::type;
+
+template 
+constexpr std::tuple_element_t> &
+get(std::mock_pair &p) noexcept {
+  if (I == 0)
+return p.first;
+  else
+return p.second;
+}
+
+template 
+constexpr const std::tuple_element_t> &
+get(const std::mock_pair &p) noexcept {
+  if (I == 0)
+return p.first;
+  else
+return p.second;
+}
+
+template 
+constexpr std::tuple_element_t> &&
+get(std::mock_pair &&p) noexcept {
+
+  if (I == 0)
+return static_cast> &&>(p.first);
+  else
+return static_cast> &&>(p.second);
+}
+
+template 
+constexpr const std::tuple_element_t> &&
+get(const std::mock_pair &&p) noexcept {
+  if (I == 0)
+return static_cast> &&>(p.first);
+  else
+return static_cast> &&>(p.second);
+}
+
+} // namespace std
+// A utility that generates a tuple-like struct with 2 fields
+//  of the same type. The fields are 'first' and 'second'
+#define GENERATE_TUPLE_LIKE_STRUCT(name, element_type) \
+  struct name {\
+element_type first;\
+element_type second;   \
+  };   \
+   \
+  namespace std {  \
+  template <>  \
+  struct tuple_size {\
+static const std::size_t value = 2;\
+  };   \
+   \
+  template  \
+  struct tuple_element {  \
+using type = element_type; \
+  };   \
+  }
+
+void non_user_defined_by_value(void) {
+  std::mock_pair p = {1, 2};
+
+  auto [u, v] = p;
+
+  clang_analyzer_eval(u == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(v == 2); // expected-warning{{TRUE}}
+
+  int x = u;
+  u = 10;
+  int y = u;
+
+  clang_analyzer_eval(x == 1);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(u == 10); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y == 10);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(p.first == 1); // expected-warning{{TRUE}}
+
+  p.first = 5;
+
+  clang_analyzer_eval(u == 10); // expected-warning{{TRUE}}
+}
+
+void non_user_defined_by_lref(void) {
+  std::mock_pair p = {1, 2};
+
+  auto &[u, v] = p;
+
+  int x = u;
+  u = 10;
+  int y = u;
+
+  clang_analyzer_eval(x == 1);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(u == 10); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y == 10);   // expected-warning{{TRUE}}
+  clang_analyzer_eval(p.first == 10); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(v == 2);// expected-warning{{TRUE}}
+  clang_analyzer_eval(p.second == 2); // expected-warning{{TRUE}}
+
+  p.first = 5;
+
+  clang_analyzer_eval(u == 5); // expected-warning{{TRUE}}
+}
+
+void non_user_defined_by_rref(void) {
+  std::mock_pair p = {1, 2};
+
+  auto &&[u, v] = p;
+
+  int x = u;
+  u = 10;
+  int y = u;
+
+  clang_analyzer_eval(x == 1);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(u == 10); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(y == 10);   // expected-warning{{TRUE}}
+  clang_analyzer_eval(p.first == 10); // expected-warning

[clang] 3281138 - [clang][dataflow] Fix SAT solver crashes on `X ^ X` and `X v X`

2022-07-26 Thread Dmitri Gribenko via cfe-commits

Author: Dmitri Gribenko
Date: 2022-07-26T10:26:44+02:00
New Revision: 3281138aad80fcefc7f266c7e3b2e359d5dbc8da

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

LOG: [clang][dataflow] Fix SAT solver crashes on `X ^ X` and `X v X`

BooleanFormula::addClause has an invariant that a clause has no duplicated
literals. When the solver was desugaring a formula into CNF clauses, it
could construct a clause with such duplicated literals in two cases.

Reviewed By: sgatev, ymandel, xazax.hun

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
clang/unittests/Analysis/FlowSensitive/SolverTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp 
b/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
index 6a3948bd1fea0..b081543ac1333 100644
--- a/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
+++ b/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
@@ -263,30 +263,52 @@ BooleanFormula buildBooleanFormula(const 
llvm::DenseSet &Vals) {
   const Variable LeftSubVar = GetVar(&C->getLeftSubValue());
   const Variable RightSubVar = GetVar(&C->getRightSubValue());
 
-  // `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar));
-  Formula.addClause(negLit(Var), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
-
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&C->getLeftSubValue());
-  UnprocessedSubVals.push(&C->getRightSubValue());
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A ^ A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
+
+// Visit a sub-value of `Val` (pick any, they are identical).
+UnprocessedSubVals.push(&C->getLeftSubValue());
+  } else {
+// `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v 
!B)`
+// which is already in conjunctive normal form. Below we add each of 
the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(negLit(Var), posLit(RightSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar), 
negLit(RightSubVar));
+
+// Visit the sub-values of `Val`.
+UnprocessedSubVals.push(&C->getLeftSubValue());
+UnprocessedSubVals.push(&C->getRightSubValue());
+  }
 } else if (auto *D = dyn_cast(Val)) {
   const Variable LeftSubVar = GetVar(&D->getLeftSubValue());
   const Variable RightSubVar = GetVar(&D->getRightSubValue());
 
-  // `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar));
-  Formula.addClause(posLit(Var), negLit(RightSubVar));
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A v A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
 
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&D->getLeftSubValue());
-  UnprocessedSubVals.push(&D->getRightSubValue());
+// Visit a sub-value of `Val` (pick any, they are identical).
+UnprocessedSubVals.push(&D->getLeftSubValue());
+  } else {
+// `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v 
!B)`
+// which is already in conjunctive normal form. Below we add each of 
the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar), 
posLit(RightSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(RightSubVar));
+
+// Visit the sub-values of `Val`.
+UnprocessedSubVals.push(&D->getLeftSubValue());
+UnprocessedSubVals.push(&

[PATCH] D130522: [clang][dataflow] Fix SAT solver crashes on `X ^ X` and `X v X`

2022-07-26 Thread Dmitri Gribenko 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 rG3281138aad80: [clang][dataflow] Fix SAT solver crashes on `X 
^ X` and `X v X` (authored by gribozavr).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130522

Files:
  clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
  clang/unittests/Analysis/FlowSensitive/SolverTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
@@ -120,7 +120,7 @@
   expectUnsatisfiable(solve({NotXAndY, XAndY}));
 }
 
-TEST(SolverTest, DisjunctionSameVars) {
+TEST(SolverTest, DisjunctionSameVarWithNegation) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
   auto NotX = Ctx.neg(X);
@@ -130,6 +130,15 @@
   expectSatisfiable(solve({XOrNotX}), _);
 }
 
+TEST(SolverTest, DisjunctionSameVar) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto XOrX = Ctx.disj(X, X);
+
+  // X v X
+  expectSatisfiable(solve({XOrX}), _);
+}
+
 TEST(SolverTest, ConjunctionSameVarsConflict) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
@@ -140,6 +149,15 @@
   expectUnsatisfiable(solve({XAndNotX}));
 }
 
+TEST(SolverTest, ConjunctionSameVar) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto XAndX = Ctx.conj(X, X);
+
+  // X ^ X
+  expectSatisfiable(solve({XAndX}), _);
+}
+
 TEST(SolverTest, PureVar) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
Index: clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
===
--- clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
+++ clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
@@ -263,30 +263,52 @@
   const Variable LeftSubVar = GetVar(&C->getLeftSubValue());
   const Variable RightSubVar = GetVar(&C->getRightSubValue());
 
-  // `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar));
-  Formula.addClause(negLit(Var), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
-
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&C->getLeftSubValue());
-  UnprocessedSubVals.push(&C->getRightSubValue());
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A ^ A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
+
+// Visit a sub-value of `Val` (pick any, they are identical).
+UnprocessedSubVals.push(&C->getLeftSubValue());
+  } else {
+// `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
+// which is already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(negLit(Var), posLit(RightSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
+
+// Visit the sub-values of `Val`.
+UnprocessedSubVals.push(&C->getLeftSubValue());
+UnprocessedSubVals.push(&C->getRightSubValue());
+  }
 } else if (auto *D = dyn_cast(Val)) {
   const Variable LeftSubVar = GetVar(&D->getLeftSubValue());
   const Variable RightSubVar = GetVar(&D->getRightSubValue());
 
-  // `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v !B)`
-  // which is already in conjunctive normal form. Below we add each of the
-  // conjuncts of the latter expression to the result.
-  Formula.addClause(negLit(Var), posLit(LeftSubVar), posLit(RightSubVar));
-  Formula.addClause(posLit(Var), negLit(LeftSubVar));
-  Formula.addClause(posLit(Var), negLit(RightSubVar));
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A v A)` is equivalent to `(!X v A) ^ (X v !A)` which is
+// already in conjunctive normal form. Below we add each of the
+// conjuncts of the latter expression to the result.
+Formula.addClause(negLit(Var), posLit(LeftSubVar));
+Formula.addClause(posLit(Var), negLit(LeftSubVar));
 
-  // Visit the sub-values of `Val`.
-  UnprocessedSubVals.push(&D->getLeftSubValue());
-  UnprocessedSubVals.push(&D->getRightSubValue());
+// Visit a sub-value of `Val` (pick any, they are identical).
+   

[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Roman Rusyaev via Phabricator via cfe-commits
rusyaev-roman added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

ChuanqiXu wrote:
> rusyaev-roman wrote:
> > rusyaev-roman wrote:
> > > rusyaev-roman wrote:
> > > > ChuanqiXu wrote:
> > > > > rusyaev-roman wrote:
> > > > > > ChuanqiXu wrote:
> > > > > > > rusyaev-roman wrote:
> > > > > > > > ChuanqiXu wrote:
> > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > > > What if NRVO contains a value already? It is 
> > > > > > > > > > > > > > > possible due to the value of NRVO could be set by 
> > > > > > > > > > > > > > > its children.
> > > > > > > > > > > > > > Actually this is intention. If the parent has 
> > > > > > > > > > > > > > already NRVO candidate, then it should be 
> > > > > > > > > > > > > > invalidated (or not). Let's consider the following 
> > > > > > > > > > > > > > examples:
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > >else
> > > > > > > > > > > > > >   return y; // when we process this return 
> > > > > > > > > > > > > > statement, the parent has already NRVO and it will 
> > > > > > > > > > > > > > be invalidated (this is correct behavior)
> > > > > > > > > > > > > > }
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > >
> > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > parent has already NRVO and it WON't be invalidated
> > > > > > > > > > > > > >//  (this is correct behavior), because a return 
> > > > > > > > > > > > > > slot will be available for it
> > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > }
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > parent has already NRVO and it WON't be invalidated 
> > > > > > > > > > > > > > (this is correct behavior)
> > > > > > > > > > > > > >return x;
> > > > > > > > > > > > > > }
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > >
> > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > parent contains nullptr (invalid candidate) and it 
> > > > > > > > > > > > > > will be invalidated (this is correct behavior)
> > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > }
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > parent contains nullptr (invalid candidate) and it 
> > > > > > > > > > > > > > WON't be invalidated (this is correct behavior)
> > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > }
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. 
> > > > > > > > > > > > > But I recommend to comment that the children would 
> > > > > > > > > > > > > maintain the `ReturnSlots` of their parents. (This is 
> > > > > > > > > > > > > anti-intuition)
> > > > > > > > > > > > > 
> > > > > > > > > > > > > Have you tested any larger projects? Like libc++, 
> > > > > > > > > > > > > libstdc++ or something like folly. I feel we need to 
> > > > > > > > > > > > > do such tests to avoid we get anything wrong.
> > > > > > > > > > > > I've already added a comment at the beginning of 
> > > > > > > > 

[PATCH] D117973: [cmake] Support custom package install paths

2022-07-26 Thread Sebastian Neubauer via Phabricator via cfe-commits
sebastian-ne added a comment.

I found a regression when llvm is added with CMake’s add_subdirectory. D130555 
 has a fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117973

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


[PATCH] D126534: [analyzer] Deadstore static analysis: Fix false positive on C++17 assignments

2022-07-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Looks good to me, but I think you should wait for @NoQ for approval as he had 
some concerns previously.
@NoQ, do you think it's in a good shape for landing?


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

https://reviews.llvm.org/D126534

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


[PATCH] D130513: [Flang] Add -fconvert option to swap endianness for unformatted files

2022-07-26 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for working on this. This is not my area of expertise, so I focused on 
the implementation in the driver.




Comment at: clang/include/clang/Driver/Options.td:4897
 def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Group, Alias;
+def fconvert_EQ : Joined<["-"], "fconvert=">, Group,
+  HelpText<"Set endian conversion of data for unformatted files">;

jpenix-quic wrote:
> peixin wrote:
> > Why do you move it here? Maybe it is not implemented now, clang may need 
> > this option eventually. @MaskRay 
> I was using the fixed line length options as a reference for how to handle 
> this--based on the discussion in the review here 
> (https://reviews.llvm.org/D95460) about forwarding options to gfortran, I was 
> thinking that it would also be safe to handle fconvert similarly, but I'm not 
> 100% sure and definitely might be misunderstanding something!
GFortran support has been effectively broken since LLVM 12 (see e.g. this [[ 
https://github.com/llvm/llvm-project/commit/6a75496836ea14bcfd2f4b59d35a1cad4ac58cee
 | change ]]). We would do ourselves a favor if we just removed it altogether 
(I'm not aware of anyone requiring  it). 

And if Clang ever needs this option, we can always update this definition 
accordingly. No need to optimize for hypothetical scenarios that may or may not 
happen :) To me, this change makes perfect sense.



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:52
+options::OPT_fno_automatic,
+options::OPT_fconvert_EQ});
 }

jpenix-quic wrote:
> Reading through https://reviews.llvm.org/D95460 again, I'm not sure this is 
> the appropriate place to add . I am marking this as a TODO that I will 
> revisit with the other feedback!
You can use `AddOtherOptions` instead. `AddFortranDialectOptions` is more about 
language options. Is this a language option? It's a bit of a borderline. Feel 
free to add another hook too.

Btw, the reformatting is an unrelated change. Could you submit in a separate 
patch? Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130513

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


[PATCH] D130511: [pseudo][wip] Eliminate simple-type-specifier ambiguities.

2022-07-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D130511#3677423 , @sammccall wrote:

> My main concern here is that this might reject valid code (and if it doesn't, 
> it's not obvious why).
> It does look like C++ forbids the cases I can come up with (e.g. trying to 
> provide a definition for `::Foo` is rejected by clang with "definition or 
> redeclaration of Foo cannot name the global scope).
> But I'd be way more comfortable if we could connect the specific guard rules 
> here with spec language.

The qualified declarator is tricky (it was forbidden until 
https://cplusplus.github.io/CWG/issues/482.html).

The closest thing I can find in the standard is basic.lookup.qual.general 
:

> If a name, template-id, or decltype-specifier is followed by a ​::​, it shall 
> designate a namespace, class, enumeration, or dependent type, and the ​::​ is 
> never interpreted as a complete nested-name-specifier.

IIUC, this rule forbids the parses `X::Y ::Z;` and `X ::Y::Z;` (because in the 
declarator we have a complete `::` nested-name-specifier).

> If we can't do this rigorously and merely are trying to encourage the 
> *common* parse, then we should do it in soft disambig.
>
> I'd like to think about this some more, do you know what part of the spec 
> says that `x ::y` is invalid if x is e.g. a typedef for `int`?

I didn't try to find it harder, I guess it is probably in the 
qualified-name-look-up section.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130511

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


[PATCH] D119792: [Clang] [P2025] Analyze only potential scopes for NRVO

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/Scope.cpp:152-154
+  // Consider the variable as NRVO candidate if the return slot is available
+  // for it in the current scope, or if it can be available in outer scopes.
+  NRVO = CanBePutInReturnSlot ? VD : nullptr;

rusyaev-roman wrote:
> ChuanqiXu wrote:
> > rusyaev-roman wrote:
> > > rusyaev-roman wrote:
> > > > rusyaev-roman wrote:
> > > > > ChuanqiXu wrote:
> > > > > > rusyaev-roman wrote:
> > > > > > > ChuanqiXu wrote:
> > > > > > > > rusyaev-roman wrote:
> > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > > rusyaev-roman wrote:
> > > > > > > > > > > > > > > ChuanqiXu wrote:
> > > > > > > > > > > > > > > > What if NRVO contains a value already? It is 
> > > > > > > > > > > > > > > > possible due to the value of NRVO could be set 
> > > > > > > > > > > > > > > > by its children.
> > > > > > > > > > > > > > > Actually this is intention. If the parent has 
> > > > > > > > > > > > > > > already NRVO candidate, then it should be 
> > > > > > > > > > > > > > > invalidated (or not). Let's consider the 
> > > > > > > > > > > > > > > following examples:
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > >else
> > > > > > > > > > > > > > >   return y; // when we process this return 
> > > > > > > > > > > > > > > statement, the parent has already NRVO and it 
> > > > > > > > > > > > > > > will be invalidated (this is correct behavior)
> > > > > > > > > > > > > > > }
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > > parent has already NRVO and it WON't be 
> > > > > > > > > > > > > > > invalidated
> > > > > > > > > > > > > > >//  (this is correct behavior), because a 
> > > > > > > > > > > > > > > return slot will be available for it
> > > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > > }
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > X foo(bool b) {
> > > > > > > > > > > > > > >X x;
> > > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > > parent has already NRVO and it WON't be 
> > > > > > > > > > > > > > > invalidated (this is correct behavior)
> > > > > > > > > > > > > > >return x;
> > > > > > > > > > > > > > > }
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > > parent contains nullptr (invalid candidate) and 
> > > > > > > > > > > > > > > it will be invalidated (this is correct behavior)
> > > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > > }
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > > X foo(bool b, X x) {
> > > > > > > > > > > > > > >if (b)
> > > > > > > > > > > > > > >   return x;
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > >X y;
> > > > > > > > > > > > > > >// when we process this return statement, the 
> > > > > > > > > > > > > > > parent contains nullptr (invalid candidate) and 
> > > > > > > > > > > > > > > it WON't be invalidated (this is correct behavior)
> > > > > > > > > > > > > > >return y;
> > > > > > > > > > > > > > > }
> > > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > Oh, I see. Tricky. I don't find invalid cases now. 
> > > > > > > > > > > > > > But I recommend to comment that the children would 
> > > > > > > > > > > > > > maintain the `ReturnSlots` of their parents. (This 
> > > > > > > > > > > > > > is anti-intuition)
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > Have you tested any larger projects? Like libc++, 

[clang] f3fbbe1 - [clang][analyzer][NFC] Use value_or instead of ValueOr

2022-07-26 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2022-07-26T09:16:45Z
New Revision: f3fbbe1cf33bf4da8e2620c770997d9ff68a5384

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

LOG: [clang][analyzer][NFC] Use value_or instead of ValueOr

The latter is deprecated.

Added: 


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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index 836311a69309..04e00274b2a7 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -589,7 +589,7 @@ void ExprEngine::handleConstructor(const Expr *E,
 
 unsigned Idx = 0;
 if (CE->getType()->isArrayType() || AILE) {
-  Idx = getIndexOfElementToConstruct(State, CE, LCtx).getValueOr(0u);
+  Idx = getIndexOfElementToConstruct(State, CE, LCtx).value_or(0u);
   State = setIndexOfElementToConstruct(State, CE, LCtx, Idx + 1);
 }
 



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


[clang] ad17e69 - [analyzer] Fix unused variable warning in release builds. NFC.

2022-07-26 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2022-07-26T11:29:38+02:00
New Revision: ad17e69923ec39b6439ac0041e69de1f1f5ecec4

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

LOG: [analyzer] Fix unused variable warning in release builds. NFC.

Added: 


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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 936d4ed7c89b..19149d079822 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -541,8 +541,6 @@ ExprEngine::addObjectUnderConstruction(ProgramStateRef 
State,
   if (const auto *AILE = dyn_cast_or_null(Init))
 Init = AILE->getSubExpr();
 
-  const auto *E = dyn_cast_or_null(Init);
-
   // FIXME: Currently the state might already contain the marker due to
   // incorrect handling of temporaries bound to default parameters.
   // The state will already contain the marker if we construct elements
@@ -552,7 +550,8 @@ ExprEngine::addObjectUnderConstruction(ProgramStateRef 
State,
   assert((!State->get(Key) ||
   Key.getItem().getKind() ==
   ConstructionContextItem::TemporaryDestructorKind ||
-  State->contains({E, LC})) &&
+  State->contains(
+  {dyn_cast_or_null(Init), LC})) &&
  "The object is already marked as `UnderConstruction`, when it's not "
  "supposed to!");
   return State->set(Key, V);



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


[clang] bc4eef5 - [RISCV][Clang] Refactor and rename rvv intrinsic related stuff. (NFC)

2022-07-26 Thread Zakk Chen via cfe-commits

Author: Zakk Chen
Date: 2022-07-26T09:35:34Z
New Revision: bc4eef509b21e5ba72dcf18f949eae27087a7b9c

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

LOG: [RISCV][Clang] Refactor and rename rvv intrinsic related stuff. (NFC)

This changed is based on https://reviews.llvm.org/D111617

Reviewed By: rogfer01

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

Added: 


Modified: 
clang/include/clang/Basic/riscv_vector.td
clang/include/clang/Support/RISCVVIntrinsicUtils.h
clang/lib/Support/RISCVVIntrinsicUtils.cpp
clang/utils/TableGen/RISCVVEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index d96020ee40d0..6b21f48110de 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -186,7 +186,7 @@ class RVVBuiltin : 
RVVOp0Builtin<"m", prototype, "c"> {
   let HasMaskedOffOperand = false;
 }
 
-let UnMaskedPolicy = HasPolicyOperand,
+let UnMaskedPolicyScheme = HasPolicyOperand,
 HasMaskedOffOperand = false in {
   multiclass RVVSlideBuiltinSet {
 defm "" : RVVOutBuiltinSet {
 }
 
 let HasUnMaskedOverloaded = false,
-MaskedPolicy = NonePolicy in {
+MaskedPolicyScheme = NonePolicy in {
   class RVVVLEMaskBuiltin : RVVOutBuiltin<"m", "mPCUe", "c"> {
 let Name = "vlm_v";
 let IRName = "vlm";
@@ -591,7 +591,7 @@ let HasUnMaskedOverloaded = false,
 }
 
 let HasUnMaskedOverloaded = false,
-UnMaskedPolicy = HasPassthruOperand in {
+UnMaskedPolicyScheme = HasPassthruOperand in {
   multiclass RVVVLEBuiltin types> {
 let Name = NAME # "_v",
 IRName = "vle",
@@ -664,7 +664,7 @@ multiclass RVVVLSEBuiltin types> {
   IRName = "vlse",
   MaskedIRName ="vlse_mask",
   HasUnMaskedOverloaded = false,
-  UnMaskedPolicy = HasPassthruOperand in {
+  UnMaskedPolicyScheme = HasPassthruOperand in {
 foreach type = types in {
   def : RVVOutBuiltin<"v", "vPCet", type>;
   if !not(IsFloat.val) then {
@@ -675,7 +675,7 @@ multiclass RVVVLSEBuiltin types> {
 }
 
 multiclass RVVIndexedLoad {
-  let UnMaskedPolicy = HasPassthruOperand in {
+  let UnMaskedPolicyScheme = HasPassthruOperand in {
 foreach type = TypeList in {
   foreach eew_list = EEWList[0-2] in {
 defvar eew = eew_list[0];
@@ -701,7 +701,7 @@ multiclass RVVIndexedLoad {
 }
 
 let HasMaskedOffOperand = false,
-MaskedPolicy = NonePolicy,
+MaskedPolicyScheme = NonePolicy,
 ManualCodegen = [{
   // Builtin: (ptr, value, vl). Intrinsic: (value, ptr, vl)
   std::swap(Ops[0], Ops[1]);
@@ -738,7 +738,7 @@ multiclass RVVVSSEBuiltin types> {
   IRName = "vsse",
   MaskedIRName = "vsse_mask",
   HasMaskedOffOperand = false,
-  MaskedPolicy = NonePolicy,
+  MaskedPolicyScheme = NonePolicy,
   ManualCodegen = [{
 // Builtin: (ptr, stride, value, vl). Intrinsic: (value, ptr, stride, 
vl)
 std::rotate(Ops.begin(), Ops.begin() + 2, Ops.begin() + 3);
@@ -762,7 +762,7 @@ multiclass RVVVSSEBuiltin types> {
 
 multiclass RVVIndexedStore {
   let HasMaskedOffOperand = false,
-  MaskedPolicy = NonePolicy,
+  MaskedPolicyScheme = NonePolicy,
   ManualCodegen = [{
 // Builtin: (ptr, index, value, vl). Intrinsic: (value, ptr, index, vl)
 std::rotate(Ops.begin(), Ops.begin() + 2, Ops.begin() + 3);
@@ -1141,7 +1141,7 @@ multiclass RVVUnitStridedSegStore {
 MaskedIRName = op # nf # "_mask",
 NF = nf,
 HasMaskedOffOperand = false,
-MaskedPolicy = NonePolicy,
+MaskedPolicyScheme = NonePolicy,
 ManualCodegen = [{
 {
   // Builtin: (ptr, val0, val1, ..., vl)
@@ -1187,7 +1187,7 @@ multiclass RVVStridedSegStore {
 MaskedIRName = op # nf # "_mask",
 NF = nf,
 HasMaskedOffOperand = false,
-MaskedPolicy = NonePolicy,
+MaskedPolicyScheme = NonePolicy,
 ManualCodegen = [{
 {
   // Builtin: (ptr, stride, val0, val1, ..., vl).
@@ -1229,7 +1229,7 @@ multiclass RVVIndexedSegStore {
 MaskedIRName = op # nf # "_mask",
 NF = nf,
 HasMaskedOffOperand = false,
-MaskedPolicy = NonePolicy,
+MaskedPolicyScheme = NonePolicy,
 ManualCodegen = [{
 {
   // Builtin: (ptr, index, val0, val1, ..., vl)
@@ -1568,7 +1568,7 @@ def vsetvl_macro: RVVHeader;
 let HasBuiltinAlias = false,
 HasVL = false,
 HasMasked = false,
-MaskedPolicy = NonePolicy,
+MaskedPolicyScheme = NonePolicy,
 Log2LMUL = [0],
 ManualCodegen = [{IntrinsicTypes = {ResultType};}] in // Set XLEN type
 {
@@ -1627,7 +1627,7 @@ defm : RVVIndexedSegStore<"vsoxseg">;
 

[PATCH] D126740: [RISCV][Clang] Refactor and rename rvv intrinsic related stuff. (NFC)

2022-07-26 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 rGbc4eef509b21: [RISCV][Clang] Refactor and rename rvv 
intrinsic related stuff. (NFC) (authored by khchen).

Changed prior to commit:
  https://reviews.llvm.org/D126740?vs=433256&id=447630#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126740

Files:
  clang/include/clang/Basic/riscv_vector.td
  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
@@ -479,12 +479,12 @@
 bool HasMasked = R->getValueAsBit("HasMasked");
 bool HasMaskedOffOperand = R->getValueAsBit("HasMaskedOffOperand");
 bool HasVL = R->getValueAsBit("HasVL");
-Record *MaskedPolicyRecord = R->getValueAsDef("MaskedPolicy");
-PolicyScheme MaskedPolicy =
-static_cast(MaskedPolicyRecord->getValueAsInt("Value"));
-Record *UnMaskedPolicyRecord = R->getValueAsDef("UnMaskedPolicy");
-PolicyScheme UnMaskedPolicy =
-static_cast(UnMaskedPolicyRecord->getValueAsInt("Value"));
+Record *MPSRecord = R->getValueAsDef("MaskedPolicyScheme");
+auto MaskedPolicyScheme =
+static_cast(MPSRecord->getValueAsInt("Value"));
+Record *UMPSRecord = R->getValueAsDef("UnMaskedPolicyScheme");
+auto UnMaskedPolicyScheme =
+static_cast(UMPSRecord->getValueAsInt("Value"));
 bool HasUnMaskedOverloaded = R->getValueAsBit("HasUnMaskedOverloaded");
 std::vector Log2LMULList = R->getValueAsListOfInts("Log2LMUL");
 bool HasBuiltinAlias = R->getValueAsBit("HasBuiltinAlias");
@@ -500,50 +500,19 @@
 
 // Parse prototype and create a list of primitive type with transformers
 // (operand) in Prototype. Prototype[0] is output operand.
-SmallVector Prototype = parsePrototypes(Prototypes);
+SmallVector BasicPrototype =
+parsePrototypes(Prototypes);
 
 SmallVector SuffixDesc = parsePrototypes(SuffixProto);
 SmallVector OverloadedSuffixDesc =
 parsePrototypes(OverloadedSuffixProto);
 
 // Compute Builtin types
-SmallVector MaskedPrototype = Prototype;
-if (HasMasked) {
-  // If HasMaskedOffOperand, insert result type as first input operand.
-  if (HasMaskedOffOperand) {
-if (NF == 1) {
-  MaskedPrototype.insert(MaskedPrototype.begin() + 1, Prototype[0]);
-} else {
-  // Convert
-  // (void, op0 address, op1 address, ...)
-  // to
-  // (void, op0 address, op1 address, ..., maskedoff0, maskedoff1, ...)
-  PrototypeDescriptor MaskoffType = Prototype[1];
-  MaskoffType.TM &= ~static_cast(TypeModifier::Pointer);
-  for (unsigned I = 0; I < NF; ++I)
-MaskedPrototype.insert(MaskedPrototype.begin() + NF + 1,
-   MaskoffType);
-}
-  }
-  if (HasMaskedOffOperand && NF > 1) {
-// Convert
-// (void, op0 address, op1 address, ..., maskedoff0, maskedoff1, ...)
-// to
-// (void, op0 address, op1 address, ..., mask, maskedoff0, maskedoff1,
-// ...)
-MaskedPrototype.insert(MaskedPrototype.begin() + NF + 1,
-   PrototypeDescriptor::Mask);
-  } else {
-// If HasMasked, insert PrototypeDescriptor:Mask as first input operand.
-MaskedPrototype.insert(MaskedPrototype.begin() + 1,
-   PrototypeDescriptor::Mask);
-  }
-}
-// If HasVL, append PrototypeDescriptor:VL to last operand
-if (HasVL) {
-  Prototype.push_back(PrototypeDescriptor::VL);
-  MaskedPrototype.push_back(PrototypeDescriptor::VL);
-}
+auto Prototype = RVVIntrinsic::computeBuiltinTypes(
+BasicPrototype, /*IsMasked=*/false, /*HasMaskedOffOperand=*/false,
+HasVL, NF);
+auto MaskedPrototype = RVVIntrinsic::computeBuiltinTypes(
+BasicPrototype, /*IsMasked=*/true, HasMaskedOffOperand, HasVL, NF);
 
 // Create Intrinsics for each type and LMUL.
 for (char I : TypeRange) {
@@ -562,7 +531,7 @@
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffixStr, IRName,
 /*IsMasked=*/false, /*HasMaskedOffOperand=*/false, HasVL,
-UnMaskedPolicy, HasUnMaskedOverloaded, HasBuiltinAlias,
+UnMaskedPolicyScheme, HasUnMaskedOverloaded, HasBuiltinAlias,
 ManualCodegen, *Types, IntrinsicTypes, RequiredFeatures, NF));
 if (HasMasked) {
   // Create a masked intrinsic
@@ -571,7 +540,7 @@
   Out.push_back(std::make_unique(
   Name, SuffixStr, OverloadedName, Overloade

[PATCH] D130545: [cmake] Slight fix ups to make robust to the full range of GNUInstallDirs

2022-07-26 Thread Sebastian Neubauer via Phabricator via cfe-commits
sebastian-ne accepted this revision.
sebastian-ne added a comment.
This revision is now accepted and ready to land.

Looks good to me




Comment at: openmp/CMakeLists.txt:3
 
-# Add cmake directory to search for custom cmake functions.
-set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
+set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+

There are some places that surround this by an `if(NOT DEFINED 
LLVM_COMMON_CMAKE_UTILS)` (e.g. lldb/cmake/modules/LLDBStandalone.cmake, 
clang/CMakeLists.txt, polly/CMakeLists.txt) although other places don’t 
(lld/CMakeLists.txt, libunwind/CMakeLists.txt, etc.), so both seem to be fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130545

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


[PATCH] D130551: [pseudo] Allow opaque nodes to represent terminals

2022-07-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

The change looks good, are you planning to use it in the cxx.bnf?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130551

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


[PATCH] D130553: [clang][lld][cmake] Simplify header dirs

2022-07-26 Thread Sebastian Neubauer via Phabricator via cfe-commits
sebastian-ne added inline comments.



Comment at: clang/CMakeLists.txt:81
 # path is removed.
-set(MAIN_INCLUDE_DIR "${LLVM_INCLUDE_DIR}")
+set(INCLUDE_DIRS ${LLVM_INCLUDE_DIRS})
 set(LLVM_OBJ_DIR "${LLVM_BINARY_DIR}")

Do we need to add `"${LLVM_BINARY_DIR}/include"` here as well?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130553

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


[clang] 93f8657 - [RISCV][Clang] Refactor RISCVVEmitter. (NFC)

2022-07-26 Thread Zakk Chen via cfe-commits

Author: Zakk Chen
Date: 2022-07-26T10:15:04Z
New Revision: 93f8657c743ba9ce9696e5f0c9487207cf8ccb6b

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

LOG: [RISCV][Clang] Refactor RISCVVEmitter. (NFC)

Remove MaskedPrototype and add several fields in RVVIntrinsicRecord,
compute Prototype in runtime.

Reviewed By: rogfer01

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

Added: 


Modified: 
clang/include/clang/Support/RISCVVIntrinsicUtils.h
clang/lib/Sema/SemaRISCVVectorLookup.cpp
clang/lib/Support/RISCVVIntrinsicUtils.cpp
clang/utils/TableGen/RISCVVEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h 
b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
index 44c4125a85da..7ee4896eea09 100644
--- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -371,9 +371,6 @@ struct RVVIntrinsicRecord {
   // Prototype for this intrinsic, index of RVVSignatureTable.
   uint16_t PrototypeIndex;
 
-  // Prototype for masked intrinsic, index of RVVSignatureTable.
-  uint16_t MaskedPrototypeIndex;
-
   // Suffix of intrinsic name, index of RVVSignatureTable.
   uint16_t SuffixIndex;
 
@@ -383,9 +380,6 @@ struct RVVIntrinsicRecord {
   // Length of the prototype.
   uint8_t PrototypeLength;
 
-  // Length of prototype of masked intrinsic.
-  uint8_t MaskedPrototypeLength;
-
   // Length of intrinsic name suffix.
   uint8_t SuffixLength;
 
@@ -403,6 +397,10 @@ struct RVVIntrinsicRecord {
 
   // Number of fields, greater than 1 if it's segment load/store.
   uint8_t NF;
+
+  bool HasMasked : 1;
+  bool HasVL : 1;
+  bool HasMaskedOffOperand : 1;
 };
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,

diff  --git a/clang/lib/Sema/SemaRISCVVectorLookup.cpp 
b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
index 8306b40174f8..50fd841c231b 100644
--- a/clang/lib/Sema/SemaRISCVVectorLookup.cpp
+++ b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
@@ -178,14 +178,23 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() {
   for (auto &Record : RVVIntrinsicRecords) {
 // Create Intrinsics for each type and LMUL.
 BasicType BaseType = BasicType::Unknown;
-ArrayRef ProtoSeq =
+ArrayRef BasicProtoSeq =
 ProtoSeq2ArrayRef(Record.PrototypeIndex, Record.PrototypeLength);
-ArrayRef ProtoMaskSeq = ProtoSeq2ArrayRef(
-Record.MaskedPrototypeIndex, Record.MaskedPrototypeLength);
 ArrayRef SuffixProto =
 ProtoSeq2ArrayRef(Record.SuffixIndex, Record.SuffixLength);
 ArrayRef OverloadedSuffixProto = ProtoSeq2ArrayRef(
 Record.OverloadedSuffixIndex, Record.OverloadedSuffixSize);
+
+llvm::SmallVector ProtoSeq =
+RVVIntrinsic::computeBuiltinTypes(BasicProtoSeq, /*IsMasked=*/false,
+  /*HasMaskedOffOperand=*/false,
+  Record.HasVL, Record.NF);
+
+llvm::SmallVector ProtoMaskSeq =
+RVVIntrinsic::computeBuiltinTypes(BasicProtoSeq, /*IsMasked=*/true,
+  Record.HasMaskedOffOperand,
+  Record.HasVL, Record.NF);
+
 for (unsigned int TypeRangeMaskShift = 0;
  TypeRangeMaskShift <= static_cast(BasicType::MaxOffset);
  ++TypeRangeMaskShift) {
@@ -235,7 +244,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() {
 // Create non-masked intrinsic.
 InitRVVIntrinsic(Record, SuffixStr, OverloadedSuffixStr, false, 
*Types);
 
-if (Record.MaskedPrototypeLength != 0) {
+if (Record.HasMasked) {
   // Create masked intrinsic.
   Optional MaskTypes = RVVType::computeTypes(
   BaseType, Log2LMUL, Record.NF, ProtoMaskSeq);

diff  --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp 
b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
index be2cb380aeb5..513e6376f5ae 100644
--- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -981,17 +981,18 @@ raw_ostream &operator<<(raw_ostream &OS, const 
RVVIntrinsicRecord &Record) {
   else
 OS << "\"" << Record.OverloadedName << "\",";
   OS << Record.PrototypeIndex << ",";
-  OS << Record.MaskedPrototypeIndex << ",";
   OS << Record.SuffixIndex << ",";
   OS << Record.OverloadedSuffixIndex << ",";
   OS << (int)Record.PrototypeLength << ",";
-  OS << (int)Record.MaskedPrototypeLength << ",";
   OS << (int)Record.SuffixLength << ",";
   OS << (int)Record.OverloadedSuffixSize << ",";
   OS << (int)Record.RequiredExtensions << ",";
   OS << (int)Record.TypeRangeMask << ",";
   OS << (int)Record.Log2LMULMask << ",";
   OS << (int)Record.NF << ",";
+  OS << (int)Record.HasMasked << ",";
+  OS << (int)Record.HasVL << ",";
+  OS << (int

[PATCH] D126741: [RISCV][Clang] Refactor RISCVVEmitter. (NFC)

2022-07-26 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 rG93f8657c743b: [RISCV][Clang] Refactor RISCVVEmitter. (NFC) 
(authored by khchen).

Changed prior to commit:
  https://reviews.llvm.org/D126741?vs=433257&id=447634#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126741

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  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
@@ -50,9 +50,6 @@
   // Prototype for this intrinsic.
   SmallVector Prototype;
 
-  // Prototype for masked intrinsic.
-  SmallVector MaskedPrototype;
-
   // Suffix of intrinsic name.
   SmallVector Suffix;
 
@@ -61,6 +58,10 @@
 
   // Number of field, large than 1 if it's segment load/store.
   unsigned NF;
+
+  bool HasMasked :1;
+  bool HasVL :1;
+  bool HasMaskedOffOperand :1;
 };
 
 // Compressed function signature table.
@@ -241,7 +242,6 @@
 
   llvm::for_each(SemaRecords, [&](const SemaRecord &SR) {
 InsertToSignatureSet(SR.Prototype);
-InsertToSignatureSet(SR.MaskedPrototype);
 InsertToSignatureSet(SR.Suffix);
 InsertToSignatureSet(SR.OverloadedSuffix);
   });
@@ -583,12 +583,10 @@
 }
 
 SR.NF = NF;
-
-SR.Prototype = std::move(Prototype);
-
-if (HasMasked)
-  SR.MaskedPrototype = std::move(MaskedPrototype);
-
+SR.HasMasked = HasMasked;
+SR.HasVL = HasVL;
+SR.HasMaskedOffOperand = HasMaskedOffOperand;
+SR.Prototype = std::move(BasicPrototype);
 SR.Suffix = parsePrototypes(SuffixProto);
 SR.OverloadedSuffix = parsePrototypes(OverloadedSuffixProto);
 
@@ -616,22 +614,21 @@
 R.Name = SR.Name.c_str();
 R.OverloadedName = SR.OverloadedName.c_str();
 R.PrototypeIndex = SST.getIndex(SR.Prototype);
-R.MaskedPrototypeIndex = SST.getIndex(SR.MaskedPrototype);
 R.SuffixIndex = SST.getIndex(SR.Suffix);
 R.OverloadedSuffixIndex = SST.getIndex(SR.OverloadedSuffix);
 R.PrototypeLength = SR.Prototype.size();
-R.MaskedPrototypeLength = SR.MaskedPrototype.size();
 R.SuffixLength = SR.Suffix.size();
 R.OverloadedSuffixSize = SR.OverloadedSuffix.size();
 R.RequiredExtensions = SR.RequiredExtensions;
 R.TypeRangeMask = SR.TypeRangeMask;
 R.Log2LMULMask = SR.Log2LMULMask;
 R.NF = SR.NF;
+R.HasMasked = SR.HasMasked;
+R.HasVL = SR.HasVL;
+R.HasMaskedOffOperand = SR.HasMaskedOffOperand;
 
 assert(R.PrototypeIndex !=
static_cast(SemaSignatureTable::INVALID_INDEX));
-assert(R.MaskedPrototypeIndex !=
-   static_cast(SemaSignatureTable::INVALID_INDEX));
 assert(R.SuffixIndex !=
static_cast(SemaSignatureTable::INVALID_INDEX));
 assert(R.OverloadedSuffixIndex !=
Index: clang/lib/Support/RISCVVIntrinsicUtils.cpp
===
--- clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -981,17 +981,18 @@
   else
 OS << "\"" << Record.OverloadedName << "\",";
   OS << Record.PrototypeIndex << ",";
-  OS << Record.MaskedPrototypeIndex << ",";
   OS << Record.SuffixIndex << ",";
   OS << Record.OverloadedSuffixIndex << ",";
   OS << (int)Record.PrototypeLength << ",";
-  OS << (int)Record.MaskedPrototypeLength << ",";
   OS << (int)Record.SuffixLength << ",";
   OS << (int)Record.OverloadedSuffixSize << ",";
   OS << (int)Record.RequiredExtensions << ",";
   OS << (int)Record.TypeRangeMask << ",";
   OS << (int)Record.Log2LMULMask << ",";
   OS << (int)Record.NF << ",";
+  OS << (int)Record.HasMasked << ",";
+  OS << (int)Record.HasVL << ",";
+  OS << (int)Record.HasMaskedOffOperand << ",";
   OS << "},\n";
   return OS;
 }
Index: clang/lib/Sema/SemaRISCVVectorLookup.cpp
===
--- clang/lib/Sema/SemaRISCVVectorLookup.cpp
+++ clang/lib/Sema/SemaRISCVVectorLookup.cpp
@@ -178,14 +178,23 @@
   for (auto &Record : RVVIntrinsicRecords) {
 // Create Intrinsics for each type and LMUL.
 BasicType BaseType = BasicType::Unknown;
-ArrayRef ProtoSeq =
+ArrayRef BasicProtoSeq =
 ProtoSeq2ArrayRef(Record.PrototypeIndex, Record.PrototypeLength);
-ArrayRef ProtoMaskSeq = ProtoSeq2ArrayRef(
-Record.MaskedPrototypeIndex, Record.MaskedPrototypeLength);
 ArrayRef SuffixProto =
 ProtoSeq2ArrayRef(Record.SuffixIndex, Record.SuffixLength);
 ArrayRef OverloadedSuffixProto = ProtoSeq2ArrayRef(
 Record.OverloadedSuffixIndex, Record.OverloadedSuffixSize);
+
+llvm::SmallVector ProtoSeq =
+RVVIntrinsic::computeBuiltinTypes(BasicProtoS

[PATCH] D124762: [WinEHPrepare] Avoid truncation of EH funclets with GNUstep ObjC runtime

2022-07-26 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz abandoned this revision.
sgraenitz added a comment.

Close in favor of the D128190 , which covers 
both cases at once: emit (was D124762 ) and 
inline (was D127962 )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124762

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


[PATCH] D130470: [clang][analyzer] Add more wide-character functions to CStringChecker

2022-07-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Other than nits, I think it looks great.




Comment at: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1359
+void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE,
+bool IsWide) const {
   // int memcmp(const void *s1, const void *s2, size_t n);

Personally, I dislike bools for this purpose.
Did you consider something like `enum CharacterFlavor {Regular, Wide}`? It 
would be more readable in the CallDescription table.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130470

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


[clang] 15ddc09 - [C++20] [Modules] Handle linkage properly for specializations when overloading

2022-07-26 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-07-26T18:30:48+08:00
New Revision: 15ddc09ef9b05ffd5398165049b5202264fa203a

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

LOG: [C++20] [Modules] Handle linkage properly for specializations when 
overloading

Currently, the semantics of linkage in clang is slightly
different from the semantics in C++ spec. In C++ spec, only names
have linkage. So that all entities of the same should share
one linkage. But in clang, different entities of the same could
have different linkage.

It would break a use case where the template have external linkage and
its specialization have internal linkage due to its type argument is
internal linkage. The root cause is that the semantics of internal
linkage in clang is a mixed form of internal linkage and TU-local in
C++ spec. It is hard to solve the root problem and I tried to add a
workaround inplace.

Added: 
clang/test/Modules/instantiation-argdep-lookup.cppm

Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 65dae00345f6d..7207ce7c4d21e 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -6403,11 +6403,21 @@ void Sema::AddOverloadCandidate(
   // Functions with internal linkage are only viable in the same module unit.
   if (auto *MF = Function->getOwningModule()) {
 if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
-Function->getFormalLinkage() <= Linkage::InternalLinkage &&
 !isModuleUnitOfCurrentTU(MF)) {
-  Candidate.Viable = false;
-  Candidate.FailureKind = ovl_fail_module_mismatched;
-  return;
+  /// FIXME: Currently, the semantics of linkage in clang is slightly
+  /// 
diff erent from the semantics in C++ spec. In C++ spec, only names
+  /// have linkage. So that all entities of the same should share one
+  /// linkage. But in clang, 
diff erent entities of the same could have
+  /// 
diff erent linkage.
+  NamedDecl *ND = Function;
+  if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
+ND = SpecInfo->getTemplate();
+  
+  if (ND->getFormalLinkage() <= Linkage::InternalLinkage) {
+Candidate.Viable = false;
+Candidate.FailureKind = ovl_fail_module_mismatched;
+return;
+  }
 }
   }
 

diff  --git a/clang/test/Modules/instantiation-argdep-lookup.cppm 
b/clang/test/Modules/instantiation-argdep-lookup.cppm
new file mode 100644
index 0..fc9009a5bc13d
--- /dev/null
+++ b/clang/test/Modules/instantiation-argdep-lookup.cppm
@@ -0,0 +1,42 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/A.cppm -I%t -emit-module-interface -o %t/A.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %t/Use.cpp -verify 
-fsyntax-only
+//
+//--- foo.h
+
+namespace ns {
+struct A {};
+
+template
+constexpr bool __call_is_nt(A)
+{
+return true;
+}
+ns::A make();
+
+template 
+bool foo(T t) {
+auto func = [](){};
+return __call_is_nt(t);
+}
+}
+
+//--- A.cppm
+module;
+#include "foo.h"
+export module A;
+export namespace ns {
+using ns::foo;
+using ns::make;
+}
+
+//--- Use.cpp
+// expected-no-diagnostics
+import A;
+void test() {
+auto a = ns::make();
+ns::foo(a);
+}



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


[clang] a80418e - [analyzer] Improve loads from reinterpret-cast fields

2022-07-26 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-07-26T12:31:21+02:00
New Revision: a80418eec001d91f9573456b31704a350e421560

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

LOG: [analyzer] Improve loads from reinterpret-cast fields

Consider this example:

```lang=C++
struct header {
  unsigned a : 1;
  unsigned b : 1;
};
struct parse_t {
  unsigned bits0 : 1;
  unsigned bits2 : 2; // <-- header
  unsigned bits4 : 4;
};
int parse(parse_t *p) {
  unsigned copy = p->bits2;
  clang_analyzer_dump(copy);
  // expected-warning@-1 {{reg_$1}.bits2>}}

  header *bits = (header *)©
  clang_analyzer_dump(bits->b); // <--- Was UndefinedVal previously.
  // expected-warning@-1 {{derived_$2{reg_$1}.bits2>,Element{copy,0 
S64b,struct Bug_55934::header}.b}}}
  return bits->b; // no-warning: it's not UndefinedVal
}
```

`bits->b` should have the same content as the second bit of `p->bits2`
(assuming that the bitfields are in spelling order).

---

The `Store` has the correct bindings. The problem is with the load of `bits->b`.
It will eventually reach `RegionStoreManager::getBindingForField()` with
`Element{copy,0 S64b,struct header}.b`, which is a `FieldRegion`.
It did not find any direct bindings, so the 
`getBindingForFieldOrElementCommon()`
gets called. That won't find any bindings, but it sees that the variable
is on the //stack//, thus it must be an uninitialized local variable;
thus it returns `UndefinedVal`.

Instead of doing this, it should have created a //derived symbol//
representing the slice of the region corresponding to the member.
So, if the value of `copy` is `reg1`, then the value of `bits->b` should
be `derived{reg1, elem{copy,0, header}.b}`.

Actually, the `getBindingForElement()` already does exactly this for
reinterpret-casts, so I decided to hoist that and reuse the logic.

Fixes #55934

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/test/Analysis/ptr-arith.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 5e946483a93d..d8ece9f39a25 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1888,6 +1888,30 @@ SVal RegionStoreManager::getSValFromStringLiteral(const 
StringLiteral *SL,
   return svalBuilder.makeIntVal(Code, ElemT);
 }
 
+static Optional getDerivedSymbolForBinding(
+RegionBindingsConstRef B, const TypedValueRegion *BaseRegion,
+const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) {
+  assert(BaseRegion);
+  QualType BaseTy = BaseRegion->getValueType();
+  QualType Ty = SubReg->getValueType();
+  if (BaseTy->isScalarType() && Ty->isScalarType()) {
+if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) {
+  if (const Optional &ParentValue = B.getDirectBinding(BaseRegion)) {
+if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol())
+  return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg);
+
+if (ParentValue->isUndef())
+  return UndefinedVal();
+
+// Other cases: give up.  We are indexing into a larger object
+// that has some value, but we don't know how to handle that yet.
+return UnknownVal();
+  }
+}
+  }
+  return None;
+}
+
 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
   const ElementRegion* R) {
   // Check if the region has a binding.
@@ -1932,27 +1956,10 @@ SVal 
RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
   if (!O.getRegion())
 return UnknownVal();
 
-  if (const TypedValueRegion *baseR =
-dyn_cast_or_null(O.getRegion())) {
-QualType baseT = baseR->getValueType();
-if (baseT->isScalarType()) {
-  QualType elemT = R->getElementType();
-  if (elemT->isScalarType()) {
-if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
-  if (const Optional &V = B.getDirectBinding(superR)) {
-if (SymbolRef parentSym = V->getAsSymbol())
-  return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
-
-if (V->isUnknownOrUndef())
-  return *V;
-// Other cases: give up.  We are indexing into a larger object
-// that has some value, but we don't know how to handle that yet.
-return UnknownVal();
-  }
-}
-  }
-}
-  }
+  if (const TypedValueRegion *baseR = 
dyn_cast(O.getRegion()))
+if (auto V = getDerivedSymbolForBinding(B, baseR, R, Ctx, svalBuilder))
+  return *V;
+
   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
 }
 

[PATCH] D128535: [analyzer] Improve loads from reinterpret-cast fields

2022-07-26 Thread Balázs Benics via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
steakhal marked 2 inline comments as done.
Closed by commit rGa80418eec001: [analyzer] Improve loads from reinterpret-cast 
fields (authored by steakhal).

Changed prior to commit:
  https://reviews.llvm.org/D128535?vs=439758&id=447636#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128535

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/ptr-arith.cpp

Index: clang/test/Analysis/ptr-arith.cpp
===
--- clang/test/Analysis/ptr-arith.cpp
+++ clang/test/Analysis/ptr-arith.cpp
@@ -1,4 +1,7 @@
 // RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm -verify %s
+
+template  void clang_analyzer_dump(T);
+
 struct X {
   int *p;
   int zero;
@@ -117,3 +120,24 @@
   auto n = p - reinterpret_cast((__UINTPTR_TYPE__)1);
   return n == m;
 }
+
+namespace Bug_55934 {
+struct header {
+  unsigned a : 1;
+  unsigned b : 1;
+};
+struct parse_t {
+  unsigned bits0 : 1;
+  unsigned bits2 : 2; // <-- header
+  unsigned bits4 : 4;
+};
+int parse(parse_t *p) {
+  unsigned copy = p->bits2;
+  clang_analyzer_dump(copy);
+  // expected-warning@-1 {{reg_$1}.bits2>}}
+  header *bits = (header *)©
+  clang_analyzer_dump(bits->b);
+  // expected-warning@-1 {{derived_$2{reg_$1}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
+  return bits->b; // no-warning
+}
+} // namespace Bug_55934
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1888,6 +1888,30 @@
   return svalBuilder.makeIntVal(Code, ElemT);
 }
 
+static Optional getDerivedSymbolForBinding(
+RegionBindingsConstRef B, const TypedValueRegion *BaseRegion,
+const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) {
+  assert(BaseRegion);
+  QualType BaseTy = BaseRegion->getValueType();
+  QualType Ty = SubReg->getValueType();
+  if (BaseTy->isScalarType() && Ty->isScalarType()) {
+if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) {
+  if (const Optional &ParentValue = B.getDirectBinding(BaseRegion)) {
+if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol())
+  return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg);
+
+if (ParentValue->isUndef())
+  return UndefinedVal();
+
+// Other cases: give up.  We are indexing into a larger object
+// that has some value, but we don't know how to handle that yet.
+return UnknownVal();
+  }
+}
+  }
+  return None;
+}
+
 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
   const ElementRegion* R) {
   // Check if the region has a binding.
@@ -1932,27 +1956,10 @@
   if (!O.getRegion())
 return UnknownVal();
 
-  if (const TypedValueRegion *baseR =
-dyn_cast_or_null(O.getRegion())) {
-QualType baseT = baseR->getValueType();
-if (baseT->isScalarType()) {
-  QualType elemT = R->getElementType();
-  if (elemT->isScalarType()) {
-if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
-  if (const Optional &V = B.getDirectBinding(superR)) {
-if (SymbolRef parentSym = V->getAsSymbol())
-  return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
-
-if (V->isUnknownOrUndef())
-  return *V;
-// Other cases: give up.  We are indexing into a larger object
-// that has some value, but we don't know how to handle that yet.
-return UnknownVal();
-  }
-}
-  }
-}
-  }
+  if (const TypedValueRegion *baseR = dyn_cast(O.getRegion()))
+if (auto V = getDerivedSymbolForBinding(B, baseR, R, Ctx, svalBuilder))
+  return *V;
+
   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
 }
 
@@ -1988,6 +1995,26 @@
 }
   }
 
+  // Handle the case where we are accessing into a larger scalar object.
+  // For example, this handles:
+  //   struct header {
+  // unsigned a : 1;
+  // unsigned b : 1;
+  //   };
+  //   struct parse_t {
+  // unsigned bits0 : 1;
+  // unsigned bits2 : 2; // <-- header
+  // unsigned bits4 : 4;
+  //   };
+  //   int parse(parse_t *p) {
+  // unsigned copy = p->bits2;
+  // header *bits = (header *)©
+  // return bits->b;  <-- here
+  //   }
+  if (const auto *Base = dyn_cast(R->getBaseRegion()))
+if (auto V = getDerivedSymbolForBinding(B, Base, R, Ctx, svalBuilder))
+  return *V;
+
   return getBindingForFieldOrElementCommon(B, R, Ty);
 }
 
_

[PATCH] D130551: [pseudo] Allow opaque nodes to represent terminals

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D130551#3679021 , @hokein wrote:

> The change looks good, are you planning to use it in the cxx.bnf?

I want to land a recovery rule that completes scopes (e.g. namespaces) rather 
than discarding them.

But i have to fix several deficiencies, at least this one, D130550 
, D130523 . 
and at some point we have to allow rules to have more than one recovery point.

I like having the motivating case in the patch itself but in this case there's 
just too much of this stuff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130551

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


[PATCH] D129174: [C++20][Modules] Update ADL to handle basic.lookup.argdep p4 [P1815R2 part 1]

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

FYI

When I implements/tests the modularized STL for libstdc++ 
(https://github.com/ChuanqiXu9/stdmodules), I find the patch blocks it. Due to 
the time is limited (I really wish we could have something workable in 
clang15), I made a pre-review commit in: 
https://github.com/llvm/llvm-project/commit/15ddc09ef9b05ffd5398165049b5202264fa203a

The problem shows in the tests:

  struct A {};
  
   template
   constexpr bool __call_is_nt(A)
   {
   return true;
   }
   ns::A make();
  
   template 
   bool foo(T t) {
   auto func = [](){};
   return __call_is_nt(t);
   }

The linkage of `__call_is_nt` in clang is internal linkage. So 
it is refused by this patch. This is not the fault of the patch. According to 
[basic.link], only names have linkage. So __call_is_nt should 
have same linkage with  its template, which should be external.

The root cause for the problem is that the semantics of internal linkage in 
clang is a mixed form of internal linkage and TU-Local in C++ Specifications. 
So here is the slight difference. It is hard to fix the root problem so I 
choose to give a workaround here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129174

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


[PATCH] D129138: [clang] [docs] Update the changes of C++20 Modules in clang15

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

In D129138#3674619 , @iains wrote:

> In D129138#3670708 , @ChuanqiXu 
> wrote:
>
>> @iains I'm going to land this in next Monday if all the dependent patch 
>> landed. Do you feel good with this?
>
> I am not sure if we will get p1815 part 1 landed (effectively today) - and, 
> of course, we have also some other patches in-flight that will improve the 
> C++20 implementation, but extremely unlikely to be landed today.

Now it is landed, I think we could land the ReleaseNotes too.


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

https://reviews.llvm.org/D129138

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


[PATCH] D129138: [clang] [docs] Update the changes of C++20 Modules in clang15

2022-07-26 Thread Chuanqi Xu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc73adbad6a99: [clang] [docs] Update the changes of C++20 
Modules in clang15 (authored by ChuanqiXu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129138

Files:
  clang/docs/ReleaseNotes.rst
  clang/www/cxx_status.html


Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1164,7 +1164,7 @@
 
   Modules
   https://wg21.link/p1103r3";>P1103R3
-  Partial
+  Clang 15
 

 https://wg21.link/p1766r1";>P1766R1 (DR)
@@ -1180,17 +1180,19 @@
   

 https://wg21.link/p1874r1";>P1874R1
-Partial
+Clang 15
   

 https://wg21.link/p1979r0";>P1979R0
-No
+No
   

 https://wg21.link/p1779r3";>P1779R3
+Clang 15
   
   
 https://wg21.link/p1857r3";>P1857R3
+No
   
   
 https://wg21.link/p2115r0";>P2115R0
@@ -1198,7 +1200,7 @@
   
   
 https://wg21.link/p1815r2";>P1815R2
-No
+Partial
   
 
   Coroutines
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -513,6 +513,14 @@
   that can be used for such compatibility. The demangler now demangles
   symbols with named module attachment.
 
+- Enhanced the support for C++20 Modules, including: Partitions,
+  Reachability, Header Unit and ``extern "C++"`` semantics.
+
+- Implemented `P1103R3: Merging Modules `_.
+- Implemented `P1779R3: ABI isolation for member functions 
`_.
+- Implemented `P1874R1: Dynamic Initialization Order of Non-Local Variables in 
Modules `_.
+- Partially implemented `P1815R2: Translation-unit-local entities 
`_.
+
 - As per "Conditionally Trivial Special Member Functions" (P0848), it is
   now possible to overload destructors using concepts. Note that the rest
   of the paper about other special member functions is not yet implemented.


Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1164,7 +1164,7 @@
 
   Modules
   https://wg21.link/p1103r3";>P1103R3
-  Partial
+  Clang 15
 

 https://wg21.link/p1766r1";>P1766R1 (DR)
@@ -1180,17 +1180,19 @@
   

 https://wg21.link/p1874r1";>P1874R1
-Partial
+Clang 15
   

 https://wg21.link/p1979r0";>P1979R0
-No
+No
   

 https://wg21.link/p1779r3";>P1779R3
+Clang 15
   
   
 https://wg21.link/p1857r3";>P1857R3
+No
   
   
 https://wg21.link/p2115r0";>P2115R0
@@ -1198,7 +1200,7 @@
   
   
 https://wg21.link/p1815r2";>P1815R2
-No
+Partial
   
 
   Coroutines
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -513,6 +513,14 @@
   that can be used for such compatibility. The demangler now demangles
   symbols with named module attachment.
 
+- Enhanced the support for C++20 Modules, including: Partitions,
+  Reachability, Header Unit and ``extern "C++"`` semantics.
+
+- Implemented `P1103R3: Merging Modules `_.
+- Implemented `P1779R3: ABI isolation for member functions `_.
+- Implemented `P1874R1: Dynamic Initialization Order of Non-Local Variables in Modules `_.
+- Partially implemented `P1815R2: Translation-unit-local entities `_.
+
 - As per "Conditionally Trivial Special Member Functions" (P0848), it is
   now possible to overload destructors using concepts. Note that the rest
   of the paper about other special member functions is not yet implemented.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c73adba - [clang] [docs] Update the changes of C++20 Modules in clang15

2022-07-26 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-07-26T18:47:53+08:00
New Revision: c73adbad6a9964e0700865b7c786cc6885898c68

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

LOG: [clang] [docs] Update the changes of C++20 Modules in clang15

Since clang15 is going to be branched in July 26, and C++ modules still
lack an update on ReleaseNotes. Although it is not complete yet, I think
it would be better to add one since we've done many works for C++20
Modules in clang15.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5331dd2c38468..8b23da25527e6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -513,6 +513,14 @@ C++20 Feature Support
   that can be used for such compatibility. The demangler now demangles
   symbols with named module attachment.
 
+- Enhanced the support for C++20 Modules, including: Partitions,
+  Reachability, Header Unit and ``extern "C++"`` semantics.
+
+- Implemented `P1103R3: Merging Modules `_.
+- Implemented `P1779R3: ABI isolation for member functions 
`_.
+- Implemented `P1874R1: Dynamic Initialization Order of Non-Local Variables in 
Modules `_.
+- Partially implemented `P1815R2: Translation-unit-local entities 
`_.
+
 - As per "Conditionally Trivial Special Member Functions" (P0848), it is
   now possible to overload destructors using concepts. Note that the rest
   of the paper about other special member functions is not yet implemented.

diff  --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html
index 0fd33524596ad..41b788e82d73d 100755
--- a/clang/www/cxx_status.html
+++ b/clang/www/cxx_status.html
@@ -1164,7 +1164,7 @@ C++20 implementation status
 
   Modules
   https://wg21.link/p1103r3";>P1103R3
-  Partial
+  Clang 15
 

 https://wg21.link/p1766r1";>P1766R1 (DR)
@@ -1180,17 +1180,19 @@ C++20 implementation status
   

 https://wg21.link/p1874r1";>P1874R1
-Partial
+Clang 15
   

 https://wg21.link/p1979r0";>P1979R0
-No
+No
   

 https://wg21.link/p1779r3";>P1779R3
+Clang 15
   
   
 https://wg21.link/p1857r3";>P1857R3
+No
   
   
 https://wg21.link/p2115r0";>P2115R0
@@ -1198,7 +1200,7 @@ C++20 implementation status
   
   
 https://wg21.link/p1815r2";>P1815R2
-No
+Partial
   
 
   Coroutines



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


[PATCH] D130476: [NFC] Fix some C++20 warnings

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

LGTM, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130476

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


[PATCH] D130081: Add foldings for multi-line comment.

2022-07-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Protocol.h:1782
   unsigned endCharacter;
-  std::string kind;
+  FoldingRangeKind kind;
 };

hokein wrote:
> sorry for not being clear on my previous comment, I think the current `string 
> kind;` is good, and it aligns with the LSP one.
> 
> what I suggest was adding string literals to FoldingRange, something like
> 
> 
> ```
> struct FoldingRange {
>   const static llvm::StringLiteral REGION_KIND;
>   const static llvm::StringLiteral COMMENT_KIND;
>   const static llvm::StringLiteral IMPORT_KIND;
>   
>   // other fields keep as-is.
>   ...
> }
> ```
> we're diverging from the LSP structure. 
+1, we already have the same pattern for code action kinds, i was also 
referring to this in our offline discussion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130081

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


[PATCH] D130476: [NFC] Fix some C++20 warnings

2022-07-26 Thread Evgeny Mandrikov via Phabricator via cfe-commits
Godin added a comment.

@aaron.ballman  thanks for the review! could you please commit this on my 
behalf since I do not have commit rights?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130476

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


[PATCH] D130511: [pseudo][wip] Eliminate simple-type-specifier ambiguities.

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

TL;DR: I suspect this is valid but guarding `nested-name-specifier := :: 
[guard=PrevNotIdentifier]` may be equivalent and clearer.

In D130511#3678938 , @hokein wrote:

> In D130511#3677423 , @sammccall 
> wrote:
>
>> My main concern here is that this might reject valid code (and if it 
>> doesn't, it's not obvious why).
>> It does look like C++ forbids the cases I can come up with (e.g. trying to 
>> provide a definition for `::Foo` is rejected by clang with "definition or 
>> redeclaration of Foo cannot name the global scope).
>> But I'd be way more comfortable if we could connect the specific guard rules 
>> here with spec language.
>
> The qualified declarator is tricky (it was forbidden until 
> https://cplusplus.github.io/CWG/issues/482.html).
>
> The closest thing I can find in the standard is basic.lookup.qual.general 
> :
>
>> If a name, template-id, or decltype-specifier is followed by a ​::​, it 
>> shall designate a namespace, class, enumeration, or dependent type, and the 
>> ​::​ is never interpreted as a complete nested-name-specifier.

OK, so just spelling this out so I don't get lost...

A `name` is an identifier or operator name.
From the grammar `nested-name-specifier` can have components preceding `::`:

- nothing (global scope)
- type-name, namespace-name: these are identifiers = names
- decltype-specifier,
- (simple)-template-id

So the rule is saying that if the `::` can bind to the thing on its left, it 
must (*all* the non-null components are either names, template IDs, or 
decltype-specifiers).

I think this is probably what you've implemented here, though it's not totally 
obvious to me.

It seems most natural/more obviously-correct to express this as a guard on 
`namespace-specifier := ::`, as that's what the rule directly restricts. It's 
not simple to decide in general (in `c < d > :: a`, `c` can be a template-id 
or not), but we can rule out the cases where the preceding token is an 
identifier (which is a limitation of your patch, right?).

Does `nested-name-specifier := :: [guard=PrevTokenNotIdentifier]` work for your 
testcases?
I think this is easier to tie to the [basic.language.qual.general] language you 
quoted.
(If you *don't* find this clearer, please do push back)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130511

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


[PATCH] D130510: Missing tautological compare warnings due to unary operators

2022-07-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for working on this! I have some suggestions, but you'll also need to 
add a release note at some point.




Comment at: clang/lib/Analysis/CFG.cpp:970-980
+if (LHSExpr->EvaluateAsInt(IntExprResult, *Context)) {
+   // Evaluating value.
+  BoolExpr = RHSExpr;
+}
+else if (RHSExpr->EvaluateAsInt(IntExprResult, *Context)) {
   BoolExpr = LHSExpr;
 }

Coding style fix.



Comment at: clang/lib/Analysis/CFG.cpp:985
+  BitOp->getOpcode() == BO_Or  || 
+  BitOp->getOpcode() == BO_Xor)) {
   const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();

Be sure to add test coverage for this change.



Comment at: clang/lib/Analysis/CFG.cpp:986-988
   const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
   const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
+  





Comment at: clang/lib/Analysis/CFG.cpp:989-996
+  // If integer literal in expression identified then will save value.
+  Expr::EvalResult IntExprResult2; 
 
-  const IntegerLiteral *IntLiteral2 = dyn_cast(LHSExpr2);
-
-  if (!IntLiteral2)
-IntLiteral2 = dyn_cast(RHSExpr2);
-
-  if (!IntLiteral2)
+  
+  if (LHSExpr2->EvaluateAsInt(IntExprResult2, *Context));
+  else if ( RHSExpr2->EvaluateAsInt(IntExprResult2, *Context));
+  else

(Be sure to re-run clang format over the patch, in case I've messed up 80-col 
limits with my suggestions.)



Comment at: clang/lib/Analysis/CFG.cpp:992
 
-  const IntegerLiteral *IntLiteral2 = dyn_cast(LHSExpr2);
-
-  if (!IntLiteral2)
-IntLiteral2 = dyn_cast(RHSExpr2);
-
-  if (!IntLiteral2)
+  
+  if (LHSExpr2->EvaluateAsInt(IntExprResult2, *Context));

It looks like you've added a spurious tab here.



Comment at: clang/lib/Analysis/CFG.cpp:998
 
-  llvm::APInt L1 = IntLiteral->getValue();
-  llvm::APInt L2 = IntLiteral2->getValue();
+  // Getting the values as integer from the evaluation expression to use 
for comparision.
+  llvm::APInt L1 = IntExprResult.Val.getInt(); 

Take this suggestion or leave it, as you want. I don't think the comment added 
much value because it's describing what the code does (which is reasonably 
obvious from reading the code given that the code is pretty simple) rather than 
describing why the code is necessary (which doesn't seem to be required in this 
case).



Comment at: clang/lib/Analysis/CFG.cpp:1008
  B->getOpcode() != BO_EQ);
 TryResult(B->getOpcode() != BO_EQ);
   }

This looks like an existing bug and suggests we're missing test coverage -- we 
create a `TryResult` object but do nothing with it; I suspect we wanted to 
return this result.

Can you try to add test coverage that hits this code path to verify the current 
behavior is wrong, then change it to return the result to make sure the 
behavior is corrected?



Comment at: clang/lib/Analysis/CFG.cpp:1011-1014
+  llvm::APInt IntValue = IntExprResult.Val.getInt(); // Getting the value.
   if ((IntValue == 1) || (IntValue == 0)) {
 return TryResult();
   }





Comment at: clang/test/SemaCXX/warn-unreachable.cpp:400-401
   // TODO: Extend warning to the following code:
   if (x < -1)
 calledFun();
+  if (x == -1)   // expected-note {{silence}}

Why aren't we catching this one?



Comment at: clang/test/SemaCXX/warn-unreachable.cpp:409-410
+calledFun(); // expected-warning {{will never be executed}}
   if (-1 > x)
 calledFun();
   else

Or this one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

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


[clang-tools-extra] 07b7ff9 - [pseudo] Allow opaque nodes to represent terminals

2022-07-26 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-07-26T13:56:26+02:00
New Revision: 07b7ff983837dbc20749682673d09992f71b0c59

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

LOG: [pseudo] Allow opaque nodes to represent terminals

This allows incomplete code such as `namespace foo {` to be modeled as a
normal sequence with the missing } represented by an empty opaque node.

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

Added: 


Modified: 
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index ab230accdf8f8..10a94860ffc98 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -182,9 +182,13 @@ void glrRecover(llvm::ArrayRef OldHeads,
   for (const PlaceholderRecovery *Option : BestOptions) {
 const ForestNode &Placeholder =
 Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
-const GSS::Node *NewHead = Params.GSStack.addNode(
-*Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
-&Placeholder, {Option->RecoveryNode});
+LRTable::StateID OldState = Option->RecoveryNode->State;
+LRTable::StateID NewState =
+isToken(Option->Symbol)
+? *Lang.Table.getShiftState(OldState, Option->Symbol)
+: *Lang.Table.getGoToState(OldState, Option->Symbol);
+const GSS::Node *NewHead =
+Params.GSStack.addNode(NewState, &Placeholder, {Option->RecoveryNode});
 NewHeads.push_back(NewHead);
   }
   TokenIndex = RecoveryRange->End;

diff  --git a/clang-tools-extra/pseudo/unittests/GLRTest.cpp 
b/clang-tools-extra/pseudo/unittests/GLRTest.cpp
index 5f87efec67044..7abf9295d1570 100644
--- a/clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ b/clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -604,6 +604,28 @@ TEST_F(GLRTest, RecoveryEndToEnd) {
 "[  5, end) └─} := tok[5]\n");
 }
 
+TEST_F(GLRTest, RecoverTerminal) {
+  build(R"bnf(
+_ := stmt
+
+stmt := IDENTIFIER ; [recover=Skip]
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) stmt := IDENTIFIER ; [recover=Skip]\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─; := \n");
+}
+
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test



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


[PATCH] D130551: [pseudo] Allow opaque nodes to represent terminals

2022-07-26 Thread Sam McCall 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 rG07b7ff983837: [pseudo] Allow opaque nodes to represent 
terminals (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130551

Files:
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -604,6 +604,28 @@
 "[  5, end) └─} := tok[5]\n");
 }
 
+TEST_F(GLRTest, RecoverTerminal) {
+  build(R"bnf(
+_ := stmt
+
+stmt := IDENTIFIER ; [recover=Skip]
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) stmt := IDENTIFIER ; [recover=Skip]\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─; := \n");
+}
+
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -182,9 +182,13 @@
   for (const PlaceholderRecovery *Option : BestOptions) {
 const ForestNode &Placeholder =
 Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
-const GSS::Node *NewHead = Params.GSStack.addNode(
-*Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
-&Placeholder, {Option->RecoveryNode});
+LRTable::StateID OldState = Option->RecoveryNode->State;
+LRTable::StateID NewState =
+isToken(Option->Symbol)
+? *Lang.Table.getShiftState(OldState, Option->Symbol)
+: *Lang.Table.getGoToState(OldState, Option->Symbol);
+const GSS::Node *NewHead =
+Params.GSStack.addNode(NewState, &Placeholder, {Option->RecoveryNode});
 NewHeads.push_back(NewHead);
   }
   TokenIndex = RecoveryRange->End;


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -604,6 +604,28 @@
 "[  5, end) └─} := tok[5]\n");
 }
 
+TEST_F(GLRTest, RecoverTerminal) {
+  build(R"bnf(
+_ := stmt
+
+stmt := IDENTIFIER ; [recover=Skip]
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) stmt := IDENTIFIER ; [recover=Skip]\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─; := \n");
+}
+
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -182,9 +182,13 @@
   for (const PlaceholderRecovery *Option : BestOptions) {
 const ForestNode &Placeholder =
 Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
-const GSS::Node *NewHead = Params.GSStack.addNode(
-*Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
-&Placeholder, {Option->RecoveryNode});
+LRTable::StateID OldState = Option->RecoveryNode->State;
+LRTable::StateID NewState =
+isToken(Option->Symbol)
+? *Lang.Table.getShiftState(OldState, Option->Symbol)
+: *Lang.Table.getGoToState(OldState, Option->Symbol);
+const GSS::Node *NewHead =
+Params.GSStack.addNode(NewState, &Placeholder, {Option->RecoveryNode});
 NewHeads.push_back(NewHead);
   }
   TokenIndex = RecoveryRange->End;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130414: [pseudo] Reorganize CXX.h enums

2022-07-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h:54
+namespace rules {
+namespace dummy {
+enum Rule {

usaxena95 wrote:
> sammccall wrote:
> > hokein wrote:
> > > why there is a dummy namespace here?
> > for each NT, we close the previous ns+enum and open new ones.
> > For this to work for the first NT, we have to open an ns+enum.
> > 
> > I can add a comment, but would prefer to do this some other way?
> I would include this block in the clang-format off block to show these are 
> for the generated code.
> ```
> //clang-format off
> namespace dummy { enum Rule {
> ...
> };}
> //clang-format on
> ```
ah, I get it (until I read the preprocessed CXX.h code) -- I found it really 
hard to understand it by literally reading the code here. 

To make it clear,  I think we can probably add two additional RULE_BEGIN, 
RULE_END macros? 

 in `CXXSymbols.inc`, we emit something like

```
RULE_BEGIN(_)
RULE(_, translation_unit, 135)
RULE(_, statement_seq, 136)
RULE(_, declaration_seq, 137))
RULE_END(_)
```

In CXX.h, we write

```
#define RULE_BEGIN(LHS) namespace LHS { enum Rule : RULE ID {
#define RULE_END()  }; }
```




Comment at: clang-tools-extra/pseudo/lib/cxx/CXX.cpp:119
 
-switch ((cxx::Rule)Declarator->rule()) {
-case Rule::noptr_declarator_0declarator_id: // reached the bottom
+switch (Declarator->rule()) {
+case rule::noptr_declarator::declarator_id: // reached the bottom

sammccall wrote:
> hokein wrote:
> > The code of applying the pattern doesn't look much worse to me and it is 
> > easier to verify the exhaustiveness by human as well. We might loose some 
> > performance (I hope not a lot), but I think it is a good tradeoff (not 
> > saying we need do it in this patch).
> > 
> > ```
> > switch (LHSNonterminal(Declarator->rule(), *G)) {
> >case cxx::Symbol::noptr_declarator: {
> >   switch ((rule::noptr_declarator)Declarator->rule())  {
> >  case rule::noptr_declarator::declarator_id:
> >  
> >  case 
> > rule::noptr_declarator::noptr_declarator__parameters_and_qualifiers:
> >  
> >   }
> >...
> >}
> > }
> > ```
> I guess this is a question of taste, but I find that style very hard to read.
> 
> (Note that it's incorrectly indented, and the indentation rules around 
> switch/case are one of the main reasons I find nested switches confusing)
> (Note that it's incorrectly indented, and the indentation rules around 
> switch/case are one of the main reasons I find nested switches confusing)

Ah the indentation is weird (it is not what I originally written..). There are 
ways to make the indentation correct (turn off the clang-format etc).

If nested switch is hard to read, maybe we can wrap one with a macro to improve 
the code readability (happy to explore ideas, I think there is value on this 
pattern).



Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:51
 #define TOK(X) #X,
-#define KEYWORD(X, Y) #X,
+#define KEYWORD(Keyword, Condition) llvm::StringRef(#Keyword).upper(),
 #include "clang/Basic/TokenKinds.def"

sammccall wrote:
> hokein wrote:
> > IMO, this improves the readability, and also aligns with the text in the 
> > cxx.grammar.
> Thanks. I like this change too. We still have `semi` vs `;` (should we use 
> `SEMI`?) but it feels clearer
yeah, that looks good (that means lowercase is always referring to nonterminals)



Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:62
 
 std::string Grammar::mangleRule(RuleID RID) const {
   const auto &R = lookupRule(RID);

sammccall wrote:
> hokein wrote:
> > nit: update the doc comment in .h file.
> Honestly I would rather just move the impl back into gen - this change seems 
> to demonstrate why
ok, feel free to move it.



Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:65
+  std::string MangleName;
+  for (size_t I = 0; I < R.seq().size(); ++I) {
+MangleName += mangleSymbol(R.seq()[I]);

sammccall wrote:
> hokein wrote:
> > ok, now we're dropping the index for all RHS symbols. Just want to know 
> > your thought about this. Personally, I'd like to keep this information 
> > (`noptr_declarator__l_square__constant_expression__r_square` vs 
> > `noptr_declarator0_l_square1_constant_expression2_r_square3`) though it 
> > makes the name a bit uglier.
> > 
> > > Change mangling of keywords to ALL_CAPS (needed to turn keywords that 
> > > appear alone on RHS into valid identifiers)
> > 
> > if we add index number to the name, then this change is not required.
> Short version: I can deal with the numbers at the front (there's a *little* 
> bit of value), but at the back of the symbol name there's no value, just 
> noise. I find the double-underscore version much more readable (than either 
> variant with numbers).
> 
> ---
> 
> 

[clang] ba198e3 - [NFC] Fix some C++20 warnings

2022-07-26 Thread Balazs Benics via cfe-commits

Author: Evgeny Mandrikov
Date: 2022-07-26T14:04:12+02:00
New Revision: ba198e35fd380350ff7bf5b47d8cf5fa9a43d3e6

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

LOG: [NFC] Fix some C++20 warnings

Without this patch when using CMAKE_CXX_STANDARD=20 Microsoft compiler produces 
following warnings

clang\include\clang/Basic/DiagnosticIDs.h(48): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(49): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(50): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(51): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(52): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(53): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(54): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(55): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(56): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(57): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(58): warning C5054: operator '+': 
deprecated between enumerations of different types
clang\include\clang/Basic/DiagnosticIDs.h(59): warning C5054: operator '+': 
deprecated between enumerations of different types

Patch By: Godin

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticIDs.h

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index 709d5e1dc80d4..91b180f8004de 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -45,18 +45,18 @@ namespace clang {
 // Start position for diagnostics.
 enum {
   DIAG_START_COMMON=  0,
-  DIAG_START_DRIVER= DIAG_START_COMMON+ DIAG_SIZE_COMMON,
-  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ DIAG_SIZE_DRIVER,
-  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + DIAG_SIZE_FRONTEND,
-  DIAG_START_LEX   = DIAG_START_SERIALIZATION + 
DIAG_SIZE_SERIALIZATION,
-  DIAG_START_PARSE = DIAG_START_LEX   + DIAG_SIZE_LEX,
-  DIAG_START_AST   = DIAG_START_PARSE + DIAG_SIZE_PARSE,
-  DIAG_START_COMMENT   = DIAG_START_AST   + DIAG_SIZE_AST,
-  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + DIAG_SIZE_COMMENT,
-  DIAG_START_SEMA  = DIAG_START_CROSSTU   + DIAG_SIZE_CROSSTU,
-  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + DIAG_SIZE_SEMA,
-  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + DIAG_SIZE_ANALYSIS,
-  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
DIAG_SIZE_REFACTORING
+  DIAG_START_DRIVER= DIAG_START_COMMON+ 
static_cast(DIAG_SIZE_COMMON),
+  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ 
static_cast(DIAG_SIZE_DRIVER),
+  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + 
static_cast(DIAG_SIZE_FRONTEND),
+  DIAG_START_LEX   = DIAG_START_SERIALIZATION + 
static_cast(DIAG_SIZE_SERIALIZATION),
+  DIAG_START_PARSE = DIAG_START_LEX   + 
static_cast(DIAG_SIZE_LEX),
+  DIAG_START_AST   = DIAG_START_PARSE + 
static_cast(DIAG_SIZE_PARSE),
+  DIAG_START_COMMENT   = DIAG_START_AST   + 
static_cast(DIAG_SIZE_AST),
+  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + 
static_cast(DIAG_SIZE_COMMENT),
+  DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
+  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
+  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
+  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING)
 };
 
 class CustomDiagInfo;



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


[PATCH] D130476: [NFC] Fix some C++20 warnings

2022-07-26 Thread Balázs Benics 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 rGba198e35fd38: [NFC] Fix some C++20 warnings (authored by 
Godin, committed by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130476

Files:
  clang/include/clang/Basic/DiagnosticIDs.h


Index: clang/include/clang/Basic/DiagnosticIDs.h
===
--- clang/include/clang/Basic/DiagnosticIDs.h
+++ clang/include/clang/Basic/DiagnosticIDs.h
@@ -45,18 +45,18 @@
 // Start position for diagnostics.
 enum {
   DIAG_START_COMMON=  0,
-  DIAG_START_DRIVER= DIAG_START_COMMON+ DIAG_SIZE_COMMON,
-  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ DIAG_SIZE_DRIVER,
-  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + DIAG_SIZE_FRONTEND,
-  DIAG_START_LEX   = DIAG_START_SERIALIZATION + 
DIAG_SIZE_SERIALIZATION,
-  DIAG_START_PARSE = DIAG_START_LEX   + DIAG_SIZE_LEX,
-  DIAG_START_AST   = DIAG_START_PARSE + DIAG_SIZE_PARSE,
-  DIAG_START_COMMENT   = DIAG_START_AST   + DIAG_SIZE_AST,
-  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + DIAG_SIZE_COMMENT,
-  DIAG_START_SEMA  = DIAG_START_CROSSTU   + DIAG_SIZE_CROSSTU,
-  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + DIAG_SIZE_SEMA,
-  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + DIAG_SIZE_ANALYSIS,
-  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
DIAG_SIZE_REFACTORING
+  DIAG_START_DRIVER= DIAG_START_COMMON+ 
static_cast(DIAG_SIZE_COMMON),
+  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ 
static_cast(DIAG_SIZE_DRIVER),
+  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + 
static_cast(DIAG_SIZE_FRONTEND),
+  DIAG_START_LEX   = DIAG_START_SERIALIZATION + 
static_cast(DIAG_SIZE_SERIALIZATION),
+  DIAG_START_PARSE = DIAG_START_LEX   + 
static_cast(DIAG_SIZE_LEX),
+  DIAG_START_AST   = DIAG_START_PARSE + 
static_cast(DIAG_SIZE_PARSE),
+  DIAG_START_COMMENT   = DIAG_START_AST   + 
static_cast(DIAG_SIZE_AST),
+  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + 
static_cast(DIAG_SIZE_COMMENT),
+  DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
+  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
+  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
+  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING)
 };
 
 class CustomDiagInfo;


Index: clang/include/clang/Basic/DiagnosticIDs.h
===
--- clang/include/clang/Basic/DiagnosticIDs.h
+++ clang/include/clang/Basic/DiagnosticIDs.h
@@ -45,18 +45,18 @@
 // Start position for diagnostics.
 enum {
   DIAG_START_COMMON=  0,
-  DIAG_START_DRIVER= DIAG_START_COMMON+ DIAG_SIZE_COMMON,
-  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ DIAG_SIZE_DRIVER,
-  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + DIAG_SIZE_FRONTEND,
-  DIAG_START_LEX   = DIAG_START_SERIALIZATION + DIAG_SIZE_SERIALIZATION,
-  DIAG_START_PARSE = DIAG_START_LEX   + DIAG_SIZE_LEX,
-  DIAG_START_AST   = DIAG_START_PARSE + DIAG_SIZE_PARSE,
-  DIAG_START_COMMENT   = DIAG_START_AST   + DIAG_SIZE_AST,
-  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + DIAG_SIZE_COMMENT,
-  DIAG_START_SEMA  = DIAG_START_CROSSTU   + DIAG_SIZE_CROSSTU,
-  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + DIAG_SIZE_SEMA,
-  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + DIAG_SIZE_ANALYSIS,
-  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + DIAG_SIZE_REFACTORING
+  DIAG_START_DRIVER= DIAG_START_COMMON+ static_cast(DIAG_SIZE_COMMON),
+  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ static_cast(DIAG_SIZE_DRIVER),
+  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + static_cast(DIAG_SIZE_FRONTEND),
+  DIAG_START_LEX   = DIAG_START_SERIALIZATION + static_cast(DIAG_SIZE_SERIALIZATION),
+  DIAG_START_PARSE = DIAG_START_LEX   + static_cast(DIAG_SIZE_LEX),
+  DIAG_START_AST   = DIAG_START_PARSE + static_cast(DIAG_SIZE_PARSE),
+  DIAG_START_COMMENT   = DIAG_START_AST   + static_cast(DIAG_SIZE_AST),
+  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + static_cast(DIAG_SIZE_COMMENT),
+  DIAG_START_SEMA  = DIAG_START_CROSSTU   + stat

[PATCH] D130519: [clang][dataflow] Add explicit "AST" nodes for implications and iff

2022-07-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:40-41
 
 // Synthetic boolean values are either atomic values or composites that
 // represent conjunctions, disjunctions, and negations.
 AtomicBool,

sgatev wrote:
> 
Applied.



Comment at: clang/lib/Analysis/FlowSensitive/DebugSupport.cpp:110
+  auto R = debugString(BV.getRightSubValue(), Depth + 1);
+  S = formatv("(=\n{0}\n{1})", L, R);
+  break;

sgatev wrote:
> I think `<=>` would be more natural.
Yeah, but `=` is what smtlib uses.



Comment at: clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp:332
+
+  if (LeftSubVar == RightSubVar) {
+// `X <=> (A <=> A)` is equvalent to `X` which is already in

xazax.hun wrote:
> gribozavr2 wrote:
> > xazax.hun wrote:
> > > xazax.hun wrote:
> > > > I wonder why this simplification is done here only for 
> > > > `BiconditionalValue`. Other operations seem to not do these sorts of 
> > > > simplifications. Also, when would we take this branch? `getOrCreateIff` 
> > > > has a special case when both operands are the same. 
> > > Oh, looking at the other patch I see it mentioning desugaring. So can 
> > > desugaring also introduce `Biconditional`s?
> > It is also necessary in the other cases due to the precondition of 
> > `addClause()`, I'm adding that special handling in a separate patch: 
> > https://reviews.llvm.org/D130522
> > 
> > We would take this branch when someone avoids using the DataflowContext 
> > API. So not extremely likely at the moment, but it is a latent bug that can 
> > be exposed by some future refactoring.
> I see, thanks! 
Marking done.



Comment at: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp:201
+
+  expectUnsatisfiable(solve({NotEquivalent}));
+}

sgatev wrote:
> Let's add a label: `!((X <=> Y) <=> ((X ^ Y) v (!X ^ !Y)))`
Added!



Comment at: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp:303
+
+  expectUnsatisfiable(solve({NotEquivalent}));
+}

sgatev wrote:
> Let's add a label: `!((X => Y) <=> (!X v Y))`
Added!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130519

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


[clang] b5e3dac - [clang][dataflow] Add explicit "AST" nodes for implications and iff

2022-07-26 Thread Dmitri Gribenko via cfe-commits

Author: Dmitri Gribenko
Date: 2022-07-26T14:19:22+02:00
New Revision: b5e3dac33d42cdf8a3b19b1f64b726e700363ded

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

LOG: [clang][dataflow] Add explicit "AST" nodes for implications and iff

Previously we used to desugar implications and biconditionals into
equivalent CNF/DNF as soon as possible. However, this desugaring makes
debug output (Environment::dump()) less readable than it could be.
Therefore, it makes sense to keep the sugared representation of a
boolean formula, and desugar it in the solver.

Reviewed By: sgatev, xazax.hun, wyt

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/Value.h
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index abc3183e1b0b5..b3e725ad3f6a5 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -340,6 +340,10 @@ class DataflowAnalysisContext {
   llvm::DenseMap, DisjunctionValue *>
   DisjunctionVals;
   llvm::DenseMap NegationVals;
+  llvm::DenseMap, ImplicationValue *>
+  ImplicationVals;
+  llvm::DenseMap, BiconditionalValue *>
+  BiconditionalVals;
 
   // Flow conditions are tracked symbolically: each unique flow condition is
   // associated with a fresh symbolic variable (token), bound to the clause 
that

diff  --git a/clang/include/clang/Analysis/FlowSensitive/Value.h 
b/clang/include/clang/Analysis/FlowSensitive/Value.h
index 70348f8745431..c63799fe6a464 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Value.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Value.h
@@ -37,12 +37,13 @@ class Value {
 Pointer,
 Struct,
 
-// Synthetic boolean values are either atomic values or composites that
-// represent conjunctions, disjunctions, and negations.
+// Synthetic boolean values are either atomic values or logical 
connectives.
 AtomicBool,
 Conjunction,
 Disjunction,
-Negation
+Negation,
+Implication,
+Biconditional,
   };
 
   explicit Value(Kind ValKind) : ValKind(ValKind) {}
@@ -84,7 +85,9 @@ class BoolValue : public Value {
 return Val->getKind() == Kind::AtomicBool ||
Val->getKind() == Kind::Conjunction ||
Val->getKind() == Kind::Disjunction ||
-   Val->getKind() == Kind::Negation;
+   Val->getKind() == Kind::Negation ||
+   Val->getKind() == Kind::Implication ||
+   Val->getKind() == Kind::Biconditional;
   }
 };
 
@@ -162,6 +165,54 @@ class NegationValue : public BoolValue {
   BoolValue &SubVal;
 };
 
+/// Models a boolean implication.
+///
+/// Equivalent to `!LHS v RHS`.
+class ImplicationValue : public BoolValue {
+public:
+  explicit ImplicationValue(BoolValue &LeftSubVal, BoolValue &RightSubVal)
+  : BoolValue(Kind::Implication), LeftSubVal(LeftSubVal),
+RightSubVal(RightSubVal) {}
+
+  static bool classof(const Value *Val) {
+return Val->getKind() == Kind::Implication;
+  }
+
+  /// Returns the left sub-value of the implication.
+  BoolValue &getLeftSubValue() const { return LeftSubVal; }
+
+  /// Returns the right sub-value of the implication.
+  BoolValue &getRightSubValue() const { return RightSubVal; }
+
+private:
+  BoolValue &LeftSubVal;
+  BoolValue &RightSubVal;
+};
+
+/// Models a boolean biconditional.
+///
+/// Equivalent to `(LHS ^ RHS) v (!LHS ^ !RHS)`.
+class BiconditionalValue : public BoolValue {
+public:
+  explicit BiconditionalValue(BoolValue &LeftSubVal, BoolValue &RightSubVal)
+  : BoolValue(Kind::Biconditional), LeftSubVal(LeftSubVal),
+RightSubVal(RightSubVal) {}
+
+  static bool classof(const Value *Val) {
+return Val->getKind() == Kind::Biconditional;
+  }
+
+  /// Returns the left sub-value of the biconditional.
+  BoolValue &getLeftSubValue() const { return LeftSubVal; }
+
+  /// Returns the right sub-value of the biconditional.
+  BoolValue &getRightSubValue() const { return RightSubVal; }
+
+private:
+  BoolValue &LeftSubVal;
+  BoolValue &RightSubVal;
+};
+
 /// Models an integer.
 class Intege

[PATCH] D130519: [clang][dataflow] Add explicit "AST" nodes for implications and iff

2022-07-26 Thread Dmitri Gribenko 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 rGb5e3dac33d42: [clang][dataflow] Add explicit "AST" 
nodes for implications and iff (authored by gribozavr).

Changed prior to commit:
  https://reviews.llvm.org/D130519?vs=447484&id=447650#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130519

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
  clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -251,12 +251,16 @@
 
   // Creates a boolean implication value.
   BoolValue *impl(BoolValue *LeftSubVal, BoolValue *RightSubVal) {
-return disj(neg(LeftSubVal), RightSubVal);
+Vals.push_back(
+std::make_unique(*LeftSubVal, *RightSubVal));
+return Vals.back().get();
   }
 
   // Creates a boolean biconditional value.
   BoolValue *iff(BoolValue *LeftSubVal, BoolValue *RightSubVal) {
-return conj(impl(LeftSubVal, RightSubVal), impl(RightSubVal, LeftSubVal));
+Vals.push_back(
+std::make_unique(*LeftSubVal, *RightSubVal));
+return Vals.back().get();
   }
 
 private:
Index: clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
@@ -206,6 +206,20 @@
   expectUnsatisfiable(solve({XOrY, NotXOrY, NotXOrNotY, XOrNotY}));
 }
 
+TEST(SolverTest, IffIsEquivalentToDNF) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto Y = Ctx.atom();
+  auto NotX = Ctx.neg(X);
+  auto NotY = Ctx.neg(Y);
+  auto XIffY = Ctx.iff(X, Y);
+  auto XIffYDNF = Ctx.disj(Ctx.conj(X, Y), Ctx.conj(NotX, NotY));
+  auto NotEquivalent = Ctx.neg(Ctx.iff(XIffY, XIffYDNF));
+
+  // !((X <=> Y) <=> ((X ^ Y) v (!X ^ !Y)))
+  expectUnsatisfiable(solve({NotEquivalent}));
+}
+
 TEST(SolverTest, IffSameVars) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
@@ -297,6 +311,18 @@
   expectUnsatisfiable(solve({XEqY, X, NotY}));
 }
 
+TEST(SolverTest, ImplicationIsEquivalentToDNF) {
+  ConstraintContext Ctx;
+  auto X = Ctx.atom();
+  auto Y = Ctx.atom();
+  auto XImpliesY = Ctx.impl(X, Y);
+  auto XImpliesYDNF = Ctx.disj(Ctx.neg(X), Y);
+  auto NotEquivalent = Ctx.neg(Ctx.iff(XImpliesY, XImpliesYDNF));
+
+  // !((X => Y) <=> (!X v Y))
+  expectUnsatisfiable(solve({NotEquivalent}));
+}
+
 TEST(SolverTest, ImplicationConflict) {
   ConstraintContext Ctx;
   auto X = Ctx.atom();
Index: clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
@@ -64,33 +64,24 @@
 }
 
 TEST(BoolValueDebugStringTest, Implication) {
-  // B0 => B1, implemented as !B0 v B1
+  // B0 => B1
   ConstraintContext Ctx;
-  auto B = Ctx.disj(Ctx.neg(Ctx.atom()), Ctx.atom());
+  auto B = Ctx.impl(Ctx.atom(), Ctx.atom());
 
-  auto Expected = R"((or
-(not
-B0)
+  auto Expected = R"((=>
+B0
 B1))";
   EXPECT_THAT(debugString(*B), StrEq(Expected));
 }
 
 TEST(BoolValueDebugStringTest, Iff) {
-  // B0 <=> B1, implemented as (!B0 v B1) ^ (B0 v !B1)
+  // B0 <=> B1
   ConstraintContext Ctx;
-  auto B0 = Ctx.atom();
-  auto B1 = Ctx.atom();
-  auto B = Ctx.conj(Ctx.disj(Ctx.neg(B0), B1), Ctx.disj(B0, Ctx.neg(B1)));
+  auto B = Ctx.iff(Ctx.atom(), Ctx.atom());
 
-  auto Expected = R"((and
-(or
-(not
-B0)
-B1)
-(or
-B0
-(not
-B1";
+  auto Expected = R"((=
+B0
+B1))";
   EXPECT_THAT(debugString(*B), StrEq(Expected));
 }
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -304,7 +304,7 @@
 }
 #endif
 
-TEST_F(DataflowAnalysisContextTest, SubstituteFlowConditionsAtomicFC) {
+TEST_F(DataflowAnalysisContextTest, SubstituteFlowConditionContainingAtomic) {
   auto &X = Context.

[PATCH] D130270: [clang][dataflow] Use a dedicated bool to encode which branch was taken

2022-07-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 requested changes to this revision.
gribozavr2 added a comment.
This revision now requires changes to proceed.

Sorry, could you rebase the patch? It does not apply cleanly anymore.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130270

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


[PATCH] D130306: [clang][dataflow] Analyze calls to in-TU functions

2022-07-26 Thread Sam Estep via Phabricator via cfe-commits
samestep added a comment.

@xazax.hun Do you have anything else you'd like addressed/changed (either here 
or in the doc we shared with you) before I land this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130306

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


[PATCH] D130270: [clang][dataflow] Use a dedicated bool to encode which branch was taken

2022-07-26 Thread Sam Estep via Phabricator via cfe-commits
samestep updated this revision to Diff 447656.
samestep added a comment.

Rebase and add Yitzie's assertion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130270

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -1175,4 +1175,33 @@
   });
 }
 
+TEST_F(FlowConditionTest, JoinBackedge) {
+  std::string Code = R"(
+void target(bool Cond) {
+  bool Foo = true;
+  while (true) {
+(void)0;
+// [[p]]
+Foo = false;
+  }
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+auto &FooVal = *cast(Env.getValue(*FooDecl, SkipPast::None));
+
+EXPECT_FALSE(Env.flowConditionImplies(FooVal));
+EXPECT_FALSE(Env.flowConditionImplies(Env.makeNot(FooVal)));
+  });
+}
+
 } // namespace
Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -179,7 +179,8 @@
   Context.addFlowConditionConstraint(FC2, C2);
   Context.addFlowConditionConstraint(FC2, C3);
 
-  auto &FC3 = Context.joinFlowConditions(FC1, FC2);
+  auto &B = Context.createAtomicBoolValue();
+  auto &FC3 = Context.joinFlowConditions(FC1, FC2, B);
   EXPECT_FALSE(Context.flowConditionImplies(FC3, C1));
   EXPECT_FALSE(Context.flowConditionImplies(FC3, C2));
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
@@ -435,38 +436,49 @@
   // FC2 = Y
   auto &FC2 = Context.makeFlowConditionToken();
   Context.addFlowConditionConstraint(FC2, Y);
-  // JoinedFC = (FC1 || FC2) && Z = (X || Y) && Z
-  auto &JoinedFC = Context.joinFlowConditions(FC1, FC2);
+  // JoinedFC = ((!B && FC1) || (B && FC2)) && Z = ((!B && X) || (B && Y)) && Z
+  auto &B = Context.createAtomicBoolValue();
+  auto &JoinedFC = Context.joinFlowConditions(FC1, FC2, B);
   Context.addFlowConditionConstraint(JoinedFC, Z);
 
-  // If any of X, Y is true in JoinedFC, JoinedFC = (X || Y) && Z is equivalent
-  // to evaluating the remaining Z
-  auto &JoinedFCWithXTrue =
-  Context.buildAndSubstituteFlowCondition(JoinedFC, {{&X, &True}});
-  auto &JoinedFCWithYTrue =
-  Context.buildAndSubstituteFlowCondition(JoinedFC, {{&Y, &True}});
+  // If any of (!B && X), (B && Y) is true in JoinedFC,
+  // JoinedFC = ((!B && X) || (B && Y)) && Z is equivalent to evaluating the
+  // remaining Z
+  auto &JoinedFCWithXTrue = Context.buildAndSubstituteFlowCondition(
+  JoinedFC, {{&B, &False}, {&X, &True}});
+  auto &JoinedFCWithYTrue = Context.buildAndSubstituteFlowCondition(
+  JoinedFC, {{&B, &True}, {&Y, &True}});
   EXPECT_TRUE(Context.equivalentBoolValues(JoinedFCWithXTrue, Z));
   EXPECT_TRUE(Context.equivalentBoolValues(JoinedFCWithYTrue, Z));
 
-  // If Z is true in JoinedFC, JoinedFC = (X || Y) && Z is equivalent to
-  // evaluating the remaining disjunction (X || Y)
+  // If Z is true in JoinedFC, JoinedFC = ((!B && X) || (B && Y)) && Z is
+  // equivalent to evaluating the remaining disjunction ((!B && X) || (B && Y))
   auto &JoinedFCWithZTrue =
   Context.buildAndSubstituteFlowCondition(JoinedFC, {{&Z, &True}});
   EXPECT_TRUE(Context.equivalentBoolValues(
-  JoinedFCWithZTrue, Context.getOrCreateDisjunction(X, Y)));
-
-  // If any of X, Y is false in JoinedFC, JoinedFC = (X || Y) && Z is equivalent
-  // to evaluating the conjunction of the other value and Z
+  JoinedFCWithZTrue,
+  Context.getOrCreateDisjunction(
+  Context.getOrCreateConjunction(Context.getOrCreateNegation(B), X),
+  Context.getOrCreateConjunction(B, Y;
+
+  // If any of X, Y is false in JoinedFC,
+  // JoinedFC = ((!B && X) || (B && Y)) && Z is equivalent to evaluating the
+  // conjunction of the other disjunct and Z
   auto &JoinedFCWithXFalse =
   Context.buildAndSubstituteFlowCondition(JoinedFC, {{&X, &False}});
   auto &JoinedFCWithYFalse =
   Context.buildA

[PATCH] D130270: [clang][dataflow] Use a dedicated bool to encode which branch was taken

2022-07-26 Thread Sam Estep via Phabricator via cfe-commits
samestep added a comment.

In D130270#3679273 , @gribozavr2 
wrote:

> Sorry, could you rebase the patch? It does not apply cleanly anymore.

Done; I didn't see any conflicts when I rebased, but hopefully the issue on 
your end is resolved now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130270

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


[clang] 99daf6b - [C++20] [Modules] Don't handle no linkage entities when overloading

2022-07-26 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-07-26T21:07:41+08:00
New Revision: 99daf6b2636245446cab0a7800e36fd34777e599

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

LOG: [C++20] [Modules] Don't handle no linkage entities when overloading

The original implementation uses `ND->getFormalLinkage() <=
Linkage::InternalLinkage`. It is not right since the spec only says
internal linkage and it doesn't mention 'no linkage'. This matters when
we consider constructors. According to [class.ctor.general]p1,
constructors have no name so constructors have no linkage too.

Added: 
clang/test/Modules/ctor.arg.dep.cppm

Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 7207ce7c4d21e..5dc0aadb2d5f3 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -6413,7 +6413,7 @@ void Sema::AddOverloadCandidate(
   if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
 ND = SpecInfo->getTemplate();
   
-  if (ND->getFormalLinkage() <= Linkage::InternalLinkage) {
+  if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
 Candidate.Viable = false;
 Candidate.FailureKind = ovl_fail_module_mismatched;
 return;

diff  --git a/clang/test/Modules/ctor.arg.dep.cppm 
b/clang/test/Modules/ctor.arg.dep.cppm
new file mode 100644
index 0..0e5b1a694f6a5
--- /dev/null
+++ b/clang/test/Modules/ctor.arg.dep.cppm
@@ -0,0 +1,44 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/A.cppm -I%t -emit-module-interface -o %t/A.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %t/Use.cpp -verify 
-fsyntax-only
+//
+//--- foo.h
+
+namespace ns {
+
+struct T {
+T(void*);
+};
+
+struct A {
+template 
+A(F f) : t(&f)  {}
+
+T t;
+};
+
+template 
+void foo(T) {
+auto f = [](){};
+ns::A a(f);
+}
+}
+
+//--- A.cppm
+module;
+#include "foo.h"
+export module A;
+export namespace ns {
+using ns::A;
+using ns::foo;
+}
+
+//--- Use.cpp
+// expected-no-diagnostics
+import A;
+void test() {
+ns::foo(5);
+}



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


[PATCH] D130550: [pseudo] Start rules are `_ := start-symbol EOF`, improve recovery.

2022-07-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

+1 on this change, it would make the expose-lookahead-index-to-guard change 
easier.




Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:74
 bool GCParity;
+// Have we already used this node for error recovery? (prevents loops)
+mutable bool Recovered = false;

haven't look at it deeply -- is this bug related to this eof change? This looks 
like a different bug in recovery.



Comment at: clang-tools-extra/pseudo/lib/Forest.cpp:191
+  // This is important to drive the final shift/recover/reduce loop.
+  new (&Terminals[Index])
+  ForestNode(ForestNode::Terminal, tokenSymbol(tok::eof),

nit: in the underlying TokenStream implementation, `tokens()` has a trailing 
eof token, I think we can fold this into the above loop (if we expose a 
`token_eof()` method in TokenStream). Not sure we should do this. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130550

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


[PATCH] D128190: [WinEH] Apply funclet operand bundles to nounwind intrinsics that lower to function calls

2022-07-26 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz updated this revision to Diff 447667.
sgraenitz marked 2 inline comments as done.
sgraenitz added a comment.

Rebase and polish comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128190

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
  llvm/include/llvm/IR/IntrinsicInst.h
  llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
  llvm/lib/IR/IntrinsicInst.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/test/CodeGen/X86/win64-funclet-preisel-intrinsics.ll
  llvm/test/Feature/OperandBundles/inliner-funclet-wineh.ll

Index: llvm/test/Feature/OperandBundles/inliner-funclet-wineh.ll
===
--- /dev/null
+++ llvm/test/Feature/OperandBundles/inliner-funclet-wineh.ll
@@ -0,0 +1,51 @@
+; RUN: opt -S -always-inline -mtriple=x86_64-windows-msvc < %s | FileCheck %s
+
+; WinEH requires funclet tokens on nounwind intrinsics if they can lower to
+; regular function calls in the course of IR transformations.
+;
+; Test that the inliner propagates funclet tokens to such intrinsics when
+; inlining into EH funclets, i.e.: llvm.objc.storeStrong inherits the "funclet"
+; token from inlined_fn.
+
+define void @inlined_fn(ptr %ex) #1 {
+entry:
+  call void @llvm.objc.storeStrong(ptr %ex, ptr null)
+  ret void
+}
+
+define void @test_catch_with_inline() personality ptr @__CxxFrameHandler3 {
+entry:
+  %exn.slot = alloca ptr, align 8
+  %ex = alloca ptr, align 8
+  invoke void @opaque() to label %invoke.cont unwind label %catch.dispatch
+
+catch.dispatch:
+  %0 = catchswitch within none [label %catch] unwind to caller
+
+invoke.cont:
+  unreachable
+
+catch:
+  %1 = catchpad within %0 [ptr null, i32 64, ptr %exn.slot]
+  call void @inlined_fn(ptr %ex) [ "funclet"(token %1) ]
+  catchret from %1 to label %catchret.dest
+
+catchret.dest:
+  ret void
+}
+
+declare void @opaque()
+declare void @llvm.objc.storeStrong(ptr, ptr) #0
+declare i32 @__CxxFrameHandler3(...)
+
+attributes #0 = { nounwind }
+attributes #1 = { alwaysinline }
+
+; After inlining, llvm.objc.storeStrong inherited the "funclet" token:
+;
+;   CHECK-LABEL:  define void @test_catch_with_inline()
+;   ...
+;   CHECK:catch:
+;   CHECK-NEXT: %1 = catchpad within %0 [ptr null, i32 64, ptr %exn.slot]
+;   CHECK-NEXT: call void @llvm.objc.storeStrong(ptr %ex, ptr null) [ "funclet"(token %1) ]
+;   CHECK-NEXT: catchret from %1 to label %catchret.dest
Index: llvm/test/CodeGen/X86/win64-funclet-preisel-intrinsics.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/win64-funclet-preisel-intrinsics.ll
@@ -0,0 +1,77 @@
+; RUN: llc -mtriple=x86_64-windows-msvc < %s | FileCheck %s
+
+; WinEH requires funclet tokens on nounwind intrinsics if they can lower to
+; regular function calls in the course of IR transformations.
+;
+; Test that the code generator will emit the function call and not consider it
+; an "implausible instruciton". In the past this silently truncated code on
+; exception paths and caused crashes at runtime.
+;
+; Reduced IR generated from ObjC++ source:
+;
+; @class Ety;
+; void opaque(void);
+; void test_catch_with_objc_intrinsic(void) {
+;   @try {
+; opaque();
+;   } @catch (Ety *ex) {
+; // Destroy ex when leaving catchpad. This would emit calls to two
+; // intrinsic functions: llvm.objc.retain and llvm.objc.storeStrong
+;   }
+; }
+;
+; llvm.objc.retain and llvm.objc.storeStrong both lower into regular function
+; calls before ISel. We only need one of them to trigger funclet truncation
+; during codegen:
+
+define void @test_catch_with_objc_intrinsic() personality ptr @__CxxFrameHandler3 {
+entry:
+  %exn.slot = alloca ptr, align 8
+  %ex2 = alloca ptr, align 8
+  invoke void @opaque() to label %invoke.cont unwind label %catch.dispatch
+
+catch.dispatch:
+  %0 = catchswitch within none [label %catch] unwind to caller
+
+invoke.cont:
+  unreachable
+
+catch:
+  %1 = catchpad within %0 [ptr null, i32 64, ptr %exn.slot]
+  call void @llvm.objc.storeStrong(ptr %ex2, ptr null) [ "funclet"(token %1) ]
+  catchret from %1 to label %catchret.dest
+
+catchret.dest:
+  ret void
+}
+
+declare void @opaque()
+declare void @llvm.objc.storeStrong(ptr, ptr) #0
+declare i32 @__CxxFrameHandler3(...)
+
+attributes #0 = { nounwind }
+
+; EH catchpad with SEH prologue:
+; CHECK: # %catch
+; CHECK: pushq   %rbp
+; CHECK: .seh_pushreg %rbp
+;...
+; CHECK: .seh_endprologue
+;
+; At this point the code used to be truncated (and sometimes terminated with an
+; int3 opcode):
+; CHECK-NOT: int3
+;
+; Instead, the call to objc_storeStrong should be emitted:
+; CHECK: leaq	-24(%rbp), %rcx
+; CHECK: xorl	%edx, %edx
+; CHECK: callq	objc_storeStrong
+;...
+;
+; This is the end of the funclet

[PATCH] D128190: [WinEH] Apply funclet operand bundles to nounwind intrinsics that lower to function calls

2022-07-26 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz added a comment.

Hi @theraven thanks for reviewing!




Comment at: llvm/lib/IR/IntrinsicInst.cpp:61
+  case Intrinsic::objc_sync_enter:
+  case Intrinsic::objc_sync_exit:
+return true;

theraven wrote:
> I'm curious why memcpy and friends don't need to be on this list.  Do they 
> get expanded at a different point?  Or is it that the front end inserts a 
> memcpy call and the optimiser that turns them into intrinsics and back 
> preserves operand bundles?  It would be a good idea to have a comment 
> explaining why these specific ones are on the list and not other libc (or 
> math library) functions that may appear in cleanup blocks.  From the code in 
> `InlineFunction.cpp`, it looks as if this is a problem only for intrinsics 
> that may throw, which excludes most of the C standard ones?
The name `mayLowerToFunctionCall` was proposed in a precursor to this review: 
https://reviews.llvm.org/D127962#inline-1227485. I agree that the term might 
appear overly general at first. I still followed the advice because:
(1) This controls assignment and propagation of operand bundles, which is a 
very general concept.
(2) From the perspective of IR transformations, only a few intrinsics actually 
lower to function calls (the majority remains intrinsics).
(3) The approach might be applied to other intrinsics, e.g. statepoints

However, this is not obvious and because other readers might have the same 
question, I extended my comment in the header like this:
```
Check if the intrinsic might lower into a regular function call in the course 
of IR transformations
```

Do you think that makes it more clear?

**For additional context**
Right now the list only contains ObjC ARC intrinsics. These are subject to 
`PreISelIntrinsicLowering` which means they are lowered to regular function 
calls before we run exception handling passes:
https://github.com/llvm/llvm-project/blob/c73adbad6a9964e0700865b7c786cc6885898c68/llvm/lib/CodeGen/TargetPassConfig.cpp#L1114-L1118

WinEHPrepare is an exception handling pass and it accepts call instructions in 
EH funclets only if they: 
* target nounwind intrinsics or inline assembly
* have a matching funclet bundle operand

It declares other calls as "implausible instructions" and marks them 
unreachable, which caused the truncation bug that this patch aims to fix.

All ObjC ARC intrinsics have the `nounwind` attribute. My understanding is that 
the only user-code that might run in turn of an invocation can be destructors 
-- and they don't throw per definition.

The reason libc functions like memcpy are not in this list is that they are 
lowered at a later point in time. In the context of WinEHPrepare (and opt in 
general) they are always intrinsics. 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128190

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


[PATCH] D128955: [WPD] Use new llvm.public.type.test intrinsic for potentially publicly visible classes

2022-07-26 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson accepted this revision.
tejohnson added a comment.
This revision is now accepted and ready to land.

lgtm

In D128955#3676478 , @aeubanks wrote:

> In D128955#3676198 , @tejohnson 
> wrote:
>
>> In D128955#3674787 , @aeubanks 
>> wrote:
>>
>>> random question, if the old API is "legacy", are there any plans to remove 
>>> it?
>>
>> @fhahn started to work on this at some point (see 
>> https://bugs.llvm.org/show_bug.cgi?id=41541), but I'm not sure of the 
>> status. It is used by ld64 and I believe the sony toolchain too.
>
> if I'm seeing correctly, looks like there aren't any in-tree users of 
> ThinLTOCodeGenerator/LTOCodeGenerator. are those out of tree?

Yes, all linker users are out of tree. Only llvm-lto is in tree for testing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128955

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


[PATCH] D130566: [Driver] Default to DWARF 4 on Linux/sparc64

2022-07-26 Thread Rainer Orth via Phabricator via cfe-commits
ro created this revision.
ro added reviewers: glaubitz, MaskRay.
ro added a project: clang.
Herald added subscribers: jsji, StephenFan, pengfei, fedor.sergeev, jyknight.
Herald added a project: All.
ro requested review of this revision.

During a build on Debian 11/sparc64, several binaries fail to link with

  /usr/bin/ld: /usr/bin/ld: DWARF error: invalid or unhandled FORM value: 0x23

`/usr/bin/ld` is `GNU ld (GNU Binutils for Debian) 2.38.50.20220707`.  `0x23 is 
`DW_FORM_rnglistx` which isn't handled even by GNU binutils master.  Building 
with `-gdwarf-4` avoids this.

Tested on `sparc64-unknown-linux-gnu`.

For comparison's sake, I've tried a build on Ubuntu 20.04/x86_64 with GNU `ld` 
2.38.90, which isn't affected.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130566

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


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -325,7 +325,7 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  if (getTriple().isAndroid() || getTriple().isSPARC())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -325,7 +325,7 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  if (getTriple().isAndroid() || getTriple().isSPARC())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129873: [clang-offload-bundler] Library-ize ClangOffloadBundler

2022-07-26 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129873

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


[PATCH] D130566: [Driver] Default to DWARF 4 on Linux/sparc64

2022-07-26 Thread John Paul Adrian Glaubitz via Phabricator via cfe-commits
glaubitz added a comment.

Interesting and thanks for catching this! How did you discover this issue? Is 
there any particular program that fails to build due to this issue?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130566

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


[PATCH] D130569: [Driver] Use libatomic for 32-bit SPARC atomics support on Linux [clang-linux-sparc-libatomic.patch, submitted 2022-07-26]

2022-07-26 Thread Rainer Orth via Phabricator via cfe-commits
ro created this revision.
ro added reviewers: glaubitz, jrtc27, MaskRay, efriedma.
ro added a project: clang.
Herald added subscribers: StephenFan, fedor.sergeev, jyknight.
Herald added a project: All.
ro requested review of this revision.

This is the Linux/sparc64 equivalent to D118021 
, necessary to provide an external 
implementation of atomics on 32-bit SPARC which LLVM cannot inline even with 
`-mcpu=v9` or an equivalent default.

Tested on `sparc64-unknown-linux-gnu`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130569

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


Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -631,6 +631,14 @@
 
   AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
 
+  // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
+  // forcibly link with libatomic as a workaround.
+  if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
+CmdArgs.push_back("--as-needed");
+CmdArgs.push_back("-latomic");
+CmdArgs.push_back("--no-as-needed");
+  }
+
   if (WantPthread && !isAndroid)
 CmdArgs.push_back("-lpthread");
 


Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -631,6 +631,14 @@
 
   AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
 
+  // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
+  // forcibly link with libatomic as a workaround.
+  if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
+CmdArgs.push_back("--as-needed");
+CmdArgs.push_back("-latomic");
+CmdArgs.push_back("--no-as-needed");
+  }
+
   if (WantPthread && !isAndroid)
 CmdArgs.push_back("-lpthread");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130414: [pseudo] Reorganize CXX.h enums

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 6 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h:54
+namespace rules {
+namespace dummy {
+enum Rule {

hokein wrote:
> sammccall wrote:
> > usaxena95 wrote:
> > > sammccall wrote:
> > > > hokein wrote:
> > > > > why there is a dummy namespace here?
> > > > for each NT, we close the previous ns+enum and open new ones.
> > > > For this to work for the first NT, we have to open an ns+enum.
> > > > 
> > > > I can add a comment, but would prefer to do this some other way?
> > > I would include this block in the clang-format off block to show these 
> > > are for the generated code.
> > > ```
> > > //clang-format off
> > > namespace dummy { enum Rule {
> > > ...
> > > };}
> > > //clang-format on
> > > ```
> > Oops, they're not for the generated code, just for the macro definition 
> > (clang-format gets very confused)
> > 
> > Restricted the scope of the formatting-disabled block and tried to improve 
> > the hand-formatting (though I don't think any formatting of this particular 
> > preprocessor trick is very readable)
> ah, I get it (until I read the preprocessed CXX.h code) -- I found it really 
> hard to understand it by literally reading the code here. 
> 
> To make it clear,  I think we can probably add two additional RULE_BEGIN, 
> RULE_END macros? 
> 
>  in `CXXSymbols.inc`, we emit something like
> 
> ```
> RULE_BEGIN(_)
> RULE(_, translation_unit, 135)
> RULE(_, statement_seq, 136)
> RULE(_, declaration_seq, 137))
> RULE_END(_)
> ```
> 
> In CXX.h, we write
> 
> ```
> #define RULE_BEGIN(LHS) namespace LHS { enum Rule : RULE ID {
> #define RULE_END()  }; }
> ```
> 
That would make the callsite more clear, but at the cost of adding ad-hoc bits 
to the CXXSymbols.inc.
I'd prefer to keep it generic if we can (otherwise we might as well just have 
Gen generate the enum definitions directly, right?)

Added a comment to explain the dummy.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h:54-62
+namespace dummy {
+enum Rule {
+//clang-format off
+#define NONTERMINAL(NAME, ID) };} namespace NAME { enum Rule : RuleID {
+#define RULE(LHS, RHS, ID) RHS = ID,
 #include "CXXSymbols.inc"
+  //clang-format on

usaxena95 wrote:
> sammccall wrote:
> > hokein wrote:
> > > why there is a dummy namespace here?
> > for each NT, we close the previous ns+enum and open new ones.
> > For this to work for the first NT, we have to open an ns+enum.
> > 
> > I can add a comment, but would prefer to do this some other way?
> I would include this block in the clang-format off block to show these are 
> for the generated code.
> ```
> //clang-format off
> namespace dummy { enum Rule {
> ...
> };}
> //clang-format on
> ```
Oops, they're not for the generated code, just for the macro definition 
(clang-format gets very confused)

Restricted the scope of the formatting-disabled block and tried to improve the 
hand-formatting (though I don't think any formatting of this particular 
preprocessor trick is very readable)



Comment at: clang-tools-extra/pseudo/lib/cxx/CXX.cpp:119
 
-switch ((cxx::Rule)Declarator->rule()) {
-case Rule::noptr_declarator_0declarator_id: // reached the bottom
+switch (Declarator->rule()) {
+case rule::noptr_declarator::declarator_id: // reached the bottom

hokein wrote:
> sammccall wrote:
> > hokein wrote:
> > > The code of applying the pattern doesn't look much worse to me and it is 
> > > easier to verify the exhaustiveness by human as well. We might loose some 
> > > performance (I hope not a lot), but I think it is a good tradeoff (not 
> > > saying we need do it in this patch).
> > > 
> > > ```
> > > switch (LHSNonterminal(Declarator->rule(), *G)) {
> > >case cxx::Symbol::noptr_declarator: {
> > >   switch ((rule::noptr_declarator)Declarator->rule())  {
> > >  case rule::noptr_declarator::declarator_id:
> > >  
> > >  case 
> > > rule::noptr_declarator::noptr_declarator__parameters_and_qualifiers:
> > >  
> > >   }
> > >...
> > >}
> > > }
> > > ```
> > I guess this is a question of taste, but I find that style very hard to 
> > read.
> > 
> > (Note that it's incorrectly indented, and the indentation rules around 
> > switch/case are one of the main reasons I find nested switches confusing)
> > (Note that it's incorrectly indented, and the indentation rules around 
> > switch/case are one of the main reasons I find nested switches confusing)
> 
> Ah the indentation is weird (it is not what I originally written..). There 
> are ways to make the indentation correct (turn off the clang-format etc).
> 
> If nested switch is hard to read, maybe we can wrap one with a macro to 
> improve the code readability (happy to explore ideas, I think there is value 
> on this pattern).
Maybe - I think nonstandard formatting and

[PATCH] D130566: [Driver] Default to DWARF 4 on Linux/sparc64

2022-07-26 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

In D130566#3679480 , @glaubitz wrote:

> Interesting and thanks for catching this! How did you discover this issue? Is 
> there any particular program that fails to build due to this issue?

Sure: many programs fail to link during `ninja check-all` for this problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130566

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


[PATCH] D130414: [pseudo] Reorganize CXX.h enums

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 447675.
sammccall marked an inline comment as done.
sammccall added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130414

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -113,15 +113,16 @@
   build(R"bnf(
 _ := declaration
 
-declaration := ptr-declarator ;
+declaration := cv-qualifier ptr-declarator ;
 ptr-declarator := * IDENTIFIER
+cv-qualifier := CONST
 
   )bnf");
   ASSERT_TRUE(Diags.empty());
   EXPECT_EQ(G.mangleRule(ruleFor("declaration")),
-"declaration_0ptr_declarator_1semi");
-  EXPECT_EQ(G.mangleRule(ruleFor("ptr-declarator")),
-"ptr_declarator_0star_1identifier");
+"cv_qualifier__ptr_declarator__semi");
+  EXPECT_EQ(G.mangleRule(ruleFor("ptr-declarator")), "star__identifier");
+  EXPECT_EQ(G.mangleRule(ruleFor("cv-qualifier")), "CONST");
 }
 
 TEST_F(GrammarTest, Diagnostics) {
Index: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
===
--- clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
+++ clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
@@ -45,28 +45,6 @@
   return T->Nonterminals[SID].Name;
 }
 
-std::string Grammar::mangleSymbol(SymbolID SID) const {
-  static const char *const TokNames[] = {
-#define TOK(X) #X,
-#define KEYWORD(X, Y) #X,
-#include "clang/Basic/TokenKinds.def"
-  nullptr};
-  if (clang::pseudo::isToken(SID))
-return TokNames[clang::pseudo::symbolToToken(SID)];
-  std::string Name = symbolName(SID).str();
-  // translation-unit -> translation_unit
-  std::replace(Name.begin(), Name.end(), '-', '_');
-  return Name;
-}
-
-std::string Grammar::mangleRule(RuleID RID) const {
-  const auto &R = lookupRule(RID);
-  std::string MangleName = mangleSymbol(R.Target);
-  for (size_t I = 0; I < R.seq().size(); ++I)
-MangleName += llvm::formatv("_{0}{1}", I, mangleSymbol(R.seq()[I]));
-  return MangleName;
-}
-
 llvm::Optional Grammar::findNonterminal(llvm::StringRef Name) const {
   auto It = llvm::partition_point(
   T->Nonterminals,
Index: clang-tools-extra/pseudo/lib/cxx/CXX.cpp
===
--- clang-tools-extra/pseudo/lib/cxx/CXX.cpp
+++ clang-tools-extra/pseudo/lib/cxx/CXX.cpp
@@ -111,42 +111,41 @@
 }
 
 bool isFunctionDeclarator(const ForestNode *Declarator) {
-  assert(Declarator->symbol() == (SymbolID)(cxx::Symbol::declarator));
+  assert(Declarator->symbol() == cxx::Symbol::declarator);
   bool IsFunction = false;
-  using cxx::Rule;
   while (true) {
 // not well-formed code, return the best guess.
 if (Declarator->kind() != ForestNode::Sequence)
   return IsFunction;
 
-switch ((cxx::Rule)Declarator->rule()) {
-case Rule::noptr_declarator_0declarator_id: // reached the bottom
+switch (Declarator->rule()) {
+case rule::noptr_declarator::declarator_id: // reached the bottom
   return IsFunction;
 // *X is a nonfunction (unless X is a function).
-case Rule::ptr_declarator_0ptr_operator_1ptr_declarator:
+case rule::ptr_declarator::ptr_operator__ptr_declarator:
   Declarator = Declarator->elements()[1];
   IsFunction = false;
   continue;
 // X() is a function (unless X is a pointer or similar).
-case Rule::
-declarator_0noptr_declarator_1parameters_and_qualifiers_2trailing_return_type:
-case Rule::noptr_declarator_0noptr_declarator_1parameters_and_qualifiers:
+case rule::declarator::
+noptr_declarator__parameters_and_qualifiers__trailing_return_type:
+case rule::noptr_declarator::noptr_declarator__parameters_and_qualifiers:
   Declarator = Declarator->elements()[0];
   IsFunction = true;
   continue;
 // X[] is an array (unless X is a pointer or function).
-case Rule::
-noptr_declarator_0noptr_declarator_1l_square_2constant_expression_3r_square:
-case Rule::noptr_declarator_0noptr_declarator_1l_square_2r_square:
+case rule::noptr_declarator::
+noptr_declarator__l_square__constant_expression__r_square:
+case rule::noptr_declarator::noptr_declarator__l_square__r_square:
   Declarator = Declarator->elements()[0];
   IsFunction = false;
   continue;
 // (X) is whatever X is.
-case Rule::noptr_declarator_0l_paren_1ptr_declarator_2r_paren:
+case rule::noptr_declarator::l_paren_

[PATCH] D130306: [clang][dataflow] Analyze calls to in-TU functions

2022-07-26 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: rnkovacs.

In D130306#3679294 , @samestep wrote:

> @xazax.hun Do you have anything else you'd like addressed/changed (either 
> here or in the doc we shared with you) before I land this?

Nope, most of my concerns are unrelated to this patch. Sorry for hijacking the 
conversation with some offtopics. Feel free to land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130306

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


[PATCH] D130374: [Passes] add a tail-call-elim pass near the end of the opt pipeline

2022-07-26 Thread Aditya Kumar via Phabricator via cfe-commits
hiraditya added a comment.

Thanks a lot for fixing this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130374

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


[PATCH] D130374: [Passes] add a tail-call-elim pass near the end of the opt pipeline

2022-07-26 Thread Aditya Kumar via Phabricator via cfe-commits
hiraditya added a comment.

In D130374#3675677 , @vdsered wrote:

> Just JFYI :)
> Yes, probably not worth it

that is interesting. do we know why?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130374

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


[PATCH] D130550: [pseudo] Start rules are `_ := start-symbol EOF`, improve recovery.

2022-07-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:74
 bool GCParity;
+// Have we already used this node for error recovery? (prevents loops)
+mutable bool Recovered = false;

hokein wrote:
> haven't look at it deeply -- is this bug related to this eof change? This 
> looks like a different bug in recovery.
They're "related" in that they both fix repeated-recovery scenarios.
This change fixes that we can hit an infinite loop when applying recovery 
repeatedly.
The eof change fixes that recovery is (erroneously) only applied once at eof.

I hoped to cover them with the same testcase, which tests repeated recovery at 
EOF. I can extract this change with a separate test if you like, though it will 
be very similar to the one I have here.



Comment at: clang-tools-extra/pseudo/lib/Forest.cpp:191
+  // This is important to drive the final shift/recover/reduce loop.
+  new (&Terminals[Index])
+  ForestNode(ForestNode::Terminal, tokenSymbol(tok::eof),

hokein wrote:
> nit: in the underlying TokenStream implementation, `tokens()` has a trailing 
> eof token, I think we can fold this into the above loop (if we expose a 
> `token_eof()` method in TokenStream). Not sure we should do this. 
I think this doesn't generalize well... at the moment we're parsing the whole 
stream, but in future we likely want to parse a subrange (pp-disabled 
regions?). In such a case we would still want the terminating EOF terminal as a 
device for parsing, even though there's no corresponding token.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130550

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


[PATCH] D130374: [Passes] add a tail-call-elim pass near the end of the opt pipeline

2022-07-26 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added a comment.

In D130374#3679550 , @hiraditya wrote:

> In D130374#3675677 , @vdsered wrote:
>
>> Just JFYI :)
>> Yes, probably not worth it
>
> that is interesting. do we know why?

Based on this data: 
https://llvm-compile-time-tracker.com/compare.php?from=95f4ca7f5db623bacc2e34548d39fe5b28d47bad&to=bfb9b8e075ee32197157ccaf0c301122ca9b81af&stat=instructions

This patch (adding a late round of TCE) caused a ~0.06% compile-time regression 
for a -O3 build (less for the LTO variants). So the value of splitting the pass 
as proposed in D60031  depends on whether we 
think it's worth trying to save some (unknown?) fraction of the 0.06%.
We decided to push this for the known codegen wins, but someone can still 
revive the pass-splitting patch if it seems worthwhile.

One more note that I failed to mention while updating all of those clang tests: 
the reason those tests did not show "tail" before is because we only ran TCE 
with -O{2/3/s/z}, not -O1. This patch enabled TCE for all -O levels. I don't 
know the history/motivation for not including TCE at -O1 before, but it did not 
seem worth excluding based on compile-time cost. If there's another reason, we 
can add that limitation to the late invocation too (and it should cause 
most/all of the clang test diffs to revert).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130374

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


[PATCH] D130545: [cmake] Slight fix ups to make robust to the full range of GNUInstallDirs

2022-07-26 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 added inline comments.



Comment at: openmp/CMakeLists.txt:3
 
-# Add cmake directory to search for custom cmake functions.
-set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
+set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+

sebastian-ne wrote:
> There are some places that surround this by an `if(NOT DEFINED 
> LLVM_COMMON_CMAKE_UTILS)` (e.g. lldb/cmake/modules/LLDBStandalone.cmake, 
> clang/CMakeLists.txt, polly/CMakeLists.txt) although other places don’t 
> (lld/CMakeLists.txt, libunwind/CMakeLists.txt, etc.), so both seem to be fine.
Ah true. Yeah it should be fine either way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130545

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


[PATCH] D130545: [cmake] Slight fix ups to make robust to the full range of GNUInstallDirs

2022-07-26 Thread John Ericson 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 rG28e665fa054d: [cmake] Slight fix ups to make robust to the 
full range of GNUInstallDirs (authored by Ericson2314).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130545

Files:
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  llvm-libgcc/lib/CMakeLists.txt
  llvm/cmake/modules/CMakeLists.txt
  openmp/CMakeLists.txt
  openmp/runtime/src/CMakeLists.txt

Index: openmp/runtime/src/CMakeLists.txt
===
--- openmp/runtime/src/CMakeLists.txt
+++ openmp/runtime/src/CMakeLists.txt
@@ -8,6 +8,8 @@
 #//===--===//
 #
 
+include(ExtendPath)
+
 # Configure omp.h, kmp_config.h and omp-tools.h if necessary
 configure_file(${LIBOMP_INC_DIR}/omp.h.var omp.h @ONLY)
 configure_file(kmp_config.h.cmake kmp_config.h @ONLY)
@@ -347,8 +349,8 @@
 add_dependencies(libomp-micro-tests libomp-test-deps)
 
 # Install rules
-# We want to install libomp in DESTDIR/CMAKE_INSTALL_PREFIX/lib
-# We want to install headers in DESTDIR/CMAKE_INSTALL_PREFIX/include
+# We want to install libomp in ${DESTDIR}/${CMAKE_INSTALL_FULL_LIBDIR}
+# We want to install headers in ${DESTDIR}/${CMAKE_INSTALL_FULL_INCLUDEDIR}
 if(${OPENMP_STANDALONE_BUILD})
   set(LIBOMP_HEADERS_INSTALL_PATH "${CMAKE_INSTALL_INCLUDEDIR}")
 else()
@@ -362,9 +364,10 @@
   set(LIBOMP_ALIASES "libiomp5md")
   foreach(alias IN LISTS LIBOMP_ALIASES)
 install(CODE "execute_process(COMMAND \"\${CMAKE_COMMAND}\" -E copy \"${LIBOMP_LIB_FILE}\"
-  \"${alias}${LIBOMP_LIBRARY_SUFFIX}\" WORKING_DIRECTORY \"\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}\")")
+  \"${alias}${LIBOMP_LIBRARY_SUFFIX}\" WORKING_DIRECTORY \"${CMAKE_INSTALL_FULL_BINDIR}\")")
+extend_path(outdir "${CMAKE_INSTALL_PREFIX}" "${OPENMP_INSTALL_LIBDIR}")
 install(CODE "execute_process(COMMAND \"\${CMAKE_COMMAND}\" -E copy \"${LIBOMP_IMP_LIB_FILE}\"
-  \"${alias}${CMAKE_STATIC_LIBRARY_SUFFIX}\" WORKING_DIRECTORY \"\${CMAKE_INSTALL_PREFIX}/${OPENMP_INSTALL_LIBDIR}\")")
+  \"${alias}${CMAKE_STATIC_LIBRARY_SUFFIX}\" WORKING_DIRECTORY \"${outdir}\")")
   endforeach()
 else()
 
@@ -374,9 +377,10 @@
 # Create aliases (symlinks) of the library for backwards compatibility
 set(LIBOMP_ALIASES "libgomp;libiomp5")
 foreach(alias IN LISTS LIBOMP_ALIASES)
+  extend_path(outdir "${CMAKE_INSTALL_PREFIX}" "${OPENMP_INSTALL_LIBDIR}")
   install(CODE "execute_process(COMMAND \"\${CMAKE_COMMAND}\" -E create_symlink \"${LIBOMP_LIB_FILE}\"
 \"${alias}${LIBOMP_LIBRARY_SUFFIX}\" WORKING_DIRECTORY
-\"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${OPENMP_INSTALL_LIBDIR}\")")
+\"\$ENV{DESTDIR}\${outdir}\")")
 endforeach()
   endif()
 endif()
Index: openmp/CMakeLists.txt
===
--- openmp/CMakeLists.txt
+++ openmp/CMakeLists.txt
@@ -1,7 +1,12 @@
 cmake_minimum_required(VERSION 3.13.4)
 
-# Add cmake directory to search for custom cmake functions.
-set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
+set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+
+# Add path for custom modules
+list(INSERT CMAKE_MODULE_PATH 0
+  "${CMAKE_CURRENT_SOURCE_DIR}/cmake"
+  "${LLVM_COMMON_CMAKE_UTILS}/Modules"
+  )
 
 # llvm/runtimes/ will set OPENMP_STANDALONE_BUILD.
 if (OPENMP_STANDALONE_BUILD OR "${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}")
Index: llvm/cmake/modules/CMakeLists.txt
===
--- llvm/cmake/modules/CMakeLists.txt
+++ llvm/cmake/modules/CMakeLists.txt
@@ -137,6 +137,7 @@
 
 set(LLVM_CONFIG_BINARY_DIR "\${LLVM_INSTALL_PREFIX}")
 extend_path(LLVM_CONFIG_CMAKE_DIR "\${LLVM_INSTALL_PREFIX}" "${LLVM_INSTALL_PACKAGE_DIR}")
+extend_path(LLVM_CONFIG_TOOLS_BINARY_DIR "\${LLVM_INSTALL_PREFIX}" "${LLVM_TOOLS_INSTALL_DIR}")
 
 # Generate a default location for lit
 if (LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS)
Index: llvm-libgcc/lib/CMakeLists.txt
===
--- llvm-libgcc/lib/CMakeLists.txt
+++ llvm-libgcc/lib/CMakeLists.txt
@@ -1,5 +1,6 @@
 include(CheckLibraryExists)
 include(GNUInstallDirs)
+include(ExtendPath)
 
 string(REPLACE "-Wl,-z,defs" "" CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}")
 
@@ -41,13 +42,13 @@
   c
 )
 
-get_filename_component(LLVM_LIBGCC_LIBUNWIND_STATIC_ROOT "${CMAKE_INSTALL_PREFIX}/${LIBUNWIND_INSTALL_LIBRARY_DIR}" ABSOLUTE)
+extend_path(LLVM_LIBGCC_LIBUNWIND_STATIC_ROOT "${CMAKE_INSTALL_PREFIX}" "${LIBUNWIND_INSTALL_LIBRARY_DIR}")
 #string(REPLACE "${CMAKE_INSTALL_FULL_LIBDIR}/" "" LLVM_LIBGCC_LIBUNWIND_STATIC_ROOT "${LLVM_LIBGCC_LIBUNWIND_STATIC_ROOT}")
 
 install

[PATCH] D130574: ClangLinkerWrapper: explicitly #include

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: efriedma, lattner.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This code relied on implicitly having std::atomic available via the
ManagedStatic.h header.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130574

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -51,6 +51,7 @@
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetMachine.h"
+#include 
 
 using namespace llvm;
 using namespace llvm::opt;


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -51,6 +51,7 @@
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetMachine.h"
+#include 
 
 using namespace llvm;
 using namespace llvm::opt;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130575: clang: include ManagedStatic.h for llvm_shutdown

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: efriedma, lattner.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The code relied on ManagedStatic.h being included indirectly. This is
about to change as uses of ManagedStatic are removed throughout the
codebase.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130575

Files:
  clang/unittests/Interpreter/InterpreterTest.cpp
  clang/utils/TableGen/TableGen.cpp


Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -13,6 +13,7 @@
 #include "TableGenBackends.h" // Declares all backends.
 #include "ASTTableGen.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/TableGen/Error.h"
Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -20,6 +20,7 @@
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Sema.h"
 
+#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/TargetSelect.h"
 
 #include "gmock/gmock.h"


Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -13,6 +13,7 @@
 #include "TableGenBackends.h" // Declares all backends.
 #include "ASTTableGen.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/TableGen/Error.h"
Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -20,6 +20,7 @@
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Sema.h"
 
+#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/TargetSelect.h"
 
 #include "gmock/gmock.h"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128955: [WPD] Use new llvm.public.type.test intrinsic for potentially publicly visible classes

2022-07-26 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

thanks for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128955

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


[PATCH] D130576: ManagedStatic: remove from ASTMatchersInternal.h

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: efriedma, lattner.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130576

Files:
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp


Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -28,7 +28,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -59,7 +59,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/iterator.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Regex.h"
 #include 
 #include 
@@ -1931,8 +1930,8 @@
 
 public:
   static const Matcher &getInstance() {
-static llvm::ManagedStatic Instance;
-return Instance->M;
+static Wrapper Instance;
+return Instance.M;
   }
 };
 


Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -28,7 +28,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -59,7 +59,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/iterator.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Regex.h"
 #include 
 #include 
@@ -1931,8 +1930,8 @@
 
 public:
   static const Matcher &getInstance() {
-static llvm::ManagedStatic Instance;
-return Instance->M;
+static Wrapper Instance;
+return Instance.M;
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129118: CommandLine: add and use cl::SubCommand::get{All,TopLevel}

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle updated this revision to Diff 447694.
nhaehnle added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129118

Files:
  bolt/lib/Utils/CommandLineOpts.cpp
  bolt/tools/driver/llvm-bolt.cpp
  clang/lib/Tooling/CommonOptionsParser.cpp
  clang/tools/clang-refactor/ClangRefactor.cpp
  llvm/include/llvm/Support/CommandLine.h
  llvm/lib/Support/CommandLine.cpp
  llvm/tools/llvm-xray/llvm-xray.cpp
  llvm/unittests/Support/CommandLineInit/CommandLineInitTest.cpp
  llvm/unittests/Support/CommandLineTest.cpp

Index: llvm/unittests/Support/CommandLineTest.cpp
===
--- llvm/unittests/Support/CommandLineTest.cpp
+++ llvm/unittests/Support/CommandLineTest.cpp
@@ -99,7 +99,7 @@
   static const char ValueString[] = "Integer";
 
   StringMap &Map =
-  cl::getRegisteredOptions(*cl::TopLevelSubCommand);
+  cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
 
   ASSERT_EQ(Map.count("test-option"), 1u) << "Could not find option in map.";
 
@@ -420,7 +420,7 @@
   << "Hid extra option that should be visable.";
 
   StringMap &Map =
-  cl::getRegisteredOptions(*cl::TopLevelSubCommand);
+  cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
   ASSERT_TRUE(Map.count("help") == (size_t)0 ||
   cl::NotHidden == Map["help"]->getOptionHiddenFlag())
   << "Hid default option that should be visable.";
@@ -446,7 +446,7 @@
   << "Hid extra option that should be visable.";
 
   StringMap &Map =
-  cl::getRegisteredOptions(*cl::TopLevelSubCommand);
+  cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
   ASSERT_TRUE(Map.count("help") == (size_t)0 ||
   cl::NotHidden == Map["help"]->getOptionHiddenFlag())
   << "Hid default option that should be visable.";
@@ -529,7 +529,7 @@
   cl::ResetCommandLineParser();
 
   StackSubCommand SC1("sc1", "First subcommand");
-  StackOption AllOpt("everywhere", cl::sub(*cl::AllSubCommands),
+  StackOption AllOpt("everywhere", cl::sub(cl::SubCommand::getAll()),
cl::init(false));
   StackSubCommand SC2("sc2", "Second subcommand");
 
@@ -566,8 +566,8 @@
 TEST(CommandLineTest, ReparseCommandLineOptions) {
   cl::ResetCommandLineParser();
 
-  StackOption TopLevelOpt("top-level", cl::sub(*cl::TopLevelSubCommand),
-cl::init(false));
+  StackOption TopLevelOpt(
+  "top-level", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false));
 
   const char *args[] = {"prog", "-top-level"};
 
@@ -614,10 +614,12 @@
 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
   cl::ResetCommandLineParser();
 
-  StackOption TopLevelRemove(
-  "top-level-remove", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
-  StackOption TopLevelKeep(
-  "top-level-keep", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
+  StackOption TopLevelRemove("top-level-remove",
+   cl::sub(cl::SubCommand::getTopLevel()),
+   cl::init(false));
+  StackOption TopLevelKeep("top-level-keep",
+ cl::sub(cl::SubCommand::getTopLevel()),
+ cl::init(false));
 
   const char *args[] = {"prog", "-top-level-remove"};
 
@@ -638,9 +640,9 @@
 
   StackSubCommand SC1("sc1", "First Subcommand");
   StackSubCommand SC2("sc2", "Second Subcommand");
-  StackOption RemoveOption("remove-option", cl::sub(*cl::AllSubCommands),
- cl::init(false));
-  StackOption KeepOption("keep-option", cl::sub(*cl::AllSubCommands),
+  StackOption RemoveOption(
+  "remove-option", cl::sub(cl::SubCommand::getAll()), cl::init(false));
+  StackOption KeepOption("keep-option", cl::sub(cl::SubCommand::getAll()),
cl::init(false));
 
   const char *args0[] = {"prog", "-remove-option"};
@@ -719,13 +721,13 @@
 TEST(CommandLineTest, DefaultOptions) {
   cl::ResetCommandLineParser();
 
-  StackOption Bar("bar", cl::sub(*cl::AllSubCommands),
+  StackOption Bar("bar", cl::sub(cl::SubCommand::getAll()),
cl::DefaultOption);
   StackOption Bar_Alias(
   "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
 
-  StackOption Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands),
-cl::DefaultOption);
+  StackOption Foo("foo", cl::init(false),
+cl::sub(cl::SubCommand::getAll()), cl::DefaultOption);
   StackOption Foo_Alias("f", cl::desc("Alias for -foo"),
  cl::aliasopt(Foo), cl::DefaultOption);
 
@@ -1062,7 +1064,7 @@
 
   cl::ResetAllOptionOccurrences();
 
-  for (auto &OM : cl::getRegisteredOptions(*cl::TopLevelSubCommand)) {
+  for (auto &OM : cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) {
 cl::Option *O = OM.second;
 if (O->A

[PATCH] D130577: clang-driver: use llvm_fast_shutdown

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: efriedma, lattner, mehdi_amini.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Avoid running almost all global destructors in the common case.

Use C->isForDiagnostics() for the decision of whether to do this, which
is the same condition as used elsewhere for triggering "-disable-free".


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130577

Files:
  clang/tools/driver/driver.cpp


Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -34,6 +34,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FastShutdown.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/InitLLVM.h"
@@ -327,16 +328,17 @@
   return 1;
 }
 
-int clang_main(int Argc, char **Argv) {
-  noteBottomOfStack();
-  llvm::InitLLVM X(Argc, Argv);
-  llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
-" and include the crash backtrace, preprocessed "
-"source, and associated run script.\n");
+// Return (FastShutdown, RetCode).
+//
+// Fast shutdown is implemented in the caller. We want the locals of this
+// function to be cleaned up even when fast shutdown is used, as at least the
+// driver's destructor must run to properly flush and close output streams (at
+// least the compilation database stream).
+static std::pair ExecuteClang(int Argc, char **Argv) {
   SmallVector Args(Argv, Argv + Argc);
 
   if (llvm::sys::Process::FixupStandardFileDescriptors())
-return 1;
+return {false, 1};
 
   llvm::InitializeAllTargets();
 
@@ -385,7 +387,7 @@
   auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
   Args.resize(newEnd - Args.begin());
 }
-return ExecuteCC1Tool(Args);
+return {false, ExecuteCC1Tool(Args)};
   }
 
   // Handle options that need handling before the real command line parsing in
@@ -494,7 +496,7 @@
 if (!Level) {
   llvm::errs() << "Unknown value for " << A->getSpelling() << ": '"
<< A->getValue() << "'\n";
-  return 1;
+  return {false, 1};
 }
 ReproLevel = *Level;
   }
@@ -572,5 +574,25 @@
 
   // If we have multiple failing commands, we return the result of the first
   // failing command.
+  bool FastShutdown = !C->isForDiagnostics();
+  return {FastShutdown, Res};
+}
+
+int clang_main(int Argc, char **Argv) {
+  noteBottomOfStack();
+  llvm::InitLLVM X(Argc, Argv);
+  llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
+" and include the crash backtrace, preprocessed "
+"source, and associated run script.\n");
+
+  bool FastShutdown;
+  int Res;
+  std::tie(FastShutdown, Res) = ExecuteClang(Argc, Argv);
+
+  if (FastShutdown) {
+llvm::llvm_fast_shutdown();
+llvm::sys::Process::Exit(Res, /*NoCleanup=*/true);
+  }
+
   return Res;
 }


Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -34,6 +34,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FastShutdown.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/InitLLVM.h"
@@ -327,16 +328,17 @@
   return 1;
 }
 
-int clang_main(int Argc, char **Argv) {
-  noteBottomOfStack();
-  llvm::InitLLVM X(Argc, Argv);
-  llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
-" and include the crash backtrace, preprocessed "
-"source, and associated run script.\n");
+// Return (FastShutdown, RetCode).
+//
+// Fast shutdown is implemented in the caller. We want the locals of this
+// function to be cleaned up even when fast shutdown is used, as at least the
+// driver's destructor must run to properly flush and close output streams (at
+// least the compilation database stream).
+static std::pair ExecuteClang(int Argc, char **Argv) {
   SmallVector Args(Argv, Argv + Argc);
 
   if (llvm::sys::Process::FixupStandardFileDescriptors())
-return 1;
+return {false, 1};
 
   llvm::InitializeAllTargets();
 
@@ -385,7 +387,7 @@
   auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
   Args.resize(newEnd - Args.begin());
 }
-return ExecuteCC1Tool(Args);
+return {false, ExecuteCC1Tool(Args)};
   }
 
   // Handle options that need handling before the real command line parsing in
@@ -494,7 +496,7 @@
 if (!Level) {
   llvm::errs() << "Unknown value for " << A->getSpelling()

[PATCH] D130569: [Driver] Use libatomic for 32-bit SPARC atomics support on Linux [clang-linux-sparc-libatomic.patch, submitted 2022-07-26]

2022-07-26 Thread John Paul Adrian Glaubitz via Phabricator via cfe-commits
glaubitz accepted this revision.
glaubitz added a comment.
This revision is now accepted and ready to land.

This should address the current CI issues on sparc64 together with D130571 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130569

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


[PATCH] D130578: ManagedStatic: remove a use from Clang

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: efriedma, lattner.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130578

Files:
  clang/lib/Frontend/PrecompiledPreamble.cpp


Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -817,10 +817,9 @@
 }
 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
 
-static llvm::ManagedStatic 
BuildPreambleErrCategory;
-
 std::error_code clang::make_error_code(BuildPreambleError Error) {
-  return std::error_code(static_cast(Error), *BuildPreambleErrCategory);
+  static BuildPreambleErrorCategory BuildPreambleErrCategory;
+  return std::error_code(static_cast(Error), BuildPreambleErrCategory);
 }
 
 const char *BuildPreambleErrorCategory::name() const noexcept {


Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -817,10 +817,9 @@
 }
 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
 
-static llvm::ManagedStatic BuildPreambleErrCategory;
-
 std::error_code clang::make_error_code(BuildPreambleError Error) {
-  return std::error_code(static_cast(Error), *BuildPreambleErrCategory);
+  static BuildPreambleErrorCategory BuildPreambleErrCategory;
+  return std::error_code(static_cast(Error), BuildPreambleErrCategory);
 }
 
 const char *BuildPreambleErrorCategory::name() const noexcept {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129131: Remove uses of llvm_shutdown

2022-07-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle updated this revision to Diff 447708.
nhaehnle added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129131

Files:
  bolt/tools/driver/llvm-bolt.cpp
  bolt/tools/merge-fdata/merge-fdata.cpp
  clang/include/clang/Frontend/CompilerInstance.h
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
  clang/unittests/Interpreter/InterpreterTest.cpp
  clang/utils/TableGen/TableGen.cpp
  libclc/utils/prepare-builtins.cpp
  lldb/tools/driver/Driver.cpp
  lldb/tools/lldb-test/lldb-test.cpp
  lldb/unittests/Utility/LogTest.cpp
  lldb/utils/TableGen/LLDBTableGen.cpp
  llvm/examples/BrainF/BrainFDriver.cpp
  llvm/examples/HowToUseJIT/HowToUseJIT.cpp
  llvm/include/llvm/PassRegistry.h
  llvm/include/llvm/Support/DynamicLibrary.h
  llvm/include/llvm/Support/InitLLVM.h
  llvm/lib/IR/Pass.cpp
  llvm/lib/Support/InitLLVM.cpp
  llvm/lib/Support/Unix/DynamicLibrary.inc
  llvm/lib/Support/Unix/Signals.inc
  llvm/lib/Support/Windows/DynamicLibrary.inc
  llvm/tools/gold/gold-plugin.cpp
  llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp
  llvm/unittests/ExecutionEngine/ExecutionEngineTest.cpp
  llvm/unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
  llvm/utils/KillTheDoctor/KillTheDoctor.cpp
  mlir/tools/mlir-vulkan-runner/mlir-vulkan-runner.cpp
  polly/lib/External/isl/interface/extract_interface.cc

Index: polly/lib/External/isl/interface/extract_interface.cc
===
--- polly/lib/External/isl/interface/extract_interface.cc
+++ polly/lib/External/isl/interface/extract_interface.cc
@@ -48,7 +48,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -587,7 +586,6 @@
 
 	delete sema;
 	delete Clang;
-	llvm::llvm_shutdown();
 
 	if (Diags.hasErrorOccurred())
 		return EXIT_FAILURE;
Index: mlir/tools/mlir-vulkan-runner/mlir-vulkan-runner.cpp
===
--- mlir/tools/mlir-vulkan-runner/mlir-vulkan-runner.cpp
+++ mlir/tools/mlir-vulkan-runner/mlir-vulkan-runner.cpp
@@ -62,7 +62,6 @@
 }
 
 int main(int argc, char **argv) {
-  llvm::llvm_shutdown_obj x;
   registerPassManagerCLOptions();
 
   llvm::InitLLVM y(argc, argv);
Index: llvm/utils/KillTheDoctor/KillTheDoctor.cpp
===
--- llvm/utils/KillTheDoctor/KillTheDoctor.cpp
+++ llvm/utils/KillTheDoctor/KillTheDoctor.cpp
@@ -36,7 +36,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Signals.h"
@@ -297,7 +296,6 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal(argv[0]);
   PrettyStackTraceProgram X(argc, argv);
-  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
 
   ToolName = argv[0];
 
Index: llvm/unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
===
--- llvm/unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
+++ llvm/unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
@@ -9,7 +9,6 @@
 #include "llvm/Support/DynamicLibrary.h"
 #include "llvm/Config/config.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Path.h"
 #include "gtest/gtest.h"
 
@@ -59,7 +58,6 @@
 TEST(DynamicLibrary, Overload) {
   {
 std::string Err;
-llvm_shutdown_obj Shutdown;
 DynamicLibrary DL =
 DynamicLibrary::getPermanentLibrary(LibPath().c_str(), &Err);
 EXPECT_TRUE(DL.isValid());
@@ -109,9 +107,6 @@
   }
   EXPECT_TRUE(FuncPtr(DynamicLibrary::SearchForAddressOfSymbol(
   "TestA")) == nullptr);
-
-  // Check serach ordering is reset to default after call to llvm_shutdown
-  EXPECT_EQ(DynamicLibrary::SearchOrder, DynamicLibrary::SO_Linker);
 }
 
 TEST(DynamicLibrary, Shutdown) {
@@ -119,7 +114,6 @@
   std::vector Order;
   {
 std::string Err;
-llvm_shutdown_obj Shutdown;
 DynamicLibrary DL =
 DynamicLibrary::getPermanentLibrary(LibPath(A).c_str(), &Err);
 EXPECT_TRUE(DL.isValid());
Index: llvm/unittests/ExecutionEngine/ExecutionEngineTest.cpp
===
--- llvm/unittests/ExecutionEngine/ExecutionEngineTest.cpp
+++ llvm/unittests/ExecutionEngine/ExecutionEngineTest.cpp
@@ -14,7 +14,6 @@
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/DynamicLibrary.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "gtest/gtest.h"
 
 using namespace llvm;
@@ -22,9 +21,6 @@
 namespace {
 
 class ExecutionEngineTest : public testing::Test {
-private:
-  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
-
 protected:
   ExecutionEn

  1   2   3   >