[PATCH] D131479: Handle explicitly defaulted consteval special members.

2022-08-10 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 451731.
usaxena95 marked 3 inline comments as done.
usaxena95 added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131479

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp

Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -766,3 +766,102 @@
   static_assert(c == 8);
 }
 }
+
+namespace defaulted_special_member_template {
+template 
+struct default_ctor {
+  T data;
+  consteval default_ctor() = default; // expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+};
+
+template 
+struct copy {
+  T data;
+
+  consteval copy(const copy &) = default;// expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+  consteval copy =(const copy &) = default; // expected-note {{non-constexpr function 'operator=' cannot be used in a constant expression}}
+  copy() = default;
+};
+
+template 
+struct move {
+  T data;
+
+  consteval move(move &&) = default;// expected-note {{non-constexpr constructor 'foo' cannot be used in a constant expression}}
+  consteval move =(move &&) = default; // expected-note {{non-constexpr function 'operator=' cannot be used in a constant expression}}
+  move() = default;
+};
+
+struct foo {
+  foo() {}// expected-note {{declared here}}
+  foo(const foo &) {} // expected-note {{declared here}}
+  foo(foo &&) {}  // expected-note {{declared here}}
+
+  foo& operator=(const foo &) { return *this; } // expected-note {{declared here}}
+  foo& operator=(foo &&) { return *this; }  // expected-note {{declared here}}
+};
+
+void func() {
+  default_ctor fail0; // expected-error-re {{call to consteval function '{{.*::default_ctor<.*::foo>}}::default_ctor' is not a constant expression}} \
+  expected-note {{in call to 'default_ctor()'}}
+
+  copy good0;
+  copy fail1{good0}; // expected-error-re {{call to consteval function '{{.*::copy<.*::foo>}}::copy' is not a constant expression}} \
+ expected-note {{in call to 'copy(good0)'}}
+  fail1 = good0;  // expected-error-re {{call to consteval function '{{.*::copy<.*::foo>}}::operator=' is not a constant expression}} \
+ expected-note {{in call to '>operator=(good0)'}}
+
+  move good1;
+  move fail2{static_cast&&>(good1)}; // expected-error-re {{call to consteval function '{{.*::move<.*::foo>}}::move' is not a constant expression}} \
+   expected-note {{in call to 'move(good1)'}}
+  fail2 = static_cast&&>(good1);  // expected-error-re {{call to consteval function '{{.*::move<.*::foo>}}::operator=' is not a constant expression}} \
+   expected-note {{in call to '>operator=(good1)'}}
+}
+} // namespace defaulted_special_member_template
+
+namespace multiple_default_constructors {
+struct Foo {
+  Foo() {} // expected-note {{declared here}}
+};
+struct Bar {
+  Bar() = default;
+};
+struct Baz {
+  consteval Baz() {}
+};
+
+template 
+struct S {
+  T data;
+  S() requires (N==1) = default;
+  // This cannot be used in constexpr context.
+  S() requires (N==2) {}  // expected-note {{declared here}}
+  consteval S() requires (N==3) = default;  // expected-note {{non-constexpr constructor 'Foo' cannot be used in a constant expression}}
+};
+
+void func() {
+  // Explictly defaulted constructor.
+  S s1;
+  S s2;
+  // User provided constructor.
+  S s3;
+  S s4;
+  // Consteval explictly defaulted constructor.
+  S s5; // expected-error-re {{call to consteval function '{{.*}}::S<{{.*}}::Foo, 3>::S' is not a constant expression}} \
+   expected-note {{in call to 'S()'}}
+  S s6;
+  S s7;
+}
+
+consteval int aConstevalFunction() { // expected-error {{consteval function never produces a constant expression}}
+  // Defaulted default constructors are implicitly consteval.
+  S s1;
+
+  S s4; // expected-note {{non-constexpr constructor 'S' cannot be used in a constant expression}}
+
+  S s2;
+  S s3;
+  return 0;
+}
+
+} // namespace multiple_default_constructors
Index: clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
===
--- clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
+++ clang/test/SemaCXX/cxx0x-defaulted-functions.cpp
@@ -44,18 +44,20 @@
 }
 
 template struct S : T {
-  constexpr S() = default;
-  constexpr S(const S&) = default;
-  constexpr S(S&&) = default;
+  constexpr S() = default; // expected-note {{previous declaration is here}}
+  constexpr S(const S&) = default; 

[PATCH] D131351: [C] Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Nit: I think it is useful mentioning `-Wincompatible-function-pointer-types` in 
the commit message, not just in `clang/docs/ReleaseNotes.rst`, so that `git log 
--grep incompatible-function-pointer-types` will reveal something when the user 
knows incompatible-function-pointer-types but not "implicit function pointer 
conversions diagnostic".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131351

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


[PATCH] D131351: [C] Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Brooks Moses via Phabricator via cfe-commits
brooksmoses added a comment.

For the record, so far we've seen this showing up in the following:

- A case in a notoriously warning-heavy third-party library where we'd 
backported a file from a newer version and didn't quite fix all the internal 
API mismatches.
- A ten-year-old bug in a local patch to another third-party library, where a 
function-pointer parameter was defined as returning a `void` and then assigned 
to a function-pointer that returns a `void *`.
- A probably-innocuous bug in a local patch to yet another third-party library, 
where we were passing an `int foo(char *, char *)` function to GLIBC's `qsort`, 
which expects a function with a signature of `int foo(void *, void *)`.
- A case where 
https://gitlab.freedesktop.org/pixman/pixman/-/commit/e0d4403e78a7af8f4be4110ae25e9c3d1ac93a78
 wasn't applied to our local version.  This is also probably an innocuous case, 
not a "real" bug.
- A case where SciPy's extension has a function that uses `void *` for a `FILE 
*` pointer 
(https://github.com/scipy/scipy/blob/main/scipy/spatial/_qhull.pyx#L187, second 
argument) while the corresponding C code's function has a real `FILE *` pointer 
(https://github.com/qhull/qhull/blob/master/src/libqhull_r/io_r.h#L97).  The 
SciPy function also uses a `void *` for an argument of a struct type, which 
seems rather odd to me given that it just defined the type two lines earlier.

So, real bugs in 40% of cases, I'd say.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131351

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


[PATCH] D131644: [clang][dataflow] Don't skip the entry block

2022-08-10 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 451721.
li.zhe.hua added a comment.

Fix commit message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131644

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


Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -342,11 +342,8 @@
   std::vector> BlockStates(
   CFCtx.getCFG().size(), llvm::None);
 
-  // The entry basic block doesn't contain statements so it can be skipped.
   const CFGBlock  = CFCtx.getCFG().getEntry();
-  BlockStates[Entry.getBlockID()] = {Analysis.typeErasedInitialElement(),
- InitEnv};
-  Worklist.enqueueSuccessors();
+  Worklist.enqueueBlock();
 
   // Bugs in lattices and transfer functions can prevent the analysis from
   // converging. To limit the damage (infinite loops) that these bugs can 
cause,


Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -342,11 +342,8 @@
   std::vector> BlockStates(
   CFCtx.getCFG().size(), llvm::None);
 
-  // The entry basic block doesn't contain statements so it can be skipped.
   const CFGBlock  = CFCtx.getCFG().getEntry();
-  BlockStates[Entry.getBlockID()] = {Analysis.typeErasedInitialElement(),
- InitEnv};
-  Worklist.enqueueSuccessors();
+  Worklist.enqueueBlock();
 
   // Bugs in lattices and transfer functions can prevent the analysis from
   // converging. To limit the damage (infinite loops) that these bugs can cause,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131646: [clang][dataflow] Restructure loops to call widen on back edges

2022-08-10 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When navigating a loop block, we call the lattice's widen operator,
which gives a lattice of infinite height the opportunity to reach
convergence.

As we enter the loop, we store the block state in the back edge block,
which represents the state after the zeroth iteration. Then, after
each loop iteration, we widen the previous iteration's state with the
new iteration's state.

Tracking bug: #56931

Depends on D131645 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131646

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.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
@@ -43,12 +43,15 @@
 using namespace test;
 using namespace ast_matchers;
 using ::testing::_;
+using ::testing::AllOf;
+using ::testing::Each;
 using ::testing::ElementsAre;
 using ::testing::IsEmpty;
-using ::testing::IsNull;
 using ::testing::NotNull;
+using ::testing::Optional;
 using ::testing::Pair;
 using ::testing::Ref;
+using ::testing::SizeIs;
 using ::testing::Test;
 using ::testing::UnorderedElementsAre;
 
@@ -222,6 +225,58 @@
 "maximum number of iterations reached");
 }
 
+struct ConvergesOnWidenLattice {
+  int State = 0;
+  bool Top = false;
+
+  bool operator==(const ConvergesOnWidenLattice ) const {
+if (Top)
+  return Other.Top;
+return State == Other.State;
+  }
+
+  LatticeJoinEffect join(const ConvergesOnWidenLattice ) {
+auto Prev = *this;
+Top = Top || Other.Top;
+State += Other.State;
+return Prev == *this ? LatticeJoinEffect::Unchanged
+ : LatticeJoinEffect::Changed;
+  }
+
+  void widen(const ConvergesOnWidenLattice ) { Top = true; }
+
+  friend std::ostream <<(std::ostream ,
+  const ConvergesOnWidenLattice ) {
+return OS << "{" << L.State << "," << (L.Top ? "true" : "false") << "}";
+  }
+};
+
+class ConvergesOnWidenAnalysis
+: public DataflowAnalysis {
+public:
+  explicit ConvergesOnWidenAnalysis(ASTContext )
+  : DataflowAnalysis(Context,
+ /*ApplyBuiltinTransfer=*/false) {}
+
+  static ConvergesOnWidenLattice initialElement() { return {}; }
+
+  void transfer(const Stmt *S, ConvergesOnWidenLattice , Environment ) {
+++E.State;
+  }
+};
+
+TEST(DataflowAnalysisTest, ConvergesOnWidenAnalysis) {
+  std::string Code = R"(
+void target() {
+  while(true) {}
+}
+  )";
+  auto BlockStates = llvm::cantFail(runAnalysis(
+  Code, [](ASTContext ) { return ConvergesOnWidenAnalysis(C); }));
+  EXPECT_THAT(BlockStates, AllOf(SizeIs(4), Each(Optional(_;
+}
+
 struct FunctionCallLattice {
   llvm::SmallSet CalledFunctions;
 
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -154,6 +154,35 @@
   TransferOptions TransferOpts;
 };
 
+// Returns whether `Block` is a "back edge" in the CFG. Such a block is empty
+// and has only one successor, the start of the loop.
+static bool isBackEdge(const CFGBlock *Block) {
+  assert(Block != nullptr);
+  return Block->LoopTarget != nullptr;
+}
+
+// Returns the predecessor to `Block` that is a "back edge", if one exists.
+//
+// If this function returns a non-null pointer, that means `Block` dominates the
+// back edge block. (That is, all paths from the entry block to the back edge
+// block must go through `Block`.) It also means that there are only two
+// predecessors; the other is along the path from the entry block to `Block`.
+static const CFGBlock *findBackEdge(const CFGBlock *Block) {
+  assert(Block != nullptr);
+
+  const CFGBlock *BackEdge = nullptr;
+  for (const auto  : Block->preds()) {
+if (!Pred.isReachable())
+  continue;
+if (isBackEdge(Pred)) {
+  assert(BackEdge == nullptr);
+  assert(Block->pred_size() == 2);
+  BackEdge = Pred;
+}
+  }
+  return BackEdge;
+}
+
 /// Computes the input state for a given basic block by joining the output
 /// states of its predecessors.
 ///
@@ -199,6 +228,21 @@
 }
   }
 
+  // If we are at the start of a loop, we will have two precessors, but we don't
+  // want to join these two predecessors. Instead, we want to take the back edge
+  // block (i.e. the result of the 

[PATCH] D131645: [clang][dataflow] Allow user-provided lattices to provide a widen operator

2022-08-10 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In order to better support convergence in a sound way, we allow users
to provide a widen operator for their lattice type. This can be
implemented for lattices of infinite (or sufficiently large) height in
order to reach convergence in loops.

If not provided, this defaults to the existing `join` operation that
is required to be defined. This is a sound default, as `join` would be
at least more precise than a theoretical `widen`.

Tracking bug: #56931

Depends on D131644 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131645

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  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
@@ -48,6 +48,7 @@
 using ::testing::IsNull;
 using ::testing::NotNull;
 using ::testing::Pair;
+using ::testing::Ref;
 using ::testing::Test;
 using ::testing::UnorderedElementsAre;
 
@@ -86,6 +87,99 @@
   EXPECT_TRUE(BlockStates[1].has_value());
 }
 
+struct HasWidenLattice {
+  HasWidenLattice() {
+ON_CALL(*this, join).WillByDefault([](const HasWidenLattice &) {
+  return LatticeJoinEffect::Unchanged;
+});
+  }
+  // Mock objects are not copyable by default. Since this is a monostate,
+  // delegate to the default ctor.
+  HasWidenLattice(const HasWidenLattice &) : HasWidenLattice() {}
+  HasWidenLattice =(const HasWidenLattice &) { return *this; }
+
+  MOCK_METHOD(LatticeJoinEffect, join, (const HasWidenLattice &));
+  MOCK_METHOD(void, widen, (const HasWidenLattice &));
+
+  friend bool operator==(const HasWidenLattice &, const HasWidenLattice &) {
+return true;
+  }
+};
+
+class HasWidenAnalysis
+: public DataflowAnalysis {
+public:
+  static HasWidenLattice initialElement() { return {}; }
+  using DataflowAnalysis::DataflowAnalysis;
+  void transfer(const Stmt *, HasWidenLattice &, Environment &) {}
+};
+
+TEST(DataflowAnalysisTest, WidenPrefersWidenWhenProvided) {
+  std::unique_ptr AST =
+  tooling::buildASTFromCodeWithArgs("int x = 0;", {"-std=c++11"});
+  HasWidenAnalysis Analysis(AST->getASTContext(),
+/*ApplyBuiltinTransfer=*/false);
+
+  TypeErasedLattice A = {HasWidenLattice()};
+  TypeErasedLattice B = {HasWidenLattice()};
+  HasWidenLattice  = *llvm::any_cast();
+  HasWidenLattice  = *llvm::any_cast();
+
+  // Expect only `LA.widen(LB)` is called, and nothing else.
+  EXPECT_CALL(LA, widen).Times(0);
+  EXPECT_CALL(LB, widen).Times(0);
+  EXPECT_CALL(LA, join).Times(0);
+  EXPECT_CALL(LB, join).Times(0);
+  EXPECT_CALL(LA, widen(Ref(LB))).Times(1);
+
+  Analysis.widenTypeErased(A, B);
+}
+
+struct OnlyJoinLattice {
+  OnlyJoinLattice() {
+ON_CALL(*this, join).WillByDefault([](const OnlyJoinLattice &) {
+  return LatticeJoinEffect::Unchanged;
+});
+  }
+  // Mock objects are not copyable by default. Since this is a monostate,
+  // delegate to the default ctor.
+  OnlyJoinLattice(const OnlyJoinLattice &) : OnlyJoinLattice() {}
+  OnlyJoinLattice =(const OnlyJoinLattice &) { return *this; }
+
+  MOCK_METHOD(LatticeJoinEffect, join, (const OnlyJoinLattice &));
+
+  friend bool operator==(const OnlyJoinLattice &, const OnlyJoinLattice &) {
+return true;
+  }
+};
+
+class OnlyJoinAnalysis
+: public DataflowAnalysis {
+public:
+  static OnlyJoinLattice initialElement() { return {}; }
+  using DataflowAnalysis::DataflowAnalysis;
+  void transfer(const Stmt *, OnlyJoinLattice &, Environment &) {}
+};
+
+TEST(DataflowAnalysisTest, WidenFallsBackToJoin) {
+  std::unique_ptr AST =
+  tooling::buildASTFromCodeWithArgs("int x = 0;", {"-std=c++11"});
+  OnlyJoinAnalysis Analysis(AST->getASTContext(),
+/*ApplyBuiltinTransfer=*/false);
+
+  TypeErasedLattice A = {OnlyJoinLattice()};
+  TypeErasedLattice B = {OnlyJoinLattice()};
+  OnlyJoinLattice  = *llvm::any_cast();
+  OnlyJoinLattice  = *llvm::any_cast();
+
+  // Expect only `LA.join(LB)` is called, and nothing else.
+  EXPECT_CALL(LA, join).Times(0);
+  EXPECT_CALL(LB, join).Times(0);
+  EXPECT_CALL(LA, join(Ref(LB))).Times(1);
+
+  Analysis.widenTypeErased(A, B);
+}
+
 struct NonConvergingLattice {
   int State;
 
Index: clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
===
--- 

[PATCH] D131644: [clang][dataflow] Don't skip the entry block

2022-08-10 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In DXXX, we implement widen by taking the block state upon entry
into the loop and copying it to the block that represents the
back-edge in order to initialize the state for the "0th" iteration of
the loop. If the loop is the first thing after the entry block,
skipping the entry block means we don't have an opportunity to do this
initialization, so we want to analyze the entry block, even as it has
zero statements, to keep the logic consistent.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131644

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


Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -342,11 +342,8 @@
   std::vector> BlockStates(
   CFCtx.getCFG().size(), llvm::None);
 
-  // The entry basic block doesn't contain statements so it can be skipped.
   const CFGBlock  = CFCtx.getCFG().getEntry();
-  BlockStates[Entry.getBlockID()] = {Analysis.typeErasedInitialElement(),
- InitEnv};
-  Worklist.enqueueSuccessors();
+  Worklist.enqueueBlock();
 
   // Bugs in lattices and transfer functions can prevent the analysis from
   // converging. To limit the damage (infinite loops) that these bugs can 
cause,


Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -342,11 +342,8 @@
   std::vector> BlockStates(
   CFCtx.getCFG().size(), llvm::None);
 
-  // The entry basic block doesn't contain statements so it can be skipped.
   const CFGBlock  = CFCtx.getCFG().getEntry();
-  BlockStates[Entry.getBlockID()] = {Analysis.typeErasedInitialElement(),
- InitEnv};
-  Worklist.enqueueSuccessors();
+  Worklist.enqueueBlock();
 
   // Bugs in lattices and transfer functions can prevent the analysis from
   // converging. To limit the damage (infinite loops) that these bugs can cause,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103874: [IR] Rename the shufflevector's undef mask to poison

2022-08-10 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune added inline comments.



Comment at: clang/test/CodeGen/X86/avx-builtins.c:182
   // CHECK-LABEL: test_mm256_castsi128_si256
-  // CHECK: shufflevector <2 x i64> %{{.*}}, <2 x i64> %{{.*}}, <4 x i32> 
+  // CHECK: shufflevector <2 x i64> %{{.*}}, <2 x i64> %{{.*}}, <4 x i32> 
   return _mm256_castsi128_si256(A);

aqjune wrote:
> RKSimon wrote:
> > efriedma wrote:
> > > This change might be visible to user code.
> > Yes the length changing casts are worrying me as well - we could update the 
> > header to insert zero into the upper elements I suppose, in many cases 
> > these would be folded away by AVX ops implicitly zeroing the 128-bits. But 
> > we'd definitely have the potential for regressions.
> I quickly skimmed through the headers in clang/lib/Headers and listed the 
> functions calling `__builtin_shufflevector` with at least one -1 mask operand.
> It seems there aren't very many, which is good news; I found 17 functions 
> only ({F19257445}).
> 
> But, correctly fixing these headers seems to require a lot of work.
> Since using the zero vector can cause performance regressions, we need to use 
> a frozen poison (undef) vector to encode a vector having unspecified bits.
> A few months ago, I created D104790 to start using freeze(vector poison) for 
> `mm*_undefined*` intrinsics. However, teaching the existing codebase to 
> successfully deal with the frozen poison vector was a pretty tough job.
> When it comes to fixing the headers, there is even no C intrinsic function 
> that represents a frozen poison vector AFAIK.
> 
> I'll appreciate any idea or help in addressing this issue. :/
Okay, D130339 has finally been merged.

I will make a patch that updates the `mm256_castsi128_si256` and its family 
functions to emit shufflevector with freeze(poison) operand.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103874

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


[PATCH] D131448: Introduce iterator sentinel to make graph traversal implementation more efficient and cleaner

2022-08-10 Thread Chris Lattner via Phabricator via cfe-commits
lattner added a comment.

I haven't reviewed this in detail, but oh my I love LOVE LOVE this!  
`llvm::scc_traversal(x)` is so nice, great work!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131448

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


[PATCH] D131639: [OpenMP] Remove 'stdbool.h' from OpenMP header wrappers

2022-08-10 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

`bool` is used by a function declaration `__ockl_fdot2` in 
`clang/lib/Headers/__clang_hip_libdevice_declares.h`, which is included by 
`clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131639

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-08-10 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

Also not caught: a cast of 0 when 0 is not a valid value in the enum.


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

https://reviews.llvm.org/D130058

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-08-10 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

In D130058#3714672 , @glandium wrote:

> This catches 
> https://searchfox.org/mozilla-central/rev/c77834ec635c523f2ba0092fcd1728c9b1c3005b/third_party/rust/glslopt/glsl-optimizer/src/compiler/glsl/ir_reader.cpp#732
>  but not 
> https://searchfox.org/mozilla-central/rev/c77834ec635c523f2ba0092fcd1728c9b1c3005b/third_party/rust/glslopt/glsl-optimizer/src/compiler/glsl/ir.cpp#654.
>  Is that expected?

Maybe something changed? A couple days ago it was catching 
https://searchfox.org/mozilla-central/rev/c77834ec635c523f2ba0092fcd1728c9b1c3005b/gfx/cairo/cairo/src/win32/cairo-dwrite-font.cpp#238
 but apparently not anymore.


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

https://reviews.llvm.org/D130058

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


[PATCH] D131532: [Sema] Avoid isNullPointerConstant invocation

2022-08-10 Thread Richard Trieu via Phabricator via cfe-commits
rtrieu accepted this revision.
rtrieu added a comment.
This revision is now accepted and ready to land.

I think this is a reasonable step for improving compile times.  I put some 
suggestions for more descriptive names below (he said, after suggesting those 
names in the first place).

The description of this change should mention that expensive part is because 
`isNullPointerConstant` makes calls to a constant evaluator which we don't need.




Comment at: clang/lib/Sema/SemaChecking.cpp:13343
+  const Expr *NewE = E->IgnoreParenImpCasts();
+  bool GNUNull = isa(NewE);
+  bool NullPtr = NewE->getType()->isNullPtrType();

Let's call this `IsGNUNullExpr`



Comment at: clang/lib/Sema/SemaChecking.cpp:13344
+  bool GNUNull = isa(NewE);
+  bool NullPtr = NewE->getType()->isNullPtrType();
+  if (!GNUNull && !NullPtr) return;

And let's call this `HasNullPtrType`


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

https://reviews.llvm.org/D131532

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


[PATCH] D131134: [X86] Report error if the amx enabled on the non-64-bits target

2022-08-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

Yes AMX is only supported in 64-bit mode but I doubt CPUID checks which mode 
the program is running in.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131134

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


[PATCH] D131541: [Sema] Fix friend destructor declarations after D130936

2022-08-10 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11522
+  if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
+  !NewFD->isDependentContext()) {
+QualType ClassType = Destructor->getThisObjectType();

This condition appears to be true even when the friend itself is not dependent. 
The error message changes for:
```
struct C;
struct B { ~B(); };
template 
struct A {
  friend B::~C();
};
```

(causing the template and non-template cases to generate different messages).




Comment at: clang/test/SemaCXX/member-class-11.cpp:36-40
+// FIXME: We should diagnose here.
+template 
+struct E {
+  friend T::S::~V();
+};

Please replace this with the case where there is an instantiation. Also, the 
prior change to the release notes in https://reviews.llvm.org/D130936 should be 
adjusted to reflect the new scope of what is fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131541

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


[PATCH] D131134: [X86] Report error if the amx enabled on the non-64-bits target

2022-08-10 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

I have the same impression. I checked ISE 
 says AMX instructions are 
`N.E.` on 32-bit mode. And seems Linux Kernel only enables AMX on 64-bit too 
https://lwn.net/ml/linux-kernel/20210730145957.7927-22-chang.seok@intel.com/#t


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131134

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


[PATCH] D131541: [Sema] Fix friend destructor declarations after D130936

2022-08-10 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11518-11520
+  // FIXME: We still don't diagnose on this case
+  // template 
+  // struct A { friend T::S::~V(); };

There's nothing we can diagnose about this without an instantiation (because 
`S` could be an alias for a class having `V` as the injected-class-name).

It is, however, true that we don't diagnose this even with problematic 
instantiations:
```
struct R { struct V; ~R(); };
struct QQ { using S = R; };

template 
struct A { friend T::S::~V(); };

A a;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131541

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


[PATCH] D131134: [X86] Report error if the amx enabled on the non-64-bits target

2022-08-10 Thread LiuChen via Phabricator via cfe-commits
LiuChen3 added a comment.

In D131134#3707397 , @craig.topper 
wrote:

> What problem are we trying to solve here? CPUID reports AMX as supported even 
> in 32-bit mode. Why can't the user pass it to the compiler?

I thought AMX is only supported on 64-bit mode. It seems I was wrong.  So for 
now just reporting an error to intrinsics is enough. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131134

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


[PATCH] D131635: [RISCV] Remove sifive-7-rv32/rv64 CPU names.

2022-08-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper abandoned this revision.
craig.topper added a comment.

I'm going to rethink this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131635

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


[PATCH] D130108: git-clang-format: format index not worktree when using --staged

2022-08-10 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3f801e07fa82: [clang-format] git-clang-format --staged 
should format the index (authored by Gergely Meszaros 
meszaros.gergel...@gmail.com, committed by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130108

Files:
  clang/tools/clang-format/git-clang-format

Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -179,15 +179,17 @@
 
   if len(commits) > 1:
 old_tree = commits[1]
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- revision=commits[1],
- binary=opts.binary,
- style=opts.style)
+revision = old_tree
+  elif opts.staged:
+old_tree = create_tree_from_index(changed_lines)
+revision = ''
   else:
 old_tree = create_tree_from_workdir(changed_lines)
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- binary=opts.binary,
- style=opts.style)
+revision = None
+  new_tree = run_clang_format_and_save_to_tree(changed_lines,
+   revision,
+   binary=opts.binary,
+   style=opts.style)
   if opts.verbose >= 1:
 print('old tree: %s' % old_tree)
 print('new tree: %s' % new_tree)
@@ -394,11 +396,29 @@
   return create_tree(filenames, '--stdin')
 
 
+def create_tree_from_index(filenames):
+  # Copy the environment, because the files have to be read from the original
+  # index.
+  env = os.environ.copy()
+  def index_contents_generator():
+for filename in filenames:
+  git_ls_files_cmd = ['git', 'ls-files', '--stage', '-z', '--', filename]
+  git_ls_files = subprocess.Popen(git_ls_files_cmd, env=env,
+  stdin=subprocess.PIPE,
+  stdout=subprocess.PIPE)
+  stdout = git_ls_files.communicate()[0]
+  yield convert_string(stdout.split(b'\0')[0])
+  return create_tree(index_contents_generator(), '--index-info')
+
+
 def run_clang_format_and_save_to_tree(changed_lines, revision=None,
   binary='clang-format', style=None):
   """Run clang-format on each file and save the result to a git tree.
 
   Returns the object ID (SHA-1) of the created tree."""
+  # Copy the environment when formatting the files in the index, because the
+  # files have to be read from the original index.
+  env = os.environ.copy() if revision == '' else None
   def iteritems(container):
   try:
   return container.iteritems() # Python 2
@@ -406,11 +426,15 @@
   return container.items() # Python 3
   def index_info_generator():
 for filename, line_ranges in iteritems(changed_lines):
-  if revision:
-git_metadata_cmd = ['git', 'ls-tree',
-'%s:%s' % (revision, os.path.dirname(filename)),
-os.path.basename(filename)]
-git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
+  if revision is not None:
+if len(revision) > 0:
+  git_metadata_cmd = ['git', 'ls-tree',
+  '%s:%s' % (revision, os.path.dirname(filename)),
+  os.path.basename(filename)]
+else:
+  git_metadata_cmd = ['git', 'ls-files', '--stage', '--', filename]
+git_metadata = subprocess.Popen(git_metadata_cmd, env=env,
+stdin=subprocess.PIPE,
 stdout=subprocess.PIPE)
 stdout = git_metadata.communicate()[0]
 mode = oct(int(stdout.split()[0], 8))
@@ -422,7 +446,8 @@
   blob_id = clang_format_to_blob(filename, line_ranges,
  revision=revision,
  binary=binary,
- style=style)
+ style=style,
+ env=env)
   yield '%s %s\t%s' % (mode, blob_id, filename)
   return create_tree(index_info_generator(), '--index-info')
 
@@ -448,11 +473,12 @@
 
 
 def clang_format_to_blob(filename, line_ranges, revision=None,
- binary='clang-format', style=None):
+ binary='clang-format', style=None, env=None):
   """Run clang-format on the given file and save the result to a git blob.
 
   Runs on the file in `revision` if not None, or on the file in the working
-  directory if `revision` 

[clang] 3f801e0 - [clang-format] git-clang-format --staged should format the index

2022-08-10 Thread via cfe-commits

Author: Gergely Meszaros
Date: 2022-08-10T19:30:41-07:00
New Revision: 3f801e07fa82055de98278d3ebeaade68fbacee9

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

LOG: [clang-format] git-clang-format --staged should format the index

When --staged (or --cached) use the index for formatting as well, not just
for the line numbers to format. Without this change git-clang-format gets
the changed line numbers based on the index, but then formats these lines on
the working tree version of the file.

This is a problem when the working tree and index differ. One common case
would be (and is the motivation behind this patch) when applying the
suggested changes git-clang-format --staged, then forgetting to add the
applied changes. When git-clang-format --staged --diff is used in a
pre-commit hook in this scenario, then the hook would allow committing the
improperly formatted changes, as the file is correctly formatted in the work
tree.

Fixes #56797.

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

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 6a1172e0bf17b..7ce6b60a8e655 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -179,15 +179,17 @@ def main():
 
   if len(commits) > 1:
 old_tree = commits[1]
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- revision=commits[1],
- binary=opts.binary,
- style=opts.style)
+revision = old_tree
+  elif opts.staged:
+old_tree = create_tree_from_index(changed_lines)
+revision = ''
   else:
 old_tree = create_tree_from_workdir(changed_lines)
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- binary=opts.binary,
- style=opts.style)
+revision = None
+  new_tree = run_clang_format_and_save_to_tree(changed_lines,
+   revision,
+   binary=opts.binary,
+   style=opts.style)
   if opts.verbose >= 1:
 print('old tree: %s' % old_tree)
 print('new tree: %s' % new_tree)
@@ -394,11 +396,29 @@ def create_tree_from_workdir(filenames):
   return create_tree(filenames, '--stdin')
 
 
+def create_tree_from_index(filenames):
+  # Copy the environment, because the files have to be read from the original
+  # index.
+  env = os.environ.copy()
+  def index_contents_generator():
+for filename in filenames:
+  git_ls_files_cmd = ['git', 'ls-files', '--stage', '-z', '--', filename]
+  git_ls_files = subprocess.Popen(git_ls_files_cmd, env=env,
+  stdin=subprocess.PIPE,
+  stdout=subprocess.PIPE)
+  stdout = git_ls_files.communicate()[0]
+  yield convert_string(stdout.split(b'\0')[0])
+  return create_tree(index_contents_generator(), '--index-info')
+
+
 def run_clang_format_and_save_to_tree(changed_lines, revision=None,
   binary='clang-format', style=None):
   """Run clang-format on each file and save the result to a git tree.
 
   Returns the object ID (SHA-1) of the created tree."""
+  # Copy the environment when formatting the files in the index, because the
+  # files have to be read from the original index.
+  env = os.environ.copy() if revision == '' else None
   def iteritems(container):
   try:
   return container.iteritems() # Python 2
@@ -406,11 +426,15 @@ def run_clang_format_and_save_to_tree(changed_lines, 
revision=None,
   return container.items() # Python 3
   def index_info_generator():
 for filename, line_ranges in iteritems(changed_lines):
-  if revision:
-git_metadata_cmd = ['git', 'ls-tree',
-'%s:%s' % (revision, os.path.dirname(filename)),
-os.path.basename(filename)]
-git_metadata = subprocess.Popen(git_metadata_cmd, 
stdin=subprocess.PIPE,
+  if revision is not None:
+if len(revision) > 0:
+  git_metadata_cmd = ['git', 'ls-tree',
+  '%s:%s' % (revision, os.path.dirname(filename)),
+  os.path.basename(filename)]
+else:
+  git_metadata_cmd = ['git', 'ls-files', '--stage', '--', filename]
+git_metadata = subprocess.Popen(git_metadata_cmd, env=env,
+

[PATCH] D131203: [HLSL] Initial codegen for SV_GroupIndex

2022-08-10 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:19
 #include "clang/Basic/TargetOptions.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"

python3kgae wrote:
> Does this mean CGHLSLRuntime is only for DirectX backend?
No, it is fairly normal to include target intrinsics throughout codegen. That 
said, I'm not handling non-DirectX intrinsics nor am I verifying the 
appropriate target, so I should make some adjustment here.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:119
+  auto *EntryTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx), false);
+  Function *EntryFn =
+  Function::Create(EntryTy, Function::ExternalLinkage, FD->getName(), );

python3kgae wrote:
> Need to move all attributes from Fn to EntryFn.
> And make Fn a normal function.
Yes on the function attributes.

What do you mean by "normal function" as written it is an external linkage 
function, which matches what we expect in DXIL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131203

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


[PATCH] D131625: [HLSL] Entry functions require param annotation

2022-08-10 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11875
+  for (const auto Param : FD->parameters()) {
+if (!Param->hasAttr()) {
+  Diag(Param->getLocation(), diag::err_hlsl_missing_parameter_annotation) 
<< Param;

python3kgae wrote:
> When param type is struct, it is OK not to have HLSL semantic as long as all 
> fields in the struct have HLSL semantic.
My intent was to handle structs in a subsequent patch. Since we only have one 
semantic implemented right now we can't make a valid test for structs unless it 
is a single element struct which is not a robust test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131625

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


[PATCH] D125418: [Arm64EC 6/?] Implement C/C++ mangling for Arm64EC function definitions.

2022-08-10 Thread chenglin.bi via Phabricator via cfe-commits
bcl5980 added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5128
+// to the function itself; it points to a stub for the compiler.
+// FIXME: We also need to emit an entry thunk.
+SmallString<256> MangledName;

efriedma wrote:
> bcl5980 wrote:
> > efriedma wrote:
> > > bcl5980 wrote:
> > > > A headache thing here.
> > > > We need to get the function definition with triple x64 to define entry 
> > > > thunk. For now the function definition here is aarch64 version.
> > > > For example the case in Microsoft doc "Understanding Arm64EC ABI and 
> > > > assembly code":
> > > > 
> > > > ```
> > > > struct SC {
> > > > char a;
> > > > char b;
> > > > char c;
> > > > };
> > > > int fB(int a, double b, int i1, int i2, int i3);
> > > > int fC(int a, struct SC c, int i1, int i2, int i3);
> > > > int fA(int a, double b, struct SC c, int i1, int i2, int i3) {
> > > > return fB(a, b, i1, i2, i3) + fC(a, c, i1, i2, i3);
> > > > }
> > > > ```
> > > > 
> > > > x64 version IR for fA is:
> > > > ```
> > > > define dso_local i32 @fA(i32 noundef %a, double noundef %b, ptr 
> > > > nocapture noundef readonly %c, i32 noundef %i1, i32 noundef %i2, i32 
> > > > noundef %i3) local_unnamed_addr #0 { ... }
> > > > ```
> > > > aarch64 version IR for fA is:
> > > > 
> > > > ```
> > > > define dso_local i32 @"#fA"(i32 noundef %a, double noundef %b, i64 
> > > > %c.coerce, i32 noundef %i1, i32 noundef %i2, i32 noundef %i3) #0 {...}
> > > > ```
> > > > Arm64 will allow any size structure to be assigned to a register 
> > > > directly. x64 only allows sizes 1, 2, 4 and 8. 
> > > > Entry thunk follow x64 version function type. But we only have aarch64 
> > > > version function type.
> > > > 
> > > > I think the best way to do is create a x64 version codeGenModule and 
> > > > use the x64 CGM to generate the function type for entry thunk. But it 
> > > > is hard for me to do here. I tried a little but a lot of issues happen.
> > > > 
> > > > One other way is only modify `AArch64ABIInfo::classifyArgumentType`, 
> > > > copy the x64 code into the function and add a flag to determine which 
> > > > version will the function use. It is easier but I'm not sure it is the 
> > > > only difference between x64 and aarch64. Maybe the classify return also 
> > > > need to do this. And it is not a clean way I think.
> > > Oh, that's annoying... I hadn't considered the case of a struct of size 
> > > 3/5/6/7.
> > > 
> > > Like I noted on D126811, attaching thunks to calls is tricky if we try to 
> > > do it from clang.
> > > 
> > > Computing the right IR type shouldn't be that hard by itself; we can call 
> > > into call lowering code in TargetInfo without modifying much else.  (We 
> > > just need a bit to tell the TargetInfo to redirect the call, like 
> > > D125419.  Use an entry point like CodeGenTypes::arrangeCall.)  You don't 
> > > need to mess with the type system or anything like that.
> > > 
> > > The problem is correctly representing the lowered call in IR; we really 
> > > don't want to do lowering early because it will block optimizations.  I 
> > > considered using an operand bundle; we can probably make that work, but 
> > > it's complicated, and probably disables some optimizations.
> > > 
> > > I think the best thing we can do here is add an IR attribute to mark 
> > > arguments which are passed directly on AArch64, but need to be passed 
> > > indirectly for the x64 ABI.  Then AArch64Arm64ECCallLowering can check 
> > > for the attribute and modify its behavior.  This isn't really clean in 
> > > the sense that it's specific to the x64/aarch64 pair of calling 
> > > conventions, but I think the alternative is worse.
> > It looks not only 3/5/6/7, but also all size exclusive larger than 8 and 
> > less than 16 are difference between x86 ABI and Aarch64 ABI.
> > Maybe we can emit a function declaration here for the x86ABI thunk, then 
> > define it in Arm64ECCallLowering.
> > 
> I think the sizes between 8 and 16 work correctly already?  All sizes greater 
> than 8 are passed indirectly on x86, and the thunk generation code accounts 
> for that.  But that's not really important for the general question.
> 
> We need to preserve the required semantics for both the AArch64 and x86 
> calling conventions.  There are basically the following possibilities:
> 
> - We compute the declaration of the thunk in the frontend, and attach it to 
> the call with an operand bundle.  Like I mentioned, I don't want to go down 
> this path: the operand bundle blocks optimizations, and it becomes more 
> complicated for other code to generate arm64ec compatible calls.
> - We don't compute the definition of the thunk in the frontend.  Given that, 
> the only other way to attach the information we need to the call is to use 
> attributes.  The simplest thing is probably to attach the attribute directly 
> to the argument; name it "arm64ec-thunk-pass-indirect", or something like 

[PATCH] D131639: [OpenMP] Remove 'stdbool.h' from OpenMP header wrappers

2022-08-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, tianshilei1992, JonChesterfield.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patch removes the `stdbool.h` include path from the clang OpenMP
header wrappers. These are used to predeclare the device-side functions
for common headers. The bool header should not be necessary and causes
some problems with redeclarations.

Fixes #57066


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131639

Files:
  clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h


Index: clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
===
--- clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -40,7 +40,6 @@
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
 #ifndef __cplusplus
-#include 
 #include 
 #endif
 


Index: clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
===
--- clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -40,7 +40,6 @@
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
 #ifndef __cplusplus
-#include 
 #include 
 #endif
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131464: [test] Make tests pass regardless of gnu++14/gnu++17 default

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.



> I use something like
>
>   // RUN: %clang_cc1 %s -fsyntax-only -verify=expected,precxx17 -std=c++14 
> -fdata-sections -fcolor-diagnostics
>   // RUN: %clang_cc1 %s -fsyntax-only -verify -std=c++17 -fdata-sections 
> -fcolor-diagnostics
>   
>   ...
> TypedefAligned4 TA8c = TA8a + TA8b;  // expected-warning {{passing 4-byte 
> aligned argument to 8-byte aligned parameter 'this' of 'operator+' may result 
> in an unaligned pointer access}}
>  // expected-warning@-1 {{passing 
> 4-byte aligned argument to 8-byte aligned parameter 1 of 'operator+' may 
> result in an unaligned pointer access}}
>  // precxx17-warning@-2 {{passing 
> 4-byte aligned argument to 8-byte aligned parameter 'this' of 
> 'StructAligned8' may result in an unaligned pointer access}}
>
> Since every RUN line uses -std=.
> Pros: using `-verify` avoids `#if` directives which make the result look 
> better.
> Cons: when we upgrade to C++20, 23, ..., the tests will become less relevant.

Yeah, that's the main/a major concern as @aaron.ballman  has mentioned.

I think in this case a regex over either would be acceptable, since the test 
probably wasn't intending to test the particular wording for a particular 
version (presumably if this is the place where this separate wording is 
uniquely used (rather than some generic diagnostic infrastructure change) then 
it's got a C++17 test already)

> Discussion
> --
>
> Do we want to prefer `#if` in all cases? They work well with `-verify` tests 
> but not so well with `FileCheck` since `FileCheck` does not ignore 
> preprocessor skipped ranges.

I think where `#if` works well, it seems good to prefer it, yeah.

> Do all `CodeGenCXX` tests have to be fixed?

I think so.




Comment at: clang/test/AST/sourceranges.cpp:1-2
-// RUN: %clang_cc1 -triple i686-mingw32 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 -triple i686-mingw32 -ast-dump %s | FileCheck %s
 // RUN: %clang_cc1 -triple i686-mingw32 -std=c++1z -ast-dump %s | FileCheck %s 
-check-prefix=CHECK-1Z
 

MaskRay wrote:
> aaron.ballman wrote:
> > I assume this change is because we're testing c++17 on the next RUN line 
> > and you want to be sure we still get the old test coverage?
> > 
> > The trouble is, when we bump from C++17 to C++20, we'll lose the test 
> > coverage for the latest standard.
> > 
> > (Not your problem per se, but I continue to think we have a lit deficiency 
> > where we need some facilities to say "run this test in C++N and later", 
> > "run this test in C89 through CN", or "run this test in all C++ language 
> > modes", etc.)
> `FileCheck` does not ignore preprocessor skipped ranges, so it is very 
> difficult to work with both C++14/C++17 defaults, if our intention is to not 
> touch such tests in the default changing patch.
> 
> I think the best strategy is to do another pass to clean up the tests after 
> the transition, not trying to address everything in this patch.
> I think the best strategy is to do another pass to clean up the tests after 
> the transition, not trying to address everything in this patch.

Not everything needs to be addressed in this patch - these cleanups can be in 
several preliminary patches that are isolated and not dependent on the switch 
to C++17.

It looks like in this case there's one `CHECK-1Z` that's out of place (line 
111, test seems to pass OK even if that's a plain `CHECK` so I guess it 
probably should be) - and the rest are all at the end, which could be moved to 
a separate file and done with a hardcoded C++17 target. (but yeah, after the 
default switch we might end up wanting to remove the hardcoded 17 (allowing the 
test to become "17 and above"), move more test coverage over to here and leave 
whatever's 14 specific in the old test)

(maybe as a separate pass, though, to your point - we might be able to go 
through and remove `-std=c++17` from tests once that's the default, so the 
tests are forwards compatible to the next language version, most likely - but, 
again, a broader LIT feature that @aaron.ballman is referring to, where tests 
could specify which configurations (beyond language versions, this could also 
help cover things like... oh, right here: https://reviews.llvm.org/D125946, 
tests could be assumed to be correct for clang-repl too, and some mode where 
clang-repl's used instead of clang for broad-scale testing of clang-repl)



Comment at: clang/test/CXX/except/except.spec/p9-dynamic.cpp:1
-// RUN: %clang_cc1 -no-opaque-pointers %s -triple=x86_64-apple-darwin10 
-emit-llvm -o - -fcxx-exceptions -fexceptions | FileCheck %s 
--check-prefixes=CHECK,CHECK-PRE17
+// RUN: %clang_cc1 -std=c++14 -no-opaque-pointers %s 
-triple=x86_64-apple-darwin10 -emit-llvm -o - -fcxx-exceptions -fexceptions | 
FileCheck %s --check-prefixes=CHECK,CHECK-PRE17
 // RUN: %clang_cc1 -no-opaque-pointers %s 

[PATCH] D131448: Introduce iterator sentinel to make graph traversal implementation more efficient and cleaner

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Direction seems pretty good - some of the details I'm fuzzy on. If there's easy 
ways to keep some of the existing syntax (like I see at least one loop that I 
think was querying the incremented iterator for "isAtEnd" - maybe that can be 
preserved initially) to reduce the number of places this patch has to touch, 
then incremental patches after this, and then removing the backcompat API?




Comment at: llvm/include/llvm/ADT/BreadthFirstIterator.h:128-131
+  bool operator==(iterator_sentinel) const { return VisitQueue.empty(); }
+
+  bool operator!=(iterator_sentinel RHS) const { return !(*this == RHS); }
+

Generally any operator that can be a non-member should be a non-member (but can 
still be a friend) so there's equal conversion handling for LHS and RHS. Could 
you make these non-members? (maybe a separate patch to do the same to the 
existing op overloads, so the new ones don't look weird)

do you need the inverse operators too, so the sentinel can appear on either 
side of the comparison? 



Comment at: llvm/include/llvm/ADT/SCCIterator.h:49-50
   using SccTy = std::vector;
-  using reference = typename scc_iterator::reference;
+  using reference = const SccTy &;
+  using pointer = const SccTy *;
 

does this need a `value` type too? (& then define the `reference` and `pointer` 
types relative to that)



Comment at: llvm/include/llvm/ADT/SCCIterator.h:152-162
+bool hasCycle() const {
+  assert(!SCC.empty() && "Dereferencing END SCC iterator!");
+  if (SCC.size() > 1)
+return true;
+  NodeRef N = SCC.front();
+  for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
+   ++CI)

I'm not quite following why this requires the proxy object - even after reading 
the comment above. It looks like this function is entirely in terms of the 
`SCC` object that's returned from `operator*` - so maybe this could be a free 
function, called with `hasCycle(*some_iterator)`?



Comment at: llvm/include/llvm/ADT/SCCIterator.h:165-170
+  SCCProxy operator*() const {
 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
 return CurrentSCC;
   }
 
+  SCCProxy operator->() const { return operator*(); }

I always forget in which cases you're allowed to return a proxy object from an 
iterator - I thought some iterator concepts (maybe random access is the level 
at which this kicks in?) that required something that amounts to "there has to 
be a real object that outlives the iterator"

Could you refresh my memory on that/on why proxy objects are acceptable for 
this iterator type? (where/how does this iterator declare what concept it 
models anyway, since this removed the facade helper?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131448

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-08-10 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

This catches 
https://searchfox.org/mozilla-central/rev/c77834ec635c523f2ba0092fcd1728c9b1c3005b/third_party/rust/glslopt/glsl-optimizer/src/compiler/glsl/ir_reader.cpp#732
 but not 
https://searchfox.org/mozilla-central/rev/c77834ec635c523f2ba0092fcd1728c9b1c3005b/third_party/rust/glslopt/glsl-optimizer/src/compiler/glsl/ir.cpp#654.
 Is that expected?


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

https://reviews.llvm.org/D130058

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


[PATCH] D130516: [llvm] compression classes

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D130516#3710972 , @MaskRay wrote:

> I have only taken very brief look at the new version. Having an enum class 
> `CompressionKind` with a parallel `CompressionAlgorithm` seems redundant.
> `friend CompressionAlgorithm *CompressionKind::operator->() const;` looks 
> magical.
>
> I hope that someone insisting on object-oriented design can put up a version 
> with less boilerplate to compete with D130506 
> .

Posted something more comparable to D130506  
in D131638  - hard to compare, though - 
D130506  is additive, whereas D131638 
 and this D130516 
 are more replacements - though a different 
with my change there is at least for the initial patch leaving the old APIs in 
place, with the intent to incrementally change the usages until the old API can 
be removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130516

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


[PATCH] D119051: Extend the C++03 definition of POD to include defaulted functions

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Still waiting for the pre-merge checks to complete, but hopefully this is clean 
now.

Realized maybe we don't need a separate driver flag for this at all, and rely 
only on the abi-compat flag? That seems to be how (at least some) other ABI 
compat changes have been handled, looking at other uses of `ClangABI` enum 
values.

There could be more testing than only the indirect result of the packing 
problem that first inspired this patch. Any suggestions on what might be the 
most direct way to test whether the type's been considered pod in this sense?




Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5594
+unsigned Num;
+if (!Ver.consumeInteger(10, Num) && Num <= 13)
+  DefaultedSMFArePOD = false;

aaron.ballman wrote:
> Is Clang 13 still the correct thing to test for here, or should this be 16 
> these days?
Hmm - trunk is currently destined to be released as 16, yeah? So I think the 
right version would be 15, here. "If you want the old clang's ABI, ask for 
that, otherwise this is 16's ABI (new)"? Off-by-one error, of sorts. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119051

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


[PATCH] D131203: [HLSL] Initial codegen for SV_GroupIndex

2022-08-10 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added inline comments.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:19
 #include "clang/Basic/TargetOptions.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"

Does this mean CGHLSLRuntime is only for DirectX backend?



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:103
+  const ParmVarDecl ) {
+  assert(D.hasAttrs() && "Entry parameter missing annotation attribute!");
+  if (D.hasAttr()) {

FIXME: support struct parameter which may not have Annotation attribute.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:119
+  auto *EntryTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx), false);
+  Function *EntryFn =
+  Function::Create(EntryTy, Function::ExternalLinkage, FD->getName(), );

Need to move all attributes from Fn to EntryFn.
And make Fn a normal function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131203

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


[PATCH] D131625: [HLSL] Entry functions require param annotation

2022-08-10 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11875
+  for (const auto Param : FD->parameters()) {
+if (!Param->hasAttr()) {
+  Diag(Param->getLocation(), diag::err_hlsl_missing_parameter_annotation) 
<< Param;

When param type is struct, it is OK not to have HLSL semantic as long as all 
fields in the struct have HLSL semantic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131625

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


[PATCH] D131307: [Clang] Allow downgrading to a warning the diagnostic for setting a non fixed enum to a value outside the range of the enumeration values

2022-08-10 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

In D131307#3713011 , @sberg wrote:

> With this commit,
>
>   $ cat test.cc
>   #include "boost/numeric/conversion/cast.hpp"
>   int main() { return boost::numeric_cast(0L); }
>   
>   $ clang++ test.cc
>
> succeeds without any diagnostic, while with its parent commit 
> https://github.com/llvm/llvm-project/commit/b3645353041818f61e2580635409ddb81ff5a272
>  " [Clang] Diagnose ill-formed constant expression when setting a non fixed 
> enum to a value outside the range of the enumeration values" it had started 
> to fail with

Yes, that is intended. When modifying the change to allow it to be turned into 
a warning it started applying outside of constant expression contexts and that 
broke a lot more stuff.

I am planning on adding a default to a warning diagnostic for the non-constant 
expression cases but that will be done separately. I wanted to help folks 
unbreak their builds first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131307

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


[PATCH] D90275: [clang][IR] Add support for leaf attribute

2022-08-10 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added a comment.

Added the description in https://reviews.llvm.org/D131628


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90275

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


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

2022-08-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:290
+   }
+  return PromotedTy;
+  }

Indentation is off



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:305
+result.second = Builder.CreateFPTrunc(result.second, ComplexElementTy, 
\
+  "unpromotion");  
\
+}  
\

Can you pull everything in this block out as a helper function?  It could end 
up being useful for other paths if they acquire specialized promoted emission.  
Call it something like `EmitUnpromotion`.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:926
+}
+  } else {
+auto result = Visit(const_cast(E));

The `default` path in the `switch` above falls through, and because of this 
`else` it skips directly to the end and doesn't emit anything.  Test case would 
be something like `f16c + (0, f16c)` — really, any binary operator besides the 
four above that returns a complex value, such as comma, compound assignment, or 
one of the C++ pointer-to-member operators.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:950
+ComplexExprEmitter::EmitPromotedComplexOperand(const Expr *E,
+   QualType PromotionType) {
+  if (E->getType()->isAnyComplexType()) {

Maybe call this the `OverallPromotionType` to make it clear that it's not 
necessarily the right promotion type for the operand (as in fact it isn't in 
the scalar case).



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:953
+if (!PromotionType.isNull())
+  return ComplexPairTy(CGF.EmitPromotedComplexExpr(E, PromotionType));
+else

I think this conversion to `ComplexPairTy` is a no-op.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:1037
 ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
 OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
   } else {

This should do a conversion to the promoted LHS type.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:1050
+OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
+  }
 } else {

This should be testing equality with, and doing a conversion to, the promoted 
`ComplexElementTy`.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3033
   Expr *Op = E->getSubExpr();
+  QualType PromotionType = getPromotionType(Op->getType());
   if (Op->getType()->isAnyComplexType()) {

If we don't want a promoted result, there's no point in promoting the operand 
just to extract `_Real` or `_Imag`.  But if the caller *does* want a promoted 
result, then we should promote the operand before the extraction so that the 
`_Real` / `_Imag` doesn't cause a truncation.  So these methods should take a 
promotion type and, if present, use it to emit the operand as promoted before 
doing the extraction.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3089
 
-BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
+Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) {
+  if (auto BO = dyn_cast(E)) {

Please do `E = E->IgnoreParens();` as the first thing in this function, or else 
parenthesizing an operand will cause intermediate truncations.  You'll need to 
do the same thing in the complex emitter.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3112
+result = CGF.Builder.CreateFPExt(result, ConvertType(E->getType()));
+  return result;
+}

The first version of the fallback path (the one in the `else`) is correct.  
Like with the complex emitter, though, you've got a bug where fall through from 
the earlier `switch` ends up in the second path; test case is something like 
`f16 + (true, f16)`.

The best fix is to just not try to use `else` for your fallback path.  The 
earlier blocks will return if they recognize cases that they can specially 
handle; everything should fall out, and you handle everything that reaches that 
point with the fallback path.

This code should check for `UnaryOperator` like it does for `BinaryOperator` 
and delegate to your `_Real` / `_Imag` implementations above.  You should 
probably also handle unary `+` and `-` so that using those does not cause 
intermediate truncations.


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

https://reviews.llvm.org/D113107

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


[PATCH] D131635: [RISCV] Remove sifive-7-rv32/rv64 CPU names.

2022-08-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: kito-cheng, arcbbb, asb, luismarques.
Herald added subscribers: sunshaoce, VincentWu, luke957, StephenFan, vkmr, 
frasercrmck, evandro, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, 
jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, 
zzheng, jrtc27, shiva0217, niosHD, sabuasal, simoncook, johnrusso, rbar, 
hiraditya, arichardson.
Herald added a project: All.
craig.topper requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added projects: clang, LLVM.

These only exist to give -mtune=sifive-7-series something to
alias to. This aliasing made them valid -mcpu options, but they
aren't real product names and gcc doesn't support them with -mcpu.

Instead alias sifive-7-series to sifive-e76 and sifive-76.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131635

Files:
  clang/test/Driver/riscv-cpus.c
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/RISCVTargetParser.def
  llvm/lib/Target/RISCV/RISCV.td
  llvm/test/Transforms/LoopUnroll/RISCV/unroll.ll

Index: llvm/test/Transforms/LoopUnroll/RISCV/unroll.ll
===
--- llvm/test/Transforms/LoopUnroll/RISCV/unroll.ll
+++ llvm/test/Transforms/LoopUnroll/RISCV/unroll.ll
@@ -1,5 +1,5 @@
 ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
-; RUN: opt %s -S -mtriple=riscv64 -loop-unroll -mcpu=sifive-7-rv64 | FileCheck %s
+; RUN: opt %s -S -mtriple=riscv64 -loop-unroll -mcpu=sifive-s76 | FileCheck %s
 
 define dso_local void @saxpy(float %a, float* %x, float* %y) {
 ; CHECK-LABEL: @saxpy(
Index: llvm/lib/Target/RISCV/RISCV.td
===
--- llvm/lib/Target/RISCV/RISCV.td
+++ llvm/lib/Target/RISCV/RISCV.td
@@ -523,11 +523,6 @@
 def : ProcessorModel<"rocket-rv32", RocketModel, []>;
 def : ProcessorModel<"rocket-rv64", RocketModel, [Feature64Bit]>;
 
-def : ProcessorModel<"sifive-7-rv32", SiFive7Model, [],
- [TuneSiFive7]>;
-def : ProcessorModel<"sifive-7-rv64", SiFive7Model, [Feature64Bit],
- [TuneSiFive7]>;
-
 def : ProcessorModel<"sifive-e20", RocketModel, [FeatureStdExtM,
  FeatureStdExtC]>;
 
Index: llvm/include/llvm/Support/RISCVTargetParser.def
===
--- llvm/include/llvm/Support/RISCVTargetParser.def
+++ llvm/include/llvm/Support/RISCVTargetParser.def
@@ -4,7 +4,7 @@
 
 TUNE_ALIAS("generic", "generic-rv32", "generic-rv64")
 TUNE_ALIAS("rocket", "rocket-rv32", "rocket-rv64")
-TUNE_ALIAS("sifive-7-series", "sifive-7-rv32", "sifive-7-rv64")
+TUNE_ALIAS("sifive-7-series", "sifive-e76", "sifive-s76")
 
 #undef TUNE_ALIAS
 
@@ -17,8 +17,6 @@
 PROC(GENERIC_RV64, {"generic-rv64"}, FK_64BIT, {""})
 PROC(ROCKET_RV32, {"rocket-rv32"}, FK_NONE, {""})
 PROC(ROCKET_RV64, {"rocket-rv64"}, FK_64BIT, {""})
-PROC(SIFIVE_732, {"sifive-7-rv32"}, FK_NONE, {""})
-PROC(SIFIVE_764, {"sifive-7-rv64"}, FK_64BIT, {""})
 PROC(SIFIVE_E20, {"sifive-e20"}, FK_NONE, {"rv32imc"})
 PROC(SIFIVE_E21, {"sifive-e21"}, FK_NONE, {"rv32imac"})
 PROC(SIFIVE_E24, {"sifive-e24"}, FK_NONE, {"rv32imafc"})
Index: clang/test/Misc/target-invalid-cpu-note.c
===
--- clang/test/Misc/target-invalid-cpu-note.c
+++ clang/test/Misc/target-invalid-cpu-note.c
@@ -81,16 +81,16 @@
 
 // RUN: not %clang_cc1 -triple riscv32 -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix RISCV32
 // RISCV32: error: unknown target CPU 'not-a-cpu'
-// RISCV32-NEXT: note: valid target CPU values are: generic-rv32, rocket-rv32, sifive-7-rv32, sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76{{$}}
+// RISCV32-NEXT: note: valid target CPU values are: generic-rv32, rocket-rv32, sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76{{$}}
 
 // RUN: not %clang_cc1 -triple riscv64 -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix RISCV64
 // RISCV64: error: unknown target CPU 'not-a-cpu'
-// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, sifive-7-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74{{$}}
+// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74{{$}}
 
 // RUN: not %clang_cc1 -triple riscv32 -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE-RISCV32
 // TUNE-RISCV32: error: unknown target CPU 'not-a-cpu'
-// TUNE-RISCV32-NEXT: note: valid target CPU values are: generic-rv32, rocket-rv32, sifive-7-rv32, sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76, generic, rocket, sifive-7-series{{$}}
+// TUNE-RISCV32-NEXT: note: 

[PATCH] D131532: [Sema] Avoid isNullPointerConstant invocation

2022-08-10 Thread Justin Stitt via Phabricator via cfe-commits
justinstitt updated this revision to Diff 451687.
justinstitt added a comment.

use @rtrieu 's suggestion regarding not invoking isNullPointerConstant as 
opposed to checking for C++ lang opt.


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

https://reviews.llvm.org/D131532

Files:
  clang/lib/Sema/SemaChecking.cpp


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13339,10 +13339,10 @@
 return;
 
   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
-  const Expr::NullPointerConstantKind NullKind =
-  E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
-  if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
-return;
+  const Expr *NewE = E->IgnoreParenImpCasts();
+  bool GNUNull = isa(NewE);
+  bool NullPtr = NewE->getType()->isNullPtrType();
+  if (!GNUNull && !NullPtr) return;
 
   // Return if target type is a safe conversion.
   if (T->isAnyPointerType() || T->isBlockPointerType() ||
@@ -13358,7 +13358,7 @@
   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
 
   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
-  if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
+  if (GNUNull && Loc.isMacroID()) {
 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
 Loc, S.SourceMgr, S.getLangOpts());
 if (MacroName == "NULL")
@@ -13370,7 +13370,7 @@
 return;
 
   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
-  << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
+  << NullPtr << T << SourceRange(CC)
   << FixItHint::CreateReplacement(Loc,
   S.getFixItZeroLiteralForType(T, Loc));
 }


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13339,10 +13339,10 @@
 return;
 
   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
-  const Expr::NullPointerConstantKind NullKind =
-  E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
-  if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
-return;
+  const Expr *NewE = E->IgnoreParenImpCasts();
+  bool GNUNull = isa(NewE);
+  bool NullPtr = NewE->getType()->isNullPtrType();
+  if (!GNUNull && !NullPtr) return;
 
   // Return if target type is a safe conversion.
   if (T->isAnyPointerType() || T->isBlockPointerType() ||
@@ -13358,7 +13358,7 @@
   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
 
   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
-  if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
+  if (GNUNull && Loc.isMacroID()) {
 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
 Loc, S.SourceMgr, S.getLangOpts());
 if (MacroName == "NULL")
@@ -13370,7 +13370,7 @@
 return;
 
   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
-  << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
+  << NullPtr << T << SourceRange(CC)
   << FixItHint::CreateReplacement(Loc,
   S.getFixItZeroLiteralForType(T, Loc));
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119051: Extend the C++03 definition of POD to include defaulted functions

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie updated this revision to Diff 451686.
dblaikie added a comment.

Remove driver flag (just rely on ABI compat) & tidy up testing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119051

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/SemaCXX/class-layout.cpp

Index: clang/test/SemaCXX/class-layout.cpp
===
--- clang/test/SemaCXX/class-layout.cpp
+++ clang/test/SemaCXX/class-layout.cpp
@@ -1,10 +1,12 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98 -Wno-inaccessible-base
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base
-// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=14
-// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=6 -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98 -Wno-inaccessible-base -Wno-c++11-extensions
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions
+// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -DCLANG_ABI_COMPAT=14
+// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -fclang-abi-compat=6 -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -Wno-c++11-extensions -fclang-abi-compat=16 -DCLANG_ABI_COMPAT=16
 // expected-no-diagnostics
 
 #define SA(n, p) int a##n[(p) ? 1 : -1]
@@ -642,3 +644,24 @@
 _Static_assert(_Alignof(t1) == 1, "");
 _Static_assert(_Alignof(t2) == 1, "");
 } // namespace non_pod_packed
+
+namespace cxx11_pod {
+struct t1 {
+  t1() = default;
+  t1(const t1&) = delete;
+  ~t1() = delete;
+  t1(t1&&) = default;
+  int a;
+};
+struct t2 {
+  t1 v1;
+} __attribute__((packed));
+// 14 and below consider t1 non-pod, but pack it anyway
+// 15 considers it non-pod and doesn't pack it
+// 16 and up considers it pod and packs it again...
+#if defined(CLANG_ABI_COMPAT) && CLANG_ABI_COMPAT == 15
+_Static_assert(_Alignof(t2) == 4, "");
+#else
+_Static_assert(_Alignof(t2) == 1, "");
+#endif
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3530,6 +3530,8 @@
 GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver14)
 GenerateArg(Args, OPT_fclang_abi_compat_EQ, "14.0", SA);
+  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver15)
+GenerateArg(Args, OPT_fclang_abi_compat_EQ, "15.0", SA);
 
   if (Opts.getSignReturnAddressScope() ==
   LangOptions::SignReturnAddressScopeKind::All)
@@ -4022,6 +4024,8 @@
 Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
   else if (Major <= 14)
 Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
+  else if (Major <= 15)
+Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
 } else if (Ver != "latest") {
   Diags.Report(diag::err_drv_invalid_value)
   << A->getAsString(Args) << A->getValue();
Index: clang/lib/AST/DeclCXX.cpp
===
--- clang/lib/AST/DeclCXX.cpp
+++ clang/lib/AST/DeclCXX.cpp
@@ -768,12 +768,16 @@
 // Note that we have a user-declared 

[PATCH] D123967: Disable update_cc_test_checks.py tests in stand-alone builds

2022-08-10 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

@h-vetinari Do these updates look OK to you?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123967

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


[PATCH] D131632: [WIP] Enable SARIF Diagnostics

2022-08-10 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd created this revision.
Herald added a subscriber: mgorny.
Herald added a project: All.
abrahamcd requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Work in progress to enable Clang to emit SARIF diagnostics.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/unittests/Frontend/CMakeLists.txt
  clang/unittests/Frontend/SARIFDiagnosticTest.cpp
  clang/unittests/Frontend/sarif-diagnostics.cpp

Index: clang/unittests/Frontend/sarif-diagnostics.cpp
===
--- /dev/null
+++ clang/unittests/Frontend/sarif-diagnostics.cpp
@@ -0,0 +1,138 @@
+// RUN: %clang -fdiagnostics-format=sarif %s -o %t.exe -DGTEST
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s 2>
+// %t.diags || true RUN: %t.exe < %t.diags
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/JSON.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Program.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace {
+
+constexpr llvm::StringRef BrokenProgram =
+R"(// Example errors below start on line 2
+void main() {
+  int i = hello;
+
+  float test = 1a.0;
+
+  if (true)
+bool Yes = true;
+return;
+
+  bool j = hi;
+}
+})";
+
+TEST(SARIFDiagnosticTest, TestFields) {
+  llvm::SmallString<256> SearchDir;
+  llvm::sys::fs::current_path(SearchDir);
+  
+  SearchDir.append("/../../../bin");
+  // ASSERT_EQ(SearchDir.str(), "hi");
+  llvm::ErrorOr ClangPathOrErr =
+  llvm::sys::findProgramByName("clang", {SearchDir});
+  ASSERT_TRUE(ClangPathOrErr);
+  const std::string  = *ClangPathOrErr;
+  // ASSERT_EQ(ClangPath, "hi");
+
+  llvm::ErrorOr EchoPathOrErr =
+  llvm::sys::findProgramByName("echo");
+  ASSERT_TRUE(EchoPathOrErr);
+  const std::string  = *EchoPathOrErr;
+
+  int EchoInputFD;
+  llvm::SmallString<32> EchoInputFile, EchoOutputFile;
+  llvm::sys::fs::createTemporaryFile("echo-input", "", EchoInputFD,
+ EchoInputFile);
+  llvm::sys::fs::createTemporaryFile("echo-output", "", EchoOutputFile);
+  llvm::FileRemover InputRemover(EchoInputFile.c_str());
+  llvm::FileRemover OutputRemover(EchoOutputFile.c_str());
+
+  llvm::Optional Redirects[] = {
+  EchoInputFile.str(), EchoOutputFile.str(), llvm::StringRef("")};
+
+  int RunResult = llvm::sys::ExecuteAndWait(EchoPath, {"echo", BrokenProgram},
+llvm::None, Redirects);
+  ASSERT_EQ(RunResult, 0);
+
+  // auto EchoOutputBuf = llvm::MemoryBuffer::getFile(EchoOutputFile.c_str());
+  // ASSERT_TRUE(EchoOutputBuf);
+  // llvm::StringRef EchoOutput = EchoOutputBuf.get()->getBuffer();
+  // ASSERT_EQ(EchoOutput.str(), "hi");
+
+  llvm::SmallString<32> ClangErrFile;
+  llvm::sys::fs::createTemporaryFile("clang-err", "", ClangErrFile);
+  llvm::FileRemover ClangErrRemover(ClangErrFile.c_str());
+
+  llvm::Optional ClangRedirects[] = {
+  EchoOutputFile.str(), llvm::StringRef(""), ClangErrFile.str()};
+  llvm::StringRef Args[] = {"clang",
+"-xc++",
+"-",
+"-fsyntax-only",
+"-Wall",
+"-Wextra",
+"-fdiagnostics-format=sarif"};
+
+  int ClangResult =
+  llvm::sys::ExecuteAndWait(ClangPath, Args, llvm::None, ClangRedirects);
+  ASSERT_EQ(ClangResult, 1);
+
+  // auto ClangOutputBuf = llvm::MemoryBuffer::getFile(ClangOutputFile.c_str());
+  // ASSERT_TRUE(ClangOutputBuf);
+  // llvm::StringRef ClangOutput = ClangOutputBuf.get()->getBuffer();
+  // ASSERT_EQ(ClangOutput.str(), "hi");
+
+  auto ClangErrBuf = llvm::MemoryBuffer::getFile(ClangErrFile.c_str());
+  ASSERT_TRUE(ClangErrBuf);
+  llvm::StringRef ClangErr = ClangErrBuf.get()->getBuffer();
+  ASSERT_EQ(ClangErr.str(), "hi");
+
+  llvm::Expected Value = llvm::json::parse(ClangErr.str());
+  ASSERT_FALSE(!Value);
+
+  llvm::json::Object *SarifDoc = Value->getAsObject();
+
+  const llvm::json::Array *Runs = SarifDoc->getArray("runs");
+  const llvm::json::Object *TheRun = Runs->back().getAsObject();
+  const llvm::json::Array *Results = TheRun->getArray("results");
+  
+  // Check Artifacts
+  const llvm::json::Array *Artifacts = TheRun->getArray("artifacts");
+  const llvm::json::Object *TheArtifact = Artifacts->back().getAsObject();
+  const llvm::json::Object *Location = TheArtifact->getObject("location");
+
+  

[PATCH] D129570: Add new clang-tidy check to find implicit conversions from enum to integer.

2022-08-10 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 updated this revision to Diff 451666.

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

https://reviews.llvm.org/D129570

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/EnumToIntCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/EnumToIntCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-int.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-int.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-int.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-int.cpp
@@ -0,0 +1,28 @@
+// RUN: %check_clang_tidy %s bugprone-enum-to-int %t
+
+enum A { e1,
+ e2 };
+
+struct bar {
+  bar(int);
+};
+void foo(int i);
+void f1() {
+  foo(e1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: Enum is implictly converted to an integral. [bugprone-enum-to-int]
+}
+void f2() {
+  foo(static_cast(e1));
+}
+void f3() {
+  int i = e1;
+  foo(i);
+}
+void f4() {
+  bar a(e1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Enum is implictly converted to an integral. [bugprone-enum-to-int]
+}
+void f5() {
+  auto a = bar{e1};
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: Enum is implictly converted to an integral. [bugprone-enum-to-int]
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -86,6 +86,7 @@
`bugprone-dangling-handle `_,
`bugprone-dynamic-static-initializers `_,
`bugprone-easily-swappable-parameters `_,
+   `bugprone-enum-to-int `_,
`bugprone-exception-escape `_,
`bugprone-fold-init-type `_,
`bugprone-forward-declaration-namespace `_,
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-int.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-int.rst
@@ -0,0 +1,24 @@
+.. title:: clang-tidy - bugprone-enum-to-int
+
+bugprone-enum-to-int
+
+
+This check diagnoses instances where an enum is implicitly converted to an
+integer. In C++11, enums can be defined as ``enum class`` which will prevent
+such implicit conversion, however, ``enum`` provides no such guarantees to
+prevent bugs. There can be many reasons why ``enum`` cannot be replaced with
+``enum class`` such as compatibility with C or legacy libraries.
+
+This check will diagnose similiar implicit conversions whne using ``enum`` to
+find the same class of bugs. Currently it will only warn on function or
+constructor calls as such conversions are not clear to the usr, but this
+could be expanded in the future.
+
+Examples:
+
+.. code-block:: c++
+
+void foo(int i);
+void f() {
+foo(e1); // e1 is implictly converted to an int
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -99,6 +99,11 @@
 New checks
 ^^
 
+- New :doc:`bugprone-enum-to-int
+  ` check.
+
+  Finds implicit conversion of enum to an integral type.
+
 New check aliases
 ^
 
Index: clang-tools-extra/clang-tidy/bugprone/EnumToIntCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/bugprone/EnumToIntCheck.h
@@ -0,0 +1,34 @@
+//===--- EnumToIntCheck.h - clang-tidy --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ENUMTOINTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ENUMTOINTCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+/// FIXME: Write a short description.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/enum-to-int.html
+class EnumToIntCheck : public ClangTidyCheck {
+public:
+  EnumToIntCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace bugprone
+} // namespace tidy
+} // namespace clang
+
+#endif // 

[PATCH] D131298: [clang-doc] Read docstrings for record members

2022-08-10 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

Thanks. Can we get the small changes to the assert + the TODO in Serialize.cpp? 
I'll be happy to land this for you after that.


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

https://reviews.llvm.org/D131298

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


[PATCH] D131203: [HLSL] Initial codegen for SV_GroupIndex

2022-08-10 Thread Chris Bieneman via Phabricator via cfe-commits
beanz updated this revision to Diff 451660.
beanz added a comment.

This is a fairly significant reworking of this patch to handle entry functions 
being called (which I hadn't anticipated). There may be some additional tweaks 
required, but the general flow here is:

(1) Don't prevent mangling of entry functions, this allows us to generate calls 
based on the mangled function name which makes things happy.
(2) Do codegen the function with parameters following the C++ codegen paths 
with no alterations
(3) Also generate a c-exported, unmanged, void(void) function for each entry 
which populates semantic arguments and calls into the mangled entry function

This solution results in code generation that covers the required cases, and 
the optimizer can (and will) eliminate the wrapper function in all cases that 
it can, and in any case that it can't the compiler will explode because 
recurison is not allowed in HLSL unless it can be translated to a loop by the 
compiler.

Fun right?

This now depends on D131625 , which is a 
small change to enforce that all entry parameters have semantic annotations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131203

Files:
  clang/lib/AST/Mangle.cpp
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGenHLSL/semantics/GroupIndex-codegen.hlsl

Index: clang/test/CodeGenHLSL/semantics/GroupIndex-codegen.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/semantics/GroupIndex-codegen.hlsl
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -emit-llvm -disable-llvm-passes -o - -hlsl-entry main %s
+
+[numthreads(1,1,1)]
+void main(unsigned GI : SV_GroupIndex) {
+  main(GI - 1);
+}
+
+// For HLSL entry functions, we are generating a C-export function that wraps
+// the C++-mangled entry function. The wrapper function can be used to populate
+// semantic parameters and provides the expected void(void) signature that
+// drivers expect for entry points.
+
+//CHECK: define void @main() {
+//CHECK-NEXT: entry:
+//CHECK-NEXT:   %0 = call i32 @llvm.dx.flattened.thread.id.in.group()
+//CHECK-NEXT:   call void @"?main@@YAXI@Z"(i32 %0)
+//CHECK-NEXT:   ret void
+//CHECK-NEXT: }
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -16,6 +16,7 @@
 #include "CGCXXABI.h"
 #include "CGCleanup.h"
 #include "CGDebugInfo.h"
+#include "CGHLSLRuntime.h"
 #include "CGOpenMPRuntime.h"
 #include "CodeGenModule.h"
 #include "CodeGenPGO.h"
@@ -907,6 +908,9 @@
   if (D && D->hasAttr())
 Fn->addFnAttr(llvm::Attribute::NoProfile);
 
+  if (D && D->hasAttr())
+CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
+
   if (D) {
 // Function attributes take precedence over command line flags.
 if (auto *A = D->getAttr()) {
Index: clang/lib/CodeGen/CGHLSLRuntime.h
===
--- clang/lib/CodeGen/CGHLSLRuntime.h
+++ clang/lib/CodeGen/CGHLSLRuntime.h
@@ -15,6 +15,8 @@
 #ifndef LLVM_CLANG_LIB_CODEGEN_CGHLSLRUNTIME_H
 #define LLVM_CLANG_LIB_CODEGEN_CGHLSLRUNTIME_H
 
+#include "llvm/IR/IRBuilder.h"
+
 #include "clang/Basic/HLSLRuntime.h"
 
 namespace llvm {
@@ -26,6 +28,7 @@
 class CallExpr;
 class Type;
 class VarDecl;
+class ParmVarDecl;
 
 class FunctionDecl;
 
@@ -39,6 +42,8 @@
   uint32_t ResourceCounters[static_cast(
   hlsl::ResourceClass::NumClasses)] = {0};
 
+  llvm::Value *emitInputSemantic(llvm::IRBuilder<> , const ParmVarDecl );
+
 public:
   CGHLSLRuntime(CodeGenModule ) : CGM(CGM) {}
   virtual ~CGHLSLRuntime() {}
@@ -48,6 +53,8 @@
   void finishCodeGen();
 
   void setHLSLFunctionAttributes(llvm::Function *, const FunctionDecl *);
+
+  void emitEntryFunction(const FunctionDecl *FD, llvm::Function *Fn);
 };
 
 } // namespace CodeGen
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -14,7 +14,9 @@
 
 #include "CGHLSLRuntime.h"
 #include "CodeGenModule.h"
+#include "clang/AST/Decl.h"
 #include "clang/Basic/TargetOptions.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/Module.h"
 
@@ -95,3 +97,36 @@
  ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
   }
 }
+
+llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> ,
+  const ParmVarDecl ) {
+  assert(D.hasAttrs() && "Entry parameter missing annotation attribute!");
+  if (D.hasAttr()) {
+llvm::Function *DxGroupIndex =
+

[clang] d5fcf8a - [clang][deps] NFC: Move dependency consumer into header file

2022-08-10 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-08-10T15:25:09-07:00
New Revision: d5fcf8a5e2e03c9c8e375876a2127d90db7efe13

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

LOG: [clang][deps] NFC: Move dependency consumer into header file

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index 77263cd6233b8..aabc1e6b16678 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -13,8 +13,11 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringMap.h"
 #include 
+#include 
 
 namespace clang {
 namespace tooling {
@@ -101,6 +104,42 @@ class DependencyScanningTool {
   DependencyScanningWorker Worker;
 };
 
+class FullDependencyConsumer : public DependencyConsumer {
+public:
+  FullDependencyConsumer(const llvm::StringSet<> )
+  : AlreadySeen(AlreadySeen) {}
+
+  void handleDependencyOutputOpts(const DependencyOutputOptions &) override {}
+
+  void handleFileDependency(StringRef File) override {
+Dependencies.push_back(std::string(File));
+  }
+
+  void handlePrebuiltModuleDependency(PrebuiltModuleDep PMD) override {
+PrebuiltModuleDeps.emplace_back(std::move(PMD));
+  }
+
+  void handleModuleDependency(ModuleDeps MD) override {
+ClangModuleDeps[MD.ID.ContextHash + MD.ID.ModuleName] = std::move(MD);
+  }
+
+  void handleContextHash(std::string Hash) override {
+ContextHash = std::move(Hash);
+  }
+
+  FullDependenciesResult getFullDependencies(
+  const std::vector ) const;
+
+private:
+  std::vector Dependencies;
+  std::vector PrebuiltModuleDeps;
+  llvm::MapVector>
+  ClangModuleDeps;
+  std::string ContextHash;
+  std::vector OutputPaths;
+  const llvm::StringSet<> 
+};
+
 } // end namespace dependencies
 } // end namespace tooling
 } // end namespace clang

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 03ad6dcc51b30..cf6085857b4d1 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -114,76 +114,42 @@ DependencyScanningTool::getFullDependencies(
 const std::vector , StringRef CWD,
 const llvm::StringSet<> ,
 llvm::Optional ModuleName) {
-  class FullDependencyPrinterConsumer : public DependencyConsumer {
-  public:
-FullDependencyPrinterConsumer(const llvm::StringSet<> )
-: AlreadySeen(AlreadySeen) {}
-
-void
-handleDependencyOutputOpts(const DependencyOutputOptions ) override {}
-
-void handleFileDependency(StringRef File) override {
-  Dependencies.push_back(std::string(File));
-}
-
-void handlePrebuiltModuleDependency(PrebuiltModuleDep PMD) override {
-  PrebuiltModuleDeps.emplace_back(std::move(PMD));
-}
-
-void handleModuleDependency(ModuleDeps MD) override {
-  ClangModuleDeps[MD.ID.ContextHash + MD.ID.ModuleName] = std::move(MD);
-}
-
-void handleContextHash(std::string Hash) override {
-  ContextHash = std::move(Hash);
-}
-
-FullDependenciesResult getFullDependencies(
-const std::vector ) const {
-  FullDependencies FD;
-
-  FD.OriginalCommandLine =
-  ArrayRef(OriginalCommandLine).slice(1);
+  FullDependencyConsumer Consumer(AlreadySeen);
+  llvm::Error Result =
+  Worker.computeDependencies(CWD, CommandLine, Consumer, ModuleName);
+  if (Result)
+return std::move(Result);
+  return Consumer.getFullDependencies(CommandLine);
+}
 
-  FD.ID.ContextHash = std::move(ContextHash);
+FullDependenciesResult FullDependencyConsumer::getFullDependencies(
+const std::vector ) const {
+  FullDependencies FD;
 
-  FD.FileDeps.assign(Dependencies.begin(), Dependencies.end());
+  FD.OriginalCommandLine = ArrayRef(OriginalCommandLine).slice(1);
 
-  for (auto & : ClangModuleDeps) {
-auto  = M.second;
-if (MD.ImportedByMainFile)
-  FD.ClangModuleDeps.push_back(MD.ID);
-  }
+  FD.ID.ContextHash = std::move(ContextHash);
 
-  FD.PrebuiltModuleDeps = std::move(PrebuiltModuleDeps);
+  FD.FileDeps.assign(Dependencies.begin(), Dependencies.end());
 
-  FullDependenciesResult FDR;
+  for (auto & : 

[PATCH] D131625: [HLSL] Entry functions require param annotation

2022-08-10 Thread Chris Bieneman via Phabricator via cfe-commits
beanz created this revision.
beanz added reviewers: bogner, aaron.ballman, python3kgae, pow2clk, tex3d.
Herald added a subscriber: Anastasia.
Herald added a project: All.
beanz requested review of this revision.
Herald added a project: clang.

HLSL entry function parameters must have parameter annotations. This
allows appropriate intrinsic values to be populated into parameters
during code generation.

This does not handle entry function return values, which will be
handled in a subsequent commit because we don't currently support any
annotations that are valid for function returns.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131625

Files:
  clang/include/clang/AST/Attr.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaHLSL/Semantics/missing_entry_annotation.hlsl
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2852,7 +2852,8 @@
   { "INHERITABLE_ATTR", "InheritableAttr" },
   { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
   { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
-  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
+  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" },
+  { "HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}
 };
 
 static void emitDefaultDefine(raw_ostream , StringRef name,
Index: clang/test/SemaHLSL/Semantics/missing_entry_annotation.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/Semantics/missing_entry_annotation.hlsl
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -fsyntax-only -hlsl-entry main -verify %s
+
+[numthreads(1,1, 1)]
+void main(int GI) { } // expected-error{{entry function parameter 'GI' missing annotation}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -11870,6 +11870,13 @@
 }
 break;
   }
+
+  for (const auto Param : FD->parameters()) {
+if (!Param->hasAttr()) {
+  Diag(Param->getLocation(), diag::err_hlsl_missing_parameter_annotation) << Param;
+  Param->setInvalidDecl();
+}
+  }
 }
 
 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11632,6 +11632,7 @@
 def err_hlsl_numthreads_invalid : Error<"total number of threads cannot exceed %0">;
 def err_hlsl_missing_numthreads : Error<"missing numthreads attribute for %0 shader entry">;
 def err_hlsl_attribute_param_mismatch : Error<"%0 attribute parameters do not match the previous declaration">;
+def err_hlsl_missing_parameter_annotation : Error<"entry function parameter %0 missing annotation">;
 
 def err_hlsl_pointers_unsupported : Error<
   "%select{pointers|references}0 are unsupported in HLSL">;
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -607,6 +607,9 @@
 /// A attribute is either a declaration attribute or a statement attribute.
 class DeclOrStmtAttr : InheritableAttr;
 
+/// An attribute class for HLSL Annotations.
+class HLSLAnnotationAttr : InheritableAttr;
+
 /// A target-specific attribute.  This class is meant to be used as a mixin
 /// with InheritableAttr or Attr depending on the attribute's needs.
 class TargetSpecificAttr {
@@ -4005,7 +4008,7 @@
   let Documentation = [NumThreadsDocs];
 }
 
-def HLSLSV_GroupIndex: InheritableAttr {
+def HLSLSV_GroupIndex: HLSLAnnotationAttr {
   let Spellings = [HLSLSemantic<"SV_GroupIndex">];
   let Subjects = SubjectList<[ParmVar, GlobalVar]>;
   let LangOpts = [HLSL];
Index: clang/include/clang/AST/Attr.h
===
--- clang/include/clang/AST/Attr.h
+++ clang/include/clang/AST/Attr.h
@@ -190,6 +190,22 @@
   }
 };
 
+class HLSLAnnotationAttr : public InheritableAttr {
+protected:
+  HLSLAnnotationAttr(ASTContext ,
+   const AttributeCommonInfo , attr::Kind AK,
+   bool IsLateParsed, bool InheritEvenIfAlreadyPresent)
+  : InheritableAttr(Context, CommonInfo, AK, IsLateParsed,
+InheritEvenIfAlreadyPresent) {}
+
+public:
+  // Implement isa/cast/dyncast/etc.
+  static bool classof(const Attr *A) {
+return A->getKind() >= attr::FirstHLSLAnnotationAttr &&
+   A->getKind() <= attr::LastHLSLAnnotationAttr;
+  }
+};
+
 /// A parameter attribute which changes the argument-passing ABI rule
 /// for the 

[PATCH] D131423: [clang] fix frontend crash when evaluating type trait

2022-08-10 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

In D131423#3712083 , @inclyc wrote:

> @aaron.ballman @shafik  (Help wanted). These type traits will not cause clang 
> to crash if current patch applied, but the `bool x` in the test case will 
> evaluate to `false`.  I think the problem behind the github issue is that we 
> didn't check the number of arguments for builtin type traits like 
> `__is_constructible`
>
> I want to ask what is our expected behavior for this, give an error like 
> using `std::is_constructible` or just consider `__is_constructible` should 
> always have a bool value? Should we report a warning but compile translation 
> unit, or report an error and terminate?

I think it should be an error but @aaron.ballman  may have a different idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131423

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


[PATCH] D131563: [WIP] [clang] Fix clang multiarch isssue with musl

2022-08-10 Thread Sergei Barannikov via Phabricator via cfe-commits
barannikov88 added a comment.

The diff seems to be restricted to few lines. It should include the full 
context.




Comment at: clang/lib/Driver/ToolChains/Linux.cpp:49
 
+  std::string EnvName = TargetTriple.isMusl() ? "musl" : "gnu";
+

* `!isMusl()` does not mean it is "gnu".
* Why don't just use `Triple::getEnvironmentTypeName`?



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

https://reviews.llvm.org/D131563

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


[PATCH] D130969: [clang] [HLSL] Fix GCC warnings about virtual methods that are hidden

2022-08-10 Thread Chris Bieneman via Phabricator via cfe-commits
beanz accepted this revision.
beanz added a comment.
This revision is now accepted and ready to land.

LGTM. This is a really unfortunate interface that causes this :(.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130969

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


[PATCH] D131622: [NFC][PowerPC] Add missing NOCOMPAT checks for builtins-ppc-xlcompat.c

2022-08-10 Thread Lei Huang via Phabricator via cfe-commits
lei created this revision.
lei added reviewers: nemanjai, amyk, power-llvm-team.
Herald added a subscriber: shchenz.
Herald added a project: All.
lei requested review of this revision.
Herald added a project: clang.

Followup patch to address request from https://reviews.llvm.org/D124093


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131622

Files:
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c


Index: clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
===
--- clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
+++ clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
@@ -21,29 +21,38 @@
 void test() {
 // CHECK-LABEL: @test(
 // CHECK-NEXT:  entry:
-// CHECK-LE-LABEL: @test(
-// CHECK-LE-NEXT:  entry:
+// NOCOMPAT-LABEL: @test(
+// NOCOMPAT-NEXT:  entry:
 
   res_vf = vec_ctf(vsll, 4);
 // CHECK: [[TMP0:%.*]] = load <2 x i64>, <2 x i64>* @vsll, align 16
 // CHECK-NEXT:[[TMP1:%.*]] = call <4 x float> @llvm.ppc.vsx.xvcvsxdsp(<2 x 
i64> [[TMP0]])
 // CHECK-NEXT:fmul <4 x float> [[TMP1]], 
+// NOCOMPAT:  [[TMP0:%.*]] = load <2 x i64>, <2 x i64>* @vsll, align 16
+// NOCOMPAT-NEXT: [[CONV:%.*]] = sitofp <2 x i64> [[TMP0]] to <2 x double>
+// NOCOMPAT-NEXT: fmul <2 x double> [[CONV]], 
 
   res_vf = vec_ctf(vull, 4);
 // CHECK: [[TMP2:%.*]] = load <2 x i64>, <2 x i64>* @vull, align 16
 // CHECK-NEXT:[[TMP3:%.*]] = call <4 x float> @llvm.ppc.vsx.xvcvuxdsp(<2 x 
i64> [[TMP2]])
 // CHECK-NEXT:fmul <4 x float> [[TMP3]], 
+// NOCOMPAT:  [[TMP2:%.*]] = load <2 x i64>, <2 x i64>* @vull, align 16
+// NOCOMPAT-NEXT: [[CONV1:%.*]] = uitofp <2 x i64> [[TMP2]] to <2 x double>
+// NOCOMPAT-NEXT: fmul <2 x double> [[CONV1]], 
 
   res_vsll = vec_cts(vd, 4);
 // CHECK: [[TMP4:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
 // CHECK-NEXT:fmul <2 x double> [[TMP4]], 
 // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcvdpsxws(<2 x double>
+// NOCOMPAT:  [[TMP4:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
+// NOCOMPAT-NEXT: fmul <2 x double> [[TMP4]], 
 
   res_vull = vec_ctu(vd, 4);
 // CHECK: [[TMP8:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
 // CHECK-NEXT:fmul <2 x double> [[TMP8]], 
 // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcvdpuxws(<2 x double>
-// NONCOMPAT: call <4 x i32> @llvm.ppc.vsx.xvcvdpuxws(<2 x double>
+// NOCOMPAT:  [[TMP7:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
+// NOCOMPAT-NEXT: fmul <2 x double> [[TMP7]], 
 
   res_vd = vec_round(vd);
 // CHECK: call double @llvm.ppc.readflm()


Index: clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
===
--- clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
+++ clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat.c
@@ -21,29 +21,38 @@
 void test() {
 // CHECK-LABEL: @test(
 // CHECK-NEXT:  entry:
-// CHECK-LE-LABEL: @test(
-// CHECK-LE-NEXT:  entry:
+// NOCOMPAT-LABEL: @test(
+// NOCOMPAT-NEXT:  entry:
 
   res_vf = vec_ctf(vsll, 4);
 // CHECK: [[TMP0:%.*]] = load <2 x i64>, <2 x i64>* @vsll, align 16
 // CHECK-NEXT:[[TMP1:%.*]] = call <4 x float> @llvm.ppc.vsx.xvcvsxdsp(<2 x i64> [[TMP0]])
 // CHECK-NEXT:fmul <4 x float> [[TMP1]], 
+// NOCOMPAT:  [[TMP0:%.*]] = load <2 x i64>, <2 x i64>* @vsll, align 16
+// NOCOMPAT-NEXT: [[CONV:%.*]] = sitofp <2 x i64> [[TMP0]] to <2 x double>
+// NOCOMPAT-NEXT: fmul <2 x double> [[CONV]], 
 
   res_vf = vec_ctf(vull, 4);
 // CHECK: [[TMP2:%.*]] = load <2 x i64>, <2 x i64>* @vull, align 16
 // CHECK-NEXT:[[TMP3:%.*]] = call <4 x float> @llvm.ppc.vsx.xvcvuxdsp(<2 x i64> [[TMP2]])
 // CHECK-NEXT:fmul <4 x float> [[TMP3]], 
+// NOCOMPAT:  [[TMP2:%.*]] = load <2 x i64>, <2 x i64>* @vull, align 16
+// NOCOMPAT-NEXT: [[CONV1:%.*]] = uitofp <2 x i64> [[TMP2]] to <2 x double>
+// NOCOMPAT-NEXT: fmul <2 x double> [[CONV1]], 
 
   res_vsll = vec_cts(vd, 4);
 // CHECK: [[TMP4:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
 // CHECK-NEXT:fmul <2 x double> [[TMP4]], 
 // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcvdpsxws(<2 x double>
+// NOCOMPAT:  [[TMP4:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
+// NOCOMPAT-NEXT: fmul <2 x double> [[TMP4]], 
 
   res_vull = vec_ctu(vd, 4);
 // CHECK: [[TMP8:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
 // CHECK-NEXT:fmul <2 x double> [[TMP8]], 
 // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcvdpuxws(<2 x double>
-// NONCOMPAT: call <4 x i32> @llvm.ppc.vsx.xvcvdpuxws(<2 x double>
+// NOCOMPAT:  [[TMP7:%.*]] = load <2 x double>, <2 x double>* @vd, align 16
+// NOCOMPAT-NEXT: fmul <2 x double> [[TMP7]], 
 
   res_vd = vec_round(vd);
 // CHECK: call double @llvm.ppc.readflm()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D131084: Add support for specifying the severity of a SARIF Result.

2022-08-10 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y updated this revision to Diff 451635.
vaibhav.y added a comment.

Run git-clang-format

Rebase on upstream


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131084

Files:
  clang/include/clang/Basic/Sarif.h
  clang/lib/Basic/Sarif.cpp
  clang/unittests/Basic/SarifTest.cpp

Index: clang/unittests/Basic/SarifTest.cpp
===
--- clang/unittests/Basic/SarifTest.cpp
+++ clang/unittests/Basic/SarifTest.cpp
@@ -7,7 +7,6 @@
 //===--===//
 
 #include "clang/Basic/Sarif.h"
-#include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
@@ -33,9 +32,9 @@
 
 static std::string serializeSarifDocument(llvm::json::Object &) {
   std::string Output;
-  llvm::json::Value value(std::move(Doc));
+  llvm::json::Value Value(std::move(Doc));
   llvm::raw_string_ostream OS{Output};
-  OS << llvm::formatv("{0}", value);
+  OS << llvm::formatv("{0}", Value);
   OS.flush();
   return Output;
 }
@@ -86,7 +85,7 @@
   const llvm::json::Object  = Writer.createDocument();
   std::vector Keys(EmptyDoc.size());
   std::transform(EmptyDoc.begin(), EmptyDoc.end(), Keys.begin(),
- [](auto item) { return item.getFirst(); });
+ [](auto Item) { return Item.getFirst(); });
 
   // THEN:
   ASSERT_THAT(Keys, testing::UnorderedElementsAre("$schema", "version"));
@@ -113,17 +112,17 @@
   ASSERT_EQ(Runs->size(), 1UL);
 
   // The tool associated with the run was the tool
-  const llvm::json::Object *driver =
+  const llvm::json::Object *Driver =
   Runs->begin()->getAsObject()->getObject("tool")->getObject("driver");
-  ASSERT_THAT(driver, testing::NotNull());
+  ASSERT_THAT(Driver, testing::NotNull());
 
-  ASSERT_TRUE(driver->getString("name").has_value());
-  ASSERT_TRUE(driver->getString("fullName").has_value());
-  ASSERT_TRUE(driver->getString("language").has_value());
+  ASSERT_TRUE(Driver->getString("name").has_value());
+  ASSERT_TRUE(Driver->getString("fullName").has_value());
+  ASSERT_TRUE(Driver->getString("language").has_value());
 
-  EXPECT_EQ(driver->getString("name").value(), ShortName);
-  EXPECT_EQ(driver->getString("fullName").value(), LongName);
-  EXPECT_EQ(driver->getString("language").value(), "en-US");
+  EXPECT_EQ(Driver->getString("name").value(), ShortName);
+  EXPECT_EQ(Driver->getString("fullName").value(), LongName);
+  EXPECT_EQ(Driver->getString("language").value(), "en-US");
 }
 
 TEST_F(SarifDocumentWriterTest, addingResultsWillCrashIfThereIsNoRun) {
@@ -147,6 +146,47 @@
   ASSERT_DEATH(Writer.appendResult(EmptyResult), Matcher);
 }
 
+TEST_F(SarifDocumentWriterTest, settingInvalidRankWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A SarifReportingConfiguration is created with an invalid "rank"
+  // * Ranks below 0.0 are invalid
+  // * Ranks above 100.0 are invalid
+
+  // THEN: The builder will crash in either case
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(-1.0),
+   ::testing::HasSubstr("Rule rank cannot be smaller than 0.0"));
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(101.0),
+   ::testing::HasSubstr("Rule rank cannot be larger than 100.0"));
+}
+
+TEST_F(SarifDocumentWriterTest, creatingResultWithDisabledRuleWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A disabled Rule is created, and a result is create referencing this rule
+  const auto  = SarifReportingConfiguration::create().disable();
+  auto RuleIdx =
+  Writer.createRule(SarifRule::create().setDefaultConfiguration(Config));
+  const SarifResult  = SarifResult::create(RuleIdx);
+
+  // THEN:
+  // SarifResult::create(...) will produce a crash
+  ASSERT_DEATH(
+  Writer.appendResult(Result),
+  ::testing::HasSubstr("Cannot add a result referencing a disabled Rule"));
+}
+
 // Test adding rule and result shows up in the final document
 TEST_F(SarifDocumentWriterTest, addingResultWithValidRuleAndRunIsOk) {
   // GIVEN:
@@ -160,9 +200,9 @@
   // WHEN:
   Writer.createRun("sarif test", "sarif test runner");
   unsigned RuleIdx = Writer.createRule(Rule);
-  const SarifResult  = SarifResult::create(RuleIdx);
+  const SarifResult  = SarifResult::create(RuleIdx);
 
-  Writer.appendResult(result);
+  Writer.appendResult(Result);
   const llvm::json::Object  = Writer.createDocument();
 
   // THEN:
@@ -199,10 +239,10 @@
   EXPECT_TRUE(Artifacts->empty());
 }
 
-TEST_F(SarifDocumentWriterTest, 

[PATCH] D131084: Add support for specifying the severity of a SARIF Result.

2022-08-10 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y updated this revision to Diff 451633.
vaibhav.y added a comment.

Autofix clang-tidy readability warnings


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131084

Files:
  clang/include/clang/Basic/Sarif.h
  clang/lib/Basic/Sarif.cpp
  clang/unittests/Basic/SarifTest.cpp

Index: clang/unittests/Basic/SarifTest.cpp
===
--- clang/unittests/Basic/SarifTest.cpp
+++ clang/unittests/Basic/SarifTest.cpp
@@ -7,7 +7,6 @@
 //===--===//
 
 #include "clang/Basic/Sarif.h"
-#include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
@@ -33,9 +32,9 @@
 
 static std::string serializeSarifDocument(llvm::json::Object &) {
   std::string Output;
-  llvm::json::Value value(std::move(Doc));
+  llvm::json::Value Value(std::move(Doc));
   llvm::raw_string_ostream OS{Output};
-  OS << llvm::formatv("{0}", value);
+  OS << llvm::formatv("{0}", Value);
   OS.flush();
   return Output;
 }
@@ -86,7 +85,7 @@
   const llvm::json::Object  = Writer.createDocument();
   std::vector Keys(EmptyDoc.size());
   std::transform(EmptyDoc.begin(), EmptyDoc.end(), Keys.begin(),
- [](auto item) { return item.getFirst(); });
+ [](auto Item) { return Item.getFirst(); });
 
   // THEN:
   ASSERT_THAT(Keys, testing::UnorderedElementsAre("$schema", "version"));
@@ -113,17 +112,17 @@
   ASSERT_EQ(Runs->size(), 1UL);
 
   // The tool associated with the run was the tool
-  const llvm::json::Object *driver =
+  const llvm::json::Object *Driver =
   Runs->begin()->getAsObject()->getObject("tool")->getObject("driver");
-  ASSERT_THAT(driver, testing::NotNull());
+  ASSERT_THAT(Driver, testing::NotNull());
 
-  ASSERT_TRUE(driver->getString("name").has_value());
-  ASSERT_TRUE(driver->getString("fullName").has_value());
-  ASSERT_TRUE(driver->getString("language").has_value());
+  ASSERT_TRUE(Driver->getString("name").has_value());
+  ASSERT_TRUE(Driver->getString("fullName").has_value());
+  ASSERT_TRUE(Driver->getString("language").has_value());
 
-  EXPECT_EQ(driver->getString("name").value(), ShortName);
-  EXPECT_EQ(driver->getString("fullName").value(), LongName);
-  EXPECT_EQ(driver->getString("language").value(), "en-US");
+  EXPECT_EQ(Driver->getString("name").value(), ShortName);
+  EXPECT_EQ(Driver->getString("fullName").value(), LongName);
+  EXPECT_EQ(Driver->getString("language").value(), "en-US");
 }
 
 TEST_F(SarifDocumentWriterTest, addingResultsWillCrashIfThereIsNoRun) {
@@ -147,6 +146,47 @@
   ASSERT_DEATH(Writer.appendResult(EmptyResult), Matcher);
 }
 
+TEST_F(SarifDocumentWriterTest, settingInvalidRankWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A SarifReportingConfiguration is created with an invalid "rank"
+  // * Ranks below 0.0 are invalid
+  // * Ranks above 100.0 are invalid
+
+  // THEN: The builder will crash in either case
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(-1.0),
+   ::testing::HasSubstr("Rule rank cannot be smaller than 0.0"));
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(101.0),
+   ::testing::HasSubstr("Rule rank cannot be larger than 100.0"));
+}
+
+TEST_F(SarifDocumentWriterTest, creatingResultWithDisabledRuleWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A disabled Rule is created, and a result is create referencing this rule
+  const auto  = SarifReportingConfiguration::create().disable();
+  auto RuleIdx =
+  Writer.createRule(SarifRule::create().setDefaultConfiguration(Config));
+  const SarifResult  = SarifResult::create(RuleIdx);
+
+  // THEN:
+  // SarifResult::create(...) will produce a crash
+  ASSERT_DEATH(
+  Writer.appendResult(Result),
+  ::testing::HasSubstr("Cannot add a result referencing a disabled Rule"));
+}
+
 // Test adding rule and result shows up in the final document
 TEST_F(SarifDocumentWriterTest, addingResultWithValidRuleAndRunIsOk) {
   // GIVEN:
@@ -160,9 +200,9 @@
   // WHEN:
   Writer.createRun("sarif test", "sarif test runner");
   unsigned RuleIdx = Writer.createRule(Rule);
-  const SarifResult  = SarifResult::create(RuleIdx);
+  const SarifResult  = SarifResult::create(RuleIdx);
 
-  Writer.appendResult(result);
+  Writer.appendResult(Result);
   const llvm::json::Object  = Writer.createDocument();
 
   // THEN:
@@ -199,10 +239,10 @@
   EXPECT_TRUE(Artifacts->empty());
 }
 
-TEST_F(SarifDocumentWriterTest, 

[PATCH] D131298: [clang-doc] Read docstrings for record members

2022-08-10 Thread Brett Wilson via Phabricator via cfe-commits
brettw updated this revision to Diff 451632.
brettw added a comment.

New patch up.


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

https://reviews.llvm.org/D131298

Files:
  clang-tools-extra/clang-doc/BitcodeReader.cpp
  clang-tools-extra/clang-doc/BitcodeWriter.cpp
  clang-tools-extra/clang-doc/Representation.h
  clang-tools-extra/clang-doc/Serialize.cpp
  clang-tools-extra/clang-doc/YAMLGenerator.cpp
  clang-tools-extra/unittests/clang-doc/BitcodeTest.cpp
  clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
  clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
  clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp

Index: clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
+++ clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
@@ -83,6 +83,19 @@
 
   I.Members.emplace_back("int", "path/to/int", "X",
  AccessSpecifier::AS_private);
+
+  // Member documentation.
+  CommentInfo TopComment;
+  TopComment.Kind = "FullComment";
+  TopComment.Children.emplace_back(std::make_unique());
+  CommentInfo *Brief = TopComment.Children.back().get();
+  Brief->Kind = "ParagraphComment";
+  Brief->Children.emplace_back(std::make_unique());
+  Brief->Children.back()->Kind = "TextComment";
+  Brief->Children.back()->Name = "ParagraphComment";
+  Brief->Children.back()->Text = "Value of the thing.";
+  I.Members.back().Description.push_back(std::move(TopComment));
+
   I.TagType = TagTypeKind::TTK_Class;
   I.Bases.emplace_back(EmptySID, "F", "path/to/F", true,
AccessSpecifier::AS_public, true);
@@ -129,6 +142,14 @@
   Path:'path/to/int'
 Name:'X'
 Access:  Private
+Description:
+  - Kind:'FullComment'
+Children:
+  - Kind:'ParagraphComment'
+Children:
+  - Kind:'TextComment'
+Text:'Value of the thing.'
+Name:'ParagraphComment'
 Bases:
   - USR: ''
 Name:'F'
Index: clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
+++ clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
@@ -80,6 +80,26 @@
   ASSERT_EQ(NumExpectedInfos, EmittedInfos.size());
 }
 
+// Constructs a comment definition as the parser would for one comment line.
+/* TODO uncomment this when the missing comment is fixed in emitRecordInfo and
+   the code that calls this is re-enabled.
+CommentInfo MakeOneLineCommentInfo(const std::string ) {
+  CommentInfo TopComment;
+  TopComment.Kind = "FullComment";
+  TopComment.Children.emplace_back(std::make_unique());
+
+  CommentInfo *Brief = TopComment.Children.back().get();
+  Brief->Kind = "ParagraphComment";
+
+  Brief->Children.emplace_back(std::make_unique());
+  Brief->Children.back()->Kind = "TextComment";
+  Brief->Children.back()->Name = "ParagraphComment";
+  Brief->Children.back()->Text = Text;
+
+  return TopComment;
+}
+*/
+
 // Test serialization of namespace declarations.
 TEST(SerializeTest, emitNamespaceInfo) {
   EmittedInfoList Infos;
@@ -124,6 +144,9 @@
   ExtractInfosFromCode(R"raw(class E {
 public:
   E() {}
+
+  // Some docs.
+  int value;
 protected:
   void ProtectedMethod();
 };
@@ -142,6 +165,9 @@
InfoType::IT_namespace);
   ExpectedE.TagType = TagTypeKind::TTK_Class;
   ExpectedE.DefLoc = Location(0, llvm::SmallString<16>{"test.cpp"});
+  ExpectedE.Members.emplace_back("int", "value", AccessSpecifier::AS_public);
+  // TODO the data member should have the docstring on it:
+  //ExpectedE.Members.back().Description.push_back(MakeOneLineCommentInfo(" Some docs"));
   CheckRecordInfo(, E);
 
   RecordInfo *RecordWithEConstructor = InfoAsRecord(Infos[2].get());
Index: clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
+++ clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
@@ -34,7 +34,12 @@
   return static_cast(I);
 }
 
-void CheckCommentInfo(CommentInfo , CommentInfo ) {
+void CheckCommentInfo(const std::vector ,
+  const std::vector );
+void CheckCommentInfo(const std::vector> ,
+  const std::vector> );
+
+void CheckCommentInfo(const CommentInfo , const CommentInfo ) {
   EXPECT_EQ(Expected.Kind, Actual.Kind);
   EXPECT_EQ(Expected.Text, Actual.Text);
   EXPECT_EQ(Expected.Name, Actual.Name);
@@ -56,9 +61,21 @@
   for (size_t Idx = 0; Idx < Actual.Args.size(); ++Idx)
 EXPECT_EQ(Expected.Args[Idx], Actual.Args[Idx]);
 
-  ASSERT_EQ(Expected.Children.size(), 

[PATCH] D131438: [clang][dataflow] Analyze constructor bodies

2022-08-10 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

Sorry but I had to revert this because of the conflicts with another revert: 
https://reviews.llvm.org/D131065


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131438

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


[PATCH] D131065: [clang][dataflow] Store DeclContext of block being analysed in Environment if available.

2022-08-10 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

Reverted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131065

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


[clang] 8d3c960 - Revert "[clang][dataflow] Store DeclContext of block being analysed in Environment if available."

2022-08-10 Thread Evgenii Stepanov via cfe-commits

Author: Evgenii Stepanov
Date: 2022-08-10T14:22:04-07:00
New Revision: 8d3c9602959df4caadfade1f40512231f7d6bbe8

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

LOG: Revert "[clang][dataflow] Store DeclContext of block being analysed in 
Environment if available."

Use of uninitialized memory.
https://lab.llvm.org/buildbot/#/builders/74/builds/12713

This reverts commit 8a4c40bfe8e6605ffc9d866f8620618dfdde2875.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 1b154010bf365..fc43b6b43575f 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -347,13 +347,6 @@ class Environment {
   /// imply that `Val` is true.
   bool flowConditionImplies(BoolValue ) const;
 
-  /// Returns the `DeclContext` of the block being analysed, if any. Otherwise,
-  /// returns null.
-  const DeclContext *getDeclCtx() { return DeclCtx; }
-
-  /// Sets the `DeclContext` of the block being analysed.
-  void setDeclCtx(const DeclContext *Ctx) { DeclCtx = Ctx; }
-
   /// Returns the `ControlFlowContext` registered for `F`, if any. Otherwise,
   /// returns null.
   const ControlFlowContext *getControlFlowContext(const FunctionDecl *F) {
@@ -384,9 +377,6 @@ class Environment {
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;
 
-  // `DeclContext` of the block being analysed if provided.
-  const DeclContext *DeclCtx;
-
   // In a properly initialized `Environment`, `ReturnLoc` should only be null 
if
   // its `DeclContext` could not be cast to a `FunctionDecl`.
   StorageLocation *ReturnLoc = nullptr;

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 16c83cad9d9e3..ff27a2a45179b 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -154,7 +154,7 @@ Environment::Environment(DataflowAnalysisContext )
 : DACtx(), FlowConditionToken(()) {}
 
 Environment::Environment(const Environment )
-: DACtx(Other.DACtx), DeclCtx(Other.DeclCtx), ReturnLoc(Other.ReturnLoc),
+: DACtx(Other.DACtx), ReturnLoc(Other.ReturnLoc),
   ThisPointeeLoc(Other.ThisPointeeLoc), DeclToLoc(Other.DeclToLoc),
   ExprToLoc(Other.ExprToLoc), LocToVal(Other.LocToVal),
   MemberLocToStruct(Other.MemberLocToStruct),
@@ -168,11 +168,9 @@ Environment ::operator=(const Environment 
) {
 }
 
 Environment::Environment(DataflowAnalysisContext ,
- const DeclContext )
+ const DeclContext )
 : Environment(DACtx) {
-  setDeclCtx();
-
-  if (const auto *FuncDecl = dyn_cast(DeclCtx)) {
+  if (const auto *FuncDecl = dyn_cast()) {
 assert(FuncDecl->getBody() != nullptr);
 initGlobalVars(*FuncDecl->getBody(), *this);
 for (const auto *ParamDecl : FuncDecl->parameters()) {
@@ -187,7 +185,7 @@ Environment::Environment(DataflowAnalysisContext ,
 ReturnLoc = (ReturnType);
   }
 
-  if (const auto *MethodDecl = dyn_cast(DeclCtx)) {
+  if (const auto *MethodDecl = dyn_cast()) {
 auto *Parent = MethodDecl->getParent();
 assert(Parent != nullptr);
 if (Parent->isLambda())
@@ -212,9 +210,6 @@ Environment Environment::pushCall(const CallExpr *Call) 
const {
 
   const auto *FuncDecl = Call->getDirectCallee();
   assert(FuncDecl != nullptr);
-
-  Env.setDeclCtx(FuncDecl);
-
   // FIXME: In order to allow the callee to reference globals, we probably need
   // to call `initGlobalVars` here in some way.
 
@@ -257,12 +252,12 @@ Environment Environment::pushCall(const CallExpr *Call) 
const {
 
 void Environment::popCall(const Environment ) {
   // We ignore `DACtx` because it's already the same in both. We don't want the
-  // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
-  // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze 
the
-  // same callee in a 
diff erent context, and `setStorageLocation` requires there
-  // to not already be a storage location assigned. Conceptually, these maps
-  // capture information from the local scope, so when popping that scope, we 
do
-  // not propagate the maps.
+  // callee's `ReturnLoc` or `ThisPointeeLoc`. We don't bring back `DeclToLoc`
+  // and `ExprToLoc` because we want to be able to later analyze the same 
callee
+  // in a 
diff erent context, and `setStorageLocation` requires there to not
+  // already be a 

[clang] 7587065 - Revert "[clang][dataflow] Analyze constructor bodies"

2022-08-10 Thread Evgenii Stepanov via cfe-commits

Author: Evgenii Stepanov
Date: 2022-08-10T14:21:56-07:00
New Revision: 75870650433de9e7bfbe86adc1bef2f2a23fe7a3

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

LOG: Revert "[clang][dataflow] Analyze constructor bodies"

https://lab.llvm.org/buildbot/#/builders/74/builds/12713

This reverts commit 000c8fef86abb7f056cbea2de99f21dca4b81bf8.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 8c169005846ef..1b154010bf365 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -135,7 +135,7 @@ class Environment {
   ///
   /// Requirements:
   ///
-  ///  The callee of `Call` must be a `FunctionDecl`.
+  ///  The callee of `Call` must be a `FunctionDecl` with a body.
   ///
   ///  The body of the callee must not reference globals.
   ///
@@ -143,7 +143,6 @@ class Environment {
   ///
   ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
-  Environment pushCall(const CXXConstructExpr *Call) const;
 
   /// Moves gathered information back into `this` from a `CalleeEnv` created 
via
   /// `pushCall`.
@@ -382,12 +381,6 @@ class Environment {
   StorageLocation (StorageLocation , SkipPast SP) const;
   const StorageLocation (const StorageLocation , SkipPast SP) const;
 
-  /// Shared implementation of `pushCall` overloads. Note that unlike
-  /// `pushCall`, this member is invoked on the environment of the callee, not
-  /// of the caller.
-  void pushCallInternal(const FunctionDecl *FuncDecl,
-ArrayRef Args);
-
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index e4af68e53e14e..16c83cad9d9e3 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -207,68 +207,52 @@ Environment::Environment(DataflowAnalysisContext ,
 
 Environment Environment::pushCall(const CallExpr *Call) const {
   Environment Env(*this);
-
   // FIXME: Support references here.
-  Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
-
-  if (const auto *MethodCall = dyn_cast(Call)) {
-if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
-  Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
-}
-  }
-
-  Env.pushCallInternal(Call->getDirectCallee(),
-   llvm::makeArrayRef(Call->getArgs(), 
Call->getNumArgs()));
+  Env.ReturnLoc = Env.getStorageLocation(*Call, SkipPast::Reference);
 
-  return Env;
-}
-
-Environment Environment::pushCall(const CXXConstructExpr *Call) const {
-  Environment Env(*this);
-
-  // FIXME: Support references here.
-  Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
+  const auto *FuncDecl = Call->getDirectCallee();
+  assert(FuncDecl != nullptr);
 
-  Env.ThisPointeeLoc = Env.ReturnLoc;
-
-  Env.pushCallInternal(Call->getConstructor(),
-   llvm::makeArrayRef(Call->getArgs(), 
Call->getNumArgs()));
-
-  return Env;
-}
-
-void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
-   ArrayRef Args) {
-  setDeclCtx(FuncDecl);
+  Env.setDeclCtx(FuncDecl);
 
   // FIXME: In order to allow the callee to reference globals, we probably need
   // to call `initGlobalVars` here in some way.
 
+  if (const auto *MethodCall = dyn_cast(Call)) {
+if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
+  Env.ThisPointeeLoc = Env.getStorageLocation(*Arg, SkipPast::Reference);
+}
+  }
+
   auto ParamIt = FuncDecl->param_begin();
+  auto ArgIt = Call->arg_begin();
+  auto ArgEnd = Call->arg_end();
 
   // FIXME: Parameters don't always map to arguments 1:1; examples include
   // overloaded operators implemented as member functions, and parameter packs.
-  for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
+  for (; ArgIt != ArgEnd; ++ParamIt, ++ArgIt) {
 assert(ParamIt != FuncDecl->param_end());
 
-const Expr *Arg = Args[ArgIndex];
-auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
+const Expr *Arg = *ArgIt;
+auto *ArgLoc = Env.getStorageLocation(*Arg, SkipPast::Reference);
 

[clang] 26089d4 - Revert "[clang][dataflow] Don't crash when caller args are missing storage locations"

2022-08-10 Thread Evgenii Stepanov via cfe-commits

Author: Evgenii Stepanov
Date: 2022-08-10T14:21:46-07:00
New Revision: 26089d4da489dc17711213f917779e480a78ed51

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

LOG: Revert "[clang][dataflow] Don't crash when caller args are missing storage 
locations"

https://lab.llvm.org/buildbot/#/builders/74/builds/12713

This reverts commit 43b298ea1282f29d448fc0f6ca971bc5fa698355.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index b3bc52a79a2fc..8c169005846ef 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,6 +140,8 @@ class Environment {
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
+  ///
+  ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
   Environment pushCall(const CXXConstructExpr *Call) const;
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 119ef337c6319..e4af68e53e14e 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,8 +253,7 @@ void Environment::pushCallInternal(const FunctionDecl 
*FuncDecl,
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-if (ArgLoc == nullptr)
-  continue;
+assert(ArgLoc != nullptr);
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 0e33df3a38008..af06021abccfd 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,27 +4229,6 @@ TEST(TransferTest, ContextSensitiveReturnArg) {
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
-TEST(TransferTest, ContextSensitiveReturnInt) {
-  std::string Code = R"(
-int identity(int x) { return x; }
-
-void target() {
-  int y = identity(42);
-  // [[p]]
-}
-  )";
-  runDataflow(Code,
-  [](llvm::ArrayRef<
- std::pair>>
- Results,
- ASTContext ) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-// This just tests that the analysis doesn't crash.
-  },
-  {/*.ApplyBuiltinTransfer=*/true,
-   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
-}
-
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {



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


[PATCH] D131065: [clang][dataflow] Store DeclContext of block being analysed in Environment if available.

2022-08-10 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

MSan is not happy:
https://lab.llvm.org/buildbot/#/builders/74/builds/12717


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131065

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


[PATCH] D131091: [clang][index] Index unresolved member expression as reference

2022-08-10 Thread Denis Fatkulin via Phabricator via cfe-commits
denis-fatkulin updated this revision to Diff 451624.
denis-fatkulin added a comment.

Broken tests are deleted


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131091

Files:
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/lib/Index/IndexBody.cpp
  clang/test/Index/Core/index-dependent-source.cpp


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | 
c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# 
|  | Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# |  | Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131351: [C] Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D131351#3714062 , @nikic wrote:

> This seems to break the test-suite build:
>
>   FAILED: CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o 
>   /root/llvm-compile-time-tracker/llvm-test-suite-build/tools/timeit 
> --summary CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o.time 
> /root/llvm-compile-time-tracker/llvm-project-build/bin/clang -DNDEBUG  
> -fexperimental-new-pass-manager -O0 -g   -w -Werror=date-time -DHAVE_CONFIG_H 
> -I/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV 
> -I/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/zlib 
> -DDONT_LOCK_DBDIRS -DC_LINUX -DFPU_WORDS_BIGENDIAN=0 -DWORDS_BIGENDIAN=0 -MD 
> -MT CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o -MF 
> CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o.d -o 
> CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o   -c 
> /root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/libclamav_readdb.c
>   
> /root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/libclamav_readdb.c:1145:49:
>  error: incompatible function pointer types passing 'int (const struct dirent 
> *, const struct dirent *)' to parameter of type '__compar_fn_t' (aka 'int 
> (*)(const void *, const void *)') [-Wincompatible-function-pointer-types]
>   qsort(dents, ndents, sizeof(struct dirent), dirent_compare);
>   ^~
>   /usr/include/stdlib.h:831:20: note: passing argument to parameter 
> '__compar' here
>  __compar_fn_t __compar) __nonnull ((1, 4));
>^
>   1 error generated.

Thanks, I'll try to take care of this shortly!

> Is it intentional that this generates an error for benign differences (in 
> pointer types only)?

Yes, it's still UB.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131351

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


[PATCH] D131351: [C] Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

This seems to break the test-suite build:

  FAILED: CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o 
  /root/llvm-compile-time-tracker/llvm-test-suite-build/tools/timeit --summary 
CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o.time 
/root/llvm-compile-time-tracker/llvm-project-build/bin/clang -DNDEBUG  
-fexperimental-new-pass-manager -O0 -g   -w -Werror=date-time -DHAVE_CONFIG_H 
-I/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV 
-I/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/zlib 
-DDONT_LOCK_DBDIRS -DC_LINUX -DFPU_WORDS_BIGENDIAN=0 -DWORDS_BIGENDIAN=0 -MD 
-MT CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o -MF 
CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o.d -o 
CTMark/ClamAV/CMakeFiles/clamscan.dir/libclamav_readdb.c.o   -c 
/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/libclamav_readdb.c
  
/root/llvm-compile-time-tracker/llvm-test-suite/CTMark/ClamAV/libclamav_readdb.c:1145:49:
 error: incompatible function pointer types passing 'int (const struct dirent 
*, const struct dirent *)' to parameter of type '__compar_fn_t' (aka 'int 
(*)(const void *, const void *)') [-Wincompatible-function-pointer-types]
  qsort(dents, ndents, sizeof(struct dirent), dirent_compare);
  ^~
  /usr/include/stdlib.h:831:20: note: passing argument to parameter '__compar' 
here
 __compar_fn_t __compar) __nonnull ((1, 4));
   ^
  1 error generated.

Is it intentional that this generates an error for benign differences (in 
pointer types only)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131351

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

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

Depends On D131614 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h

Index: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
===
--- clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
+++ clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
@@ -24,6 +24,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "llvm/ADT/StringRef.h"
 #include 
@@ -31,6 +32,8 @@
 #include 
 #include 
 
+// TODO: add tests and documentation
+
 namespace clang {
 namespace dataflow {
 
@@ -44,59 +47,45 @@
   Environment 
 };
 
-/// Matches against `Stmt` and, based on its structure, dispatches to an
-/// appropriate handler.
+template  using MatcherT = ast_matchers::internal::Matcher;
+
+template 
+using ActionT = std::function;
+
+template 
+using ASTMatchSwitch =
+std::function;
+
 template 
-using MatchSwitch = std::function;
-
-/// Collects cases of a "match switch": a collection of matchers paired with
-/// callbacks, which together define a switch that can be applied to a
-/// `Stmt`. This structure can simplify the definition of `transfer` functions
-/// that rely on pattern-matching.
-///
-/// For example, consider an analysis that handles particular function calls. It
-/// can define the `MatchSwitch` once, in the constructor of the analysis, and
-/// then reuse it each time that `transfer` is called, with a fresh state value.
-///
-/// \code
-/// MatchSwitch BuildSwitch() {
-///   return MatchSwitchBuilder>()
-/// .CaseOf(callExpr(callee(functionDecl(hasName("foo", TransferFooCall)
-/// .CaseOf(callExpr(argumentCountIs(2),
-///  callee(functionDecl(hasName("bar",
-/// TransferBarCall)
-/// .Build();
-/// }
-/// \endcode
-template  class MatchSwitchBuilder {
+using CFGMatchSwitch =
+std::function;
+
+// Alias for the previous implementation under the name of `MatchSwitch`.
+template 
+using MatchSwitch = ASTMatchSwitch;
+
+template 
+class ASTMatchSwitchBuilder {
 public:
-  /// Registers an action that will be triggered by the match of a pattern
-  /// against the input statement.
-  ///
-  /// Requirements:
-  ///
-  ///  `Node` should be a subclass of `Stmt`.
-  template 
-  MatchSwitchBuilder &&
-  CaseOf(ast_matchers::internal::Matcher M,
- std::function
- A) && {
-Matchers.push_back(std::move(M));
-Actions.push_back(
-[A = std::move(A)](const Stmt *Stmt,
-   const ast_matchers::MatchFinder::MatchResult ,
-   State ) { return A(cast(Stmt), R, S); });
+  template 
+  ASTMatchSwitchBuilder CaseOf(MatcherT Matcher,
+   ActionT Action) {
+Matchers.push_back(std::move(Matcher));
+Actions.push_back([A = std::move(Action)](
+  const BaseT *Node,
+  const ast_matchers::MatchFinder::MatchResult ,
+  State ) { return A(cast(Node), R, S); });
 return std::move(*this);
   }
 
-  MatchSwitch Build() && {
+  ASTMatchSwitch Build() {
 return [Matcher = BuildMatcher(), Actions = std::move(Actions)](
-   const Stmt , ASTContext , State ) -> Result {
-  auto Results = ast_matchers::matchDynamic(Matcher, Stmt, Context);
-  if (Results.empty())
+   const BaseT , ASTContext , State ) -> Result {
+  auto Results = ast_matchers::matchDynamic(Matcher, Node, Context);
+  if (Results.empty()) {
 return Result();
+  }
   // Look through the map for the first binding of the form "TagN..." use
   // that to select the action.
   for (const auto  : Results[0].getMap()) {
@@ -105,7 +94,7 @@
 if (ID.consume_front("Tag") && !ID.getAsInteger(10, Index) &&
 Index < Actions.size()) {
   return Actions[Index](
-  ,
+  ,
   ast_matchers::MatchFinder::MatchResult(Results[0], ), S);
 }
   }
@@ -137,15 +126,59 @@
 // The matcher type on the cases ensures that `Expr` kind is compatible with
 // all of the matchers.
 return DynTypedMatcher::constructVariadic(
-DynTypedMatcher::VO_AnyOf, ASTNodeKind::getFromNodeKind(),
+DynTypedMatcher::VO_AnyOf, ASTNodeKind::getFromNodeKind(),
 std::move(Matchers));
   }
 
+public:
   std::vector Matchers;
-  std::vector>
-  Actions;
+  std::vector> Actions;
 };
+
+// Alias 

[PATCH] D125418: [Arm64EC 6/?] Implement C/C++ mangling for Arm64EC function definitions.

2022-08-10 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5128
+// to the function itself; it points to a stub for the compiler.
+// FIXME: We also need to emit an entry thunk.
+SmallString<256> MangledName;

bcl5980 wrote:
> efriedma wrote:
> > bcl5980 wrote:
> > > A headache thing here.
> > > We need to get the function definition with triple x64 to define entry 
> > > thunk. For now the function definition here is aarch64 version.
> > > For example the case in Microsoft doc "Understanding Arm64EC ABI and 
> > > assembly code":
> > > 
> > > ```
> > > struct SC {
> > > char a;
> > > char b;
> > > char c;
> > > };
> > > int fB(int a, double b, int i1, int i2, int i3);
> > > int fC(int a, struct SC c, int i1, int i2, int i3);
> > > int fA(int a, double b, struct SC c, int i1, int i2, int i3) {
> > > return fB(a, b, i1, i2, i3) + fC(a, c, i1, i2, i3);
> > > }
> > > ```
> > > 
> > > x64 version IR for fA is:
> > > ```
> > > define dso_local i32 @fA(i32 noundef %a, double noundef %b, ptr nocapture 
> > > noundef readonly %c, i32 noundef %i1, i32 noundef %i2, i32 noundef %i3) 
> > > local_unnamed_addr #0 { ... }
> > > ```
> > > aarch64 version IR for fA is:
> > > 
> > > ```
> > > define dso_local i32 @"#fA"(i32 noundef %a, double noundef %b, i64 
> > > %c.coerce, i32 noundef %i1, i32 noundef %i2, i32 noundef %i3) #0 {...}
> > > ```
> > > Arm64 will allow any size structure to be assigned to a register 
> > > directly. x64 only allows sizes 1, 2, 4 and 8. 
> > > Entry thunk follow x64 version function type. But we only have aarch64 
> > > version function type.
> > > 
> > > I think the best way to do is create a x64 version codeGenModule and use 
> > > the x64 CGM to generate the function type for entry thunk. But it is hard 
> > > for me to do here. I tried a little but a lot of issues happen.
> > > 
> > > One other way is only modify `AArch64ABIInfo::classifyArgumentType`, copy 
> > > the x64 code into the function and add a flag to determine which version 
> > > will the function use. It is easier but I'm not sure it is the only 
> > > difference between x64 and aarch64. Maybe the classify return also need 
> > > to do this. And it is not a clean way I think.
> > Oh, that's annoying... I hadn't considered the case of a struct of size 
> > 3/5/6/7.
> > 
> > Like I noted on D126811, attaching thunks to calls is tricky if we try to 
> > do it from clang.
> > 
> > Computing the right IR type shouldn't be that hard by itself; we can call 
> > into call lowering code in TargetInfo without modifying much else.  (We 
> > just need a bit to tell the TargetInfo to redirect the call, like D125419.  
> > Use an entry point like CodeGenTypes::arrangeCall.)  You don't need to mess 
> > with the type system or anything like that.
> > 
> > The problem is correctly representing the lowered call in IR; we really 
> > don't want to do lowering early because it will block optimizations.  I 
> > considered using an operand bundle; we can probably make that work, but 
> > it's complicated, and probably disables some optimizations.
> > 
> > I think the best thing we can do here is add an IR attribute to mark 
> > arguments which are passed directly on AArch64, but need to be passed 
> > indirectly for the x64 ABI.  Then AArch64Arm64ECCallLowering can check for 
> > the attribute and modify its behavior.  This isn't really clean in the 
> > sense that it's specific to the x64/aarch64 pair of calling conventions, 
> > but I think the alternative is worse.
> It looks not only 3/5/6/7, but also all size exclusive larger than 8 and less 
> than 16 are difference between x86 ABI and Aarch64 ABI.
> Maybe we can emit a function declaration here for the x86ABI thunk, then 
> define it in Arm64ECCallLowering.
> 
I think the sizes between 8 and 16 work correctly already?  All sizes greater 
than 8 are passed indirectly on x86, and the thunk generation code accounts for 
that.  But that's not really important for the general question.

We need to preserve the required semantics for both the AArch64 and x86 calling 
conventions.  There are basically the following possibilities:

- We compute the declaration of the thunk in the frontend, and attach it to the 
call with an operand bundle.  Like I mentioned, I don't want to go down this 
path: the operand bundle blocks optimizations, and it becomes more complicated 
for other code to generate arm64ec compatible calls.
- We don't compute the definition of the thunk in the frontend.  Given that, 
the only other way to attach the information we need to the call is to use 
attributes.  The simplest thing is probably to attach the attribute directly to 
the argument; name it "arm64ec-thunk-pass-indirect", or something like that.  
(I mean, we could compute the whole signature and stuff it into a string 
attribute, but that doesn't really seem like an improvement...)


Repository:
  rG LLVM Github Monorepo

CHANGES 

[PATCH] D131553: [analyzer] exploded-graph-rewriter: Fix python3 string encoding issues

2022-08-10 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Thanks for figuring all of this out! Looks great!

That's right, we can't and probably shouldn't test graphviz.




Comment at: clang/utils/analyzer/exploded-graph-rewriter.py:862
 fp.write(data)
-print('Done! Please remember to remove the file.')
 return filename

I think the reminder is still relevant. These files can be like 100mb in size, 
and now that they aren't in /tmp they aren't autocleaned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131553

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


[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-10 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
wyt 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/D131614

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.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
@@ -71,14 +71,22 @@
   std::vector> 
 };
 
+// TODO:  add example of annotated test code snippet
+//
+// Runs dataflow analysis (specified from `MakeAnalysis`) and the `PostVisit`
+// function (if provided) on the body of the function that matches
+// `TargetFuncMatcher` in code snippet `Code`. `VerifyResults` checks that the
+// results from the analysis matches the expectations (which can be specified by
+// annotations in the `Code`).
+// Requires: `AnalysisT` contains a type `Lattice`.
 template 
-llvm::Error checkDataflow(
+llvm::Error checkDataflowOnCFG(
 llvm::StringRef Code,
 ast_matchers::internal::Matcher TargetFuncMatcher,
 std::function MakeAnalysis,
-std::function
-PostVisitStmt,
+PostVisit,
 std::function VerifyResults, ArrayRef Args,
 const tooling::FileContentMappings  = {}) {
   llvm::Annotations AnnotatedCode(Code);
@@ -112,14 +120,15 @@
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
-  std::function
-  PostVisitStmtClosure = nullptr;
-  if (PostVisitStmt != nullptr) {
-PostVisitStmtClosure = [, ](
-   const CFGStmt ,
+  std::function
+  PostVisitClosure = nullptr;
+  if (PostVisit != nullptr) {
+PostVisitClosure =
+[, ](const CFGElement ,
const TypeErasedDataflowAnalysisState ) {
-  PostVisitStmt(Context, Stmt, State);
-};
+  PostVisit(Context, Element, State);
+};
   }
 
   llvm::Expected>
@@ -130,7 +139,7 @@
 
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(*CFCtx, Analysis, Env,
-   PostVisitStmtClosure);
+   PostVisitClosure);
   if (!MaybeBlockStates)
 return MaybeBlockStates.takeError();
   auto  = *MaybeBlockStates;
@@ -141,6 +150,32 @@
   return llvm::Error::success();
 }
 
+template 
+llvm::Error checkDataflow(
+llvm::StringRef Code,
+ast_matchers::internal::Matcher TargetFuncMatcher,
+std::function MakeAnalysis,
+std::function
+PostVisitStmt,
+std::function VerifyResults, ArrayRef Args,
+const tooling::FileContentMappings  = {}) {
+
+  std::function
+  PostVisit = nullptr;
+  if (PostVisitStmt != nullptr) {
+PostVisit = [](ASTContext , const CFGElement ,
+ const TypeErasedDataflowAnalysisState ) {
+  if (Element.getKind() == CFGElement::Statement) {
+PostVisitStmt(Context, *Element.getAs(), State);
+  }
+};
+  }
+  return checkDataflowOnCFG(Code, TargetFuncMatcher, MakeAnalysis, PostVisit,
+VerifyResults, Args, VirtualMappedFiles);
+}
+
 // Runs dataflow on the body of the function that matches `TargetFuncMatcher` in
 // code snippet `Code`. Requires: `AnalysisT` contains a type `Lattice`.
 template 
@@ -157,9 +192,9 @@
 const tooling::FileContentMappings  = {}) {
   using StateT = DataflowAnalysisState;
 
-  return checkDataflow(
+  return checkDataflowOnCFG(
   Code, std::move(TargetFuncMatcher), std::move(MakeAnalysis),
-  /*PostVisitStmt=*/nullptr,
+  /*PostVisit=*/nullptr,
   [](AnalysisData AnalysisData) {
 if (AnalysisData.BlockStates.empty()) {
   VerifyResults({}, AnalysisData.ASTCtx);
@@ -180,9 +215,12 @@
   AnalysisData.CFCtx, AnalysisData.BlockStates, *Block,
   AnalysisData.Env, AnalysisData.Analysis,
   [,
-   ](const clang::CFGStmt ,
+   ](const clang::CFGElement ,
  const TypeErasedDataflowAnalysisState ) {
-auto It = Annotations.find(Stmt.getStmt());
+// FIXME: extend testing annotations to non statement constructs
+if (Element.getKind() != clang::CFGElement::Statement)
+  return;
+auto It = Annotations.find(Element.getAs()->getStmt());
 if (It == Annotations.end())
   return;
 auto *Lattice = llvm::any_cast(
Index: 

[PATCH] D126676: [clang] Disallow differences in defines used for creating and using PCH

2022-08-10 Thread Martin Storsjö via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc843c921a1a3: [clang] Require strict matches for defines for 
PCH in GCC style directories (authored by mstorsjo).

Changed prior to commit:
  https://reviews.llvm.org/D126676?vs=451434=451605#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126676

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/PCH/pch-dir.c

Index: clang/test/PCH/pch-dir.c
===
--- clang/test/PCH/pch-dir.c
+++ clang/test/PCH/pch-dir.c
@@ -6,7 +6,7 @@
 // RUN: %clang -x c++-header -std=c++98 %S/pch-dir.h -o %t.h.gch/cpp.gch 
 // RUN: %clang -include %t.h -DFOO=foo -fsyntax-only %s -Xclang -print-stats 2> %t.clog
 // RUN: FileCheck -check-prefix=CHECK-C %s < %t.clog
-// RUN: %clang -include %t.h -DFOO=bar -DBAR=bar -fsyntax-only %s -Xclang -ast-print > %t.cbarlog
+// RUN: %clang -include %t.h -DFOO=bar -fsyntax-only %s -Xclang -ast-print > %t.cbarlog
 // RUN: FileCheck -check-prefix=CHECK-CBAR %s < %t.cbarlog
 // RUN: %clang -x c++ -include %t.h -std=c++98 -fsyntax-only %s -Xclang -print-stats 2> %t.cpplog
 // RUN: FileCheck -check-prefix=CHECK-CPP %s < %t.cpplog
@@ -14,6 +14,11 @@
 // RUN: not %clang -x c++ -std=c++11 -include %t.h -fsyntax-only %s 2> %t.cpp11log
 // RUN: FileCheck -check-prefix=CHECK-NO-SUITABLE %s < %t.cpp11log
 
+// RUN: not %clang -include %t.h -fsyntax-only %s 2> %t.missinglog2
+// RUN: FileCheck -check-prefix=CHECK-NO-SUITABLE %s < %t.missinglog2
+// RUN: not %clang -include %t.h -DFOO=foo -DBAR=bar -fsyntax-only %s 2> %t.missinglog2
+// RUN: FileCheck -check-prefix=CHECK-NO-SUITABLE %s < %t.missinglog2
+
 // Don't crash if the precompiled header file is missing.
 // RUN: not %clang_cc1 -include-pch %t.h.gch -DFOO=baz -fsyntax-only %s -print-stats 2> %t.missinglog
 // RUN: FileCheck -check-prefix=CHECK-NO-SUITABLE %s < %t.missinglog
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -624,20 +624,28 @@
   }
 }
 
+enum OptionValidation {
+  OptionValidateNone,
+  OptionValidateContradictions,
+  OptionValidateStrictMatches,
+};
+
 /// Check the preprocessor options deserialized from the control block
 /// against the preprocessor options in an existing preprocessor.
 ///
 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
-/// \param Validate If true, validate preprocessor options. If false, allow
-///macros defined by \p ExistingPPOpts to override those defined by
-///\p PPOpts in SuggestedPredefines.
-static bool checkPreprocessorOptions(const PreprocessorOptions ,
- const PreprocessorOptions ,
- DiagnosticsEngine *Diags,
- FileManager ,
- std::string ,
- const LangOptions ,
- bool Validate = true) {
+/// \param Validation If set to OptionValidateNone, ignore differences in
+///preprocessor options. If set to OptionValidateContradictions,
+///require that options passed both in the AST file and on the command
+///line (-D or -U) match, but tolerate options missing in one or the
+///other. If set to OptionValidateContradictions, require that there
+///are no differences in the options between the two.
+static bool checkPreprocessorOptions(
+const PreprocessorOptions ,
+const PreprocessorOptions , DiagnosticsEngine *Diags,
+FileManager , std::string ,
+const LangOptions ,
+OptionValidation Validation = OptionValidateContradictions) {
   // Check macro definitions.
   MacroDefinitionsMap ASTFileMacros;
   collectMacroDefinitions(PPOpts, ASTFileMacros);
@@ -653,7 +661,15 @@
 // Check whether we know anything about this macro name or not.
 llvm::StringMap>::iterator Known =
 ASTFileMacros.find(MacroName);
-if (!Validate || Known == ASTFileMacros.end()) {
+if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
+  if (Validation == OptionValidateStrictMatches) {
+// If strict matches are requested, don't tolerate any extra defines on
+// the command line that are missing in the AST file.
+if (Diags) {
+  Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
+}
+return true;
+  }
   // FIXME: Check whether this identifier was referenced anywhere in the
   // AST file. If so, we should reject the AST file. Unfortunately, this
   // information isn't in the control block. What 

[clang] c843c92 - [clang] Require strict matches for defines for PCH in GCC style directories

2022-08-10 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-08-10T22:47:27+03:00
New Revision: c843c921a1a385bb805b2338d980436c94f83f19

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

LOG: [clang] Require strict matches for defines for PCH in GCC style directories

When clang includes a PCH, it tolerates some amount of differences
between the defines used when creating and when including the PCH
- this seems to be intentionally allowed in
c379c072405f39bca1d3552408fc0427328e8b6d (and later extended in
b63687519610a73dd565be1fec28332211b4df5b).

When using a PCH (or when picking a PCH out of a directory containing
multiple candidates) Clang used to accept the header if there were
defines on the command line when creating the PCH that are missing
when using the PCH, or vice versa, defines only set when using the
PCH.

The only cases where Clang explicitly rejected the use of a PCH
is if there was an explicit conflict between the options, e.g.
-DFOO=1 vs -DFOO=2, or -DFOO vs -UFOO.

The latter commit added a FIXME that we really should check whether
mismatched defines actually were used somewhere in the PCH, so that
the define would affect the outcome. This FIXME has stood unaddressed
since 2012.

This differs from GCC, which rejects PCH files if the defines differ
at all.

When explicitly including a single PCH file, the relaxed policy
of allowing minor differences is harmless for correct use cases
(but may fail to diagnose mismtaches), and potentially allow using
PCHs in wider cases (where the user intentionally know that the
differences in defines are harmless for the PCH).

However, for GCC style PCH directories, with a directory containing
multiple PCH variants and the compiler should pick the correct match
out of them, Clang's relaxed logic was problematic. The directory
could contain two otherwise identical PCHs, but one built with -DFOO
and one without. When attempting to include a PCH and iterating over
the candidates in the directory, Clang would essentially pick the
first one out of the two, even if there existed a better, exact
match in the directory.

Keep the relaxed checking when specificlly including one named
PCH file, but require strict matches when trying to pick the right
candidate out of a GCC style directory with alternatives.

This fixes https://github.com/lhmouse/mcfgthread/issues/63.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Serialization/ASTReader.h
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Serialization/ASTReader.cpp
clang/test/PCH/pch-dir.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a37120ba2d56c..3b1d2a412f459 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -89,6 +89,13 @@ Improvements to Clang's diagnostics
   language modes. It may be downgraded to a warning with
   ``-Wno-error=incompatible-function-pointer-types`` or disabled entirely with
   ``-Wno-implicit-function-pointer-types``.
+- When including a PCH from a GCC style directory with multiple alternative PCH
+  files, Clang now requires all defines set on the command line while 
generating
+  the PCH and when including it to match. This matches GCC's behaviour.
+  Previously Clang would tolerate defines to be set when creating the PCH but
+  missing when used, or vice versa. This makes sure that Clang picks the
+  correct one, where it previously would consider multiple ones as potentially
+  acceptable (and erroneously use whichever one is tried first).
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 7cdebefaf7a99..25b14f4dfa422 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1738,7 +1738,8 @@ class ASTReader
   const LangOptions ,
   const TargetOptions ,
   const PreprocessorOptions ,
-  StringRef ExistingModuleCachePath);
+  StringRef ExistingModuleCachePath,
+  bool RequireStrictOptionMatches = false);
 
   /// Returns the suggested contents of the predefines buffer,
   /// which contains a (typically-empty) subset of the predefines

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 7b07ab948f643..53cb48d2de9e6 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -772,7 +772,7 @@ bool 

[PATCH] D130363: [clang] Give priority to Class context while parsing declarations

2022-08-10 Thread Furkan via Phabricator via cfe-commits
furkanusta updated this revision to Diff 451604.
furkanusta added a comment.

- [clangd] D130363  
(CodeCompletion/overrides.cpp) Move tests to bottom


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130363

Files:
  clang/lib/Parse/ParseDecl.cpp
  clang/test/CodeCompletion/overrides.cpp


Index: clang/test/CodeCompletion/overrides.cpp
===
--- clang/test/CodeCompletion/overrides.cpp
+++ clang/test/CodeCompletion/overrides.cpp
@@ -31,3 +31,13 @@
 // CHECK-CC3-NOT: COMPLETION: Pattern : int ttt(bool param, int x = 3) const 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param, int p) 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param) override{{$}}
+
+void func() {
+  class D : public A {
+
+  };
+}
+
+// Runs completion at empty line on line 37.
+// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:37:1 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -3266,13 +3266,14 @@
 return;
   }
 
-  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
-CCC = Sema::PCC_LocalDeclarationSpecifiers;
-  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
+  // Class context can appear inside a function/block, so prioritise that.
+  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
 CCC = DSContext == DeclSpecContext::DSC_class ? 
Sema::PCC_MemberTemplate
   : Sema::PCC_Template;
   else if (DSContext == DeclSpecContext::DSC_class)
 CCC = Sema::PCC_Class;
+  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
+CCC = Sema::PCC_LocalDeclarationSpecifiers;
   else if (CurParsedObjCImpl)
 CCC = Sema::PCC_ObjCImplementation;
 


Index: clang/test/CodeCompletion/overrides.cpp
===
--- clang/test/CodeCompletion/overrides.cpp
+++ clang/test/CodeCompletion/overrides.cpp
@@ -31,3 +31,13 @@
 // CHECK-CC3-NOT: COMPLETION: Pattern : int ttt(bool param, int x = 3) const override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param) override{{$}}
+
+void func() {
+  class D : public A {
+
+  };
+}
+
+// Runs completion at empty line on line 37.
+// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:37:1 %s -o - | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -3266,13 +3266,14 @@
 return;
   }
 
-  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
-CCC = Sema::PCC_LocalDeclarationSpecifiers;
-  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
+  // Class context can appear inside a function/block, so prioritise that.
+  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
   : Sema::PCC_Template;
   else if (DSContext == DeclSpecContext::DSC_class)
 CCC = Sema::PCC_Class;
+  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
+CCC = Sema::PCC_LocalDeclarationSpecifiers;
   else if (CurParsedObjCImpl)
 CCC = Sema::PCC_ObjCImplementation;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128807: [clang][transformer] Finish plumbing `Note` all the way to the output.

2022-08-10 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128807

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


[PATCH] D131590: Fixed page title for abseil-no-internal-dependencies check documentation

2022-08-10 Thread Vladimir Plyashkun via Phabricator via cfe-commits
vladimir.plyashkun added a comment.

In D131590#3713731 , @njames93 wrote:

> Can this be backported as well.

I guess someone needs to do it, because i haven't got commit/write access in 
LLVM repository.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131590

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


[PATCH] D131388: [docs] Add "C++20 Modules"

2022-08-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

(I'll +1 to @ruoso's comments about using BMI - I think it might be best not to 
introduce a different term ("Module file") as it might confuse people as it's 
fairly close to "module source file", etc. BMI makes it clear/unambiguous that 
it's the binary file, not the source file)




Comment at: clang/docs/CPlusPlus20Modules.rst:665
+  # This is not allowed!
+  $ clang++ iostream.pcm -c -o iostream.o 
+

could this use a strikethrough, perhaps? (not sure if you can strikethrough 
inside a code block)



Comment at: clang/docs/CPlusPlus20Modules.rst:347
+  $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
+  $ rm -f M.cppm
+  $ clang++ -std=c++20 Use.cpp -fmodule-file=M.pcm

ChuanqiXu wrote:
> dblaikie wrote:
> > Could probably skip the `-f`?
> In my system, when I run `rm M.cppm`, it asks `rm: remove regular file 
> ‘M.cppm’?` and I need to enter `y` then it would remove the file actually. So 
> it looks better to add `-f` to me.
Perhaps your `rm` is aliased to `rm -i`? ( 
https://superuser.com/questions/345923/remove-file-without-asking ) - `rm` 
generally/without flags wouldn't prompt for removal of a writable file & 
encouraging people to get in the habit of using `-f` (especially when they 
probably don't need to - even if you do on your system) seems a bit 
problematic. I think not including the input/output of `rm` in case some users 
have it setup to require some interaction is OK - a plain `rm` is probably 
enough for users to understand what to do on their system.



Comment at: clang/docs/CPlusPlus20Modules.rst:395-396
+
+Roughly, this theory is correct. But the problem is that it is too rough. 
Let's see what actually happens.
+For example, the behavior also depends on the optimization level, as we will 
illustrate below.
+

ChuanqiXu wrote:
> dblaikie wrote:
> > I'm not sure I'm able to follow the example and how it justifies the rough 
> > theory as inadequate to explain the motivation for modules - could you 
> > clarify more directly (in comments, and then we can discuss how to word it) 
> > what the motivation for this section is/what you're trying to convey?
> Let me answer the motivation first. The motivation comes from my personal 
> experience. I feel like when most people heard modules, they would ask "how 
> much speedup could we get"? And there are some other questions like "why does 
> modules speedup the compilation?". So I guess the readers of the document may 
> have similar questions and I try to answer it here.
> 
> The complexity theory is correct but it may be too abstract to our users. 
> Since the complexity theory is about the scaling. But for certain users, the 
> scales of their codes are temporarily fixed. So when they try to use modules 
> but find the speedup doesn't meet their expectation in O2. They may feel 
> frustrated. And it doesn't work if I say, "hey, you'll get much better 
> speedup if the your codes get 10x longer." I guess they won't buy in. So what 
> I try to do here is to manage the user's expectation to avoid any 
> misunderstanding.
> 
> Following off is about the explanation. For example, there are `1` module 
> interface and `10` users. There is a function `F` in the module interface and 
> the function is used by every users. And let's say we need a `T` time to 
> compile the function `F` and each users without the function `F`.
> In O0, the function `F` will get compiled completely once and get involved in 
> the Sema part 10 times. Due to the Sema part is relatively fast and let's say 
> the Sema part would take `0.1T`. Given we compile them serially, we need 
> `12T` to compile the project.
> 
> But if we are with optimizations, each function `F` will get involved in 
> optimizations and IPO in every users. And these optimizations are most 
> time-consuming. Let's say these optimizations will consume `0.8T`. And the 
> time required will be `19T`. It is easy to say the we need `20T` to compile 
> the project if we're using headers. So we could find the speedup with 
> optimization is much slower.
> 
> BTW, if we write the required time with variables, it will be `nT + mT + 
> T*m*additional_compilation_part`. The `additional_compilation_part ` here 
> corresponds to the time percentage of `Sema` or `Optimizations`. And since 
> `T` and `additional_compilation_part ` are both constant. So if we write them 
> in `O()` form, it would be `O(n+m)`.
> So the theory is still correct.
> 
> 
I think the message is getting a bit lost in the text (both in the proposed 
text, and the comment here).

"At -O0 implementations of non-inline functions defined in a module will not 
impact module users, but at higher optimization levels the definitions of such 
functions are provided to user compilations for the purposes of optimization 
(but definitions of these functions are still not included in the use's object 
file) - this means 

[PATCH] D131420: [clang][deps] Always generate module paths

2022-08-10 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG71e32d5cf005: [clang][deps] Always generate module paths 
(authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D131420?vs=450887=451593#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131420

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/diagnostics.c
  clang/test/ClangScanDeps/generate-modules-path-args.c
  clang/test/ClangScanDeps/modulemap-via-vfs.m
  clang/test/ClangScanDeps/modules-context-hash-module-map-path.c
  clang/test/ClangScanDeps/modules-context-hash-outputs.c
  clang/test/ClangScanDeps/modules-context-hash.c
  clang/test/ClangScanDeps/modules-disable-free.c
  clang/test/ClangScanDeps/modules-file-path-isolation.c
  clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-inferred-explicit-build.m
  clang/test/ClangScanDeps/modules-inferred.m
  clang/test/ClangScanDeps/modules-no-undeclared-includes.c
  clang/test/ClangScanDeps/modules-pch-common-submodule.c
  clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
  clang/test/ClangScanDeps/modules-pch-dangling.c
  clang/test/ClangScanDeps/modules-pch.c
  clang/test/ClangScanDeps/modules-symlink.c
  clang/test/ClangScanDeps/removed-args.c
  clang/test/ClangScanDeps/submodule-order.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -138,36 +138,11 @@
 llvm::cl::init(ScanningOutputFormat::Make),
 llvm::cl::cat(DependencyScannerCategory));
 
-// This mode is mostly useful for development of explicitly built modules.
-// Command lines will contain arguments specifying modulemap file paths and
-// absolute paths to PCM files in the module cache directory.
-//
-// Build tools that want to put the PCM files in a different location should use
-// the C++ APIs instead, of which there are two flavors:
-//
-// 1. APIs that generate arguments with paths PCM files via a callback provided
-//by the client:
-// * ModuleDeps::getCanonicalCommandLine(LookupPCMPath)
-// * FullDependencies::getCommandLine(LookupPCMPath)
-//
-// 2. APIs that don't generate arguments with paths PCM files and instead expect
-// the client to append them manually after the fact:
-// * ModuleDeps::getCanonicalCommandLineWithoutModulePaths()
-// * FullDependencies::getCommandLineWithoutModulePaths()
-//
-static llvm::cl::opt GenerateModulesPathArgs(
-"generate-modules-path-args",
-llvm::cl::desc(
-"With '-format experimental-full', include arguments specifying "
-"modules-related paths in the generated command lines: "
-"'-fmodule-file=', '-o', '-fmodule-map-file='."),
-llvm::cl::init(false), llvm::cl::cat(DependencyScannerCategory));
-
 static llvm::cl::opt ModuleFilesDir(
 "module-files-dir",
-llvm::cl::desc("With '-generate-modules-path-args', paths to module files "
-   "in the generated command lines will begin with the "
-   "specified directory instead the module cache directory."),
+llvm::cl::desc(
+"The build directory for modules. Defaults to the value of "
+"'-fmodules-cache-path=' from command lines for implicit modules."),
 llvm::cl::cat(DependencyScannerCategory));
 
 static llvm::cl::opt OptimizeArgs(
@@ -198,8 +173,7 @@
 
 llvm::cl::list ModuleDepTargets(
 "dependency-target",
-llvm::cl::desc("With '-generate-modules-path-args', the names of "
-   "dependency targets for the dependency file"),
+llvm::cl::desc("The names of dependency targets for the dependency file"),
 llvm::cl::cat(DependencyScannerCategory));
 
 enum ResourceDirRecipeKind {
@@ -295,11 +269,9 @@
 }
 
 ID.CommandLine =
-GenerateModulesPathArgs
-? FD.getCommandLine([&](const ModuleID , ModuleOutputKind MOK) {
-return lookupModuleOutput(MID, MOK);
-  })
-: FD.getCommandLineWithoutModulePaths();
+FD.getCommandLine([&](const ModuleID , ModuleOutputKind MOK) {
+  return lookupModuleOutput(MID, MOK);
+});
 Inputs.push_back(std::move(ID));
   }
 
@@ -329,13 +301,10 @@
   {"file-deps", toJSONSorted(MD.FileDeps)},
   {"clang-module-deps", toJSONSorted(MD.ClangModuleDeps)},
   {"clang-modulemap-file", MD.ClangModuleMapFile},
-  {"command-line",
- 

[clang] 71e32d5 - [clang][deps] Always generate module paths

2022-08-10 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-08-10T11:58:28-07:00
New Revision: 71e32d5cf0053090aaad62d946fcfd00f1915f26

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

LOG: [clang][deps] Always generate module paths

Since D129389 (and downstream PR 
https://github.com/apple/llvm-project/pull/4965), the dependency scanner is 
responsible for generating full command-lines, including the modules paths. 
This patch removes the flag that was making this an opt-in behavior in 
clang-scan-deps.

Reviewed By: benlangmuir

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/diagnostics.c
clang/test/ClangScanDeps/generate-modules-path-args.c
clang/test/ClangScanDeps/modulemap-via-vfs.m
clang/test/ClangScanDeps/modules-context-hash-module-map-path.c
clang/test/ClangScanDeps/modules-context-hash-outputs.c
clang/test/ClangScanDeps/modules-context-hash.c
clang/test/ClangScanDeps/modules-disable-free.c
clang/test/ClangScanDeps/modules-file-path-isolation.c
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-inferred-explicit-build.m
clang/test/ClangScanDeps/modules-inferred.m
clang/test/ClangScanDeps/modules-no-undeclared-includes.c
clang/test/ClangScanDeps/modules-pch-common-submodule.c
clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
clang/test/ClangScanDeps/modules-pch-dangling.c
clang/test/ClangScanDeps/modules-pch.c
clang/test/ClangScanDeps/modules-symlink.c
clang/test/ClangScanDeps/removed-args.c
clang/test/ClangScanDeps/submodule-order.c
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index 0a092a433a22c..77263cd6233b8 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -53,9 +53,6 @@ struct FullDependencies {
   std::vector getCommandLine(
   llvm::function_ref
   LookupModuleOutput) const;
-
-  /// Get the full command line, excluding -fmodule-file=" arguments.
-  std::vector getCommandLineWithoutModulePaths() const;
 };
 
 struct FullDependenciesResult {

diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index f4f13a34b1746..18c342ee85c11 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -138,10 +138,6 @@ struct ModuleDeps {
   std::vector getCanonicalCommandLine(
   llvm::function_ref
   LookupModuleOutput) const;
-
-  /// Gets the canonical command line suitable for passing to clang, excluding
-  /// "-fmodule-file=" and "-o" arguments.
-  std::vector getCanonicalCommandLineWithoutModulePaths() const;
 };
 
 class ModuleDepCollector;

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 411fd9676ffdb..03ad6dcc51b30 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -16,24 +16,15 @@ using namespace dependencies;
 std::vector FullDependencies::getCommandLine(
 llvm::function_ref
 LookupModuleOutput) const {
-  std::vector Ret = getCommandLineWithoutModulePaths();
-
-  for (ModuleID MID : ClangModuleDeps) {
-auto PCM = LookupModuleOutput(MID, ModuleOutputKind::ModuleFile);
-Ret.push_back("-fmodule-file=" + PCM);
-  }
-
-  return Ret;
-}
-
-std::vector
-FullDependencies::getCommandLineWithoutModulePaths() const {
   std::vector Args = OriginalCommandLine;
 
   Args.push_back("-fno-implicit-modules");
   Args.push_back("-fno-implicit-module-maps");
   for (const PrebuiltModuleDep  : PrebuiltModuleDeps)
 Args.push_back("-fmodule-file=" + PMD.PCMFile);
+  for (ModuleID MID : ClangModuleDeps)
+Args.push_back("-fmodule-file=" +
+   LookupModuleOutput(MID, ModuleOutputKind::ModuleFile));
 
   // These arguments are unused in explicit compiles.
   llvm::erase_if(Args, [](StringRef Arg) {

diff  --git 

[PATCH] D131590: Fixed page title for abseil-no-internal-dependencies check documentation

2022-08-10 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.

Can this be backported as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131590

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


[PATCH] D131084: Add support for specifying the severity of a SARIF Result.

2022-08-10 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y added inline comments.



Comment at: clang/include/clang/Basic/Sarif.h:256
   std::string HelpURI;
+  SarifReportingConfiguration DefaultConfiguration;
 

Is this form preferred for expressing a statically known default value?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131084

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


[PATCH] D131464: [test] Make tests pass regardless of gnu++14/gnu++17 default

2022-08-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

It will take some time to fix all tests properly. Let's have a guideline how to 
fix them properly. I tried fixing some using several patterns in the last 
revision. I didn't fix all, because it would likely lead to an unsatisfactory 
result and I would spend more time :)

A construct which causes an error with C++17 onwards


I keep the existing `RUN:` lines and use something like

  #if __cplusplus < 201703L
  void* operator new[](std::size_t) throw(std::bad_alloc); 
  #endif

it the construct appears tested elsewhere or

  register int ro; // expected-error {{illegal storage class on file-scoped 
variable}}
  #if __cplusplus >= 201703L
  // expected-error@-2 {{ISO C++17 does not allow 'register' storage class 
specifier}}
  #elif __cplusplus >= 201103L
  // expected-warning@-4 {{'register' storage class specifier is deprecated}}
  #endif

if the test file appears the proper place to test the construct.

Pre-C++17 and C++17 have different results
--

I use something like

  // RUN: %clang_cc1 %s -fsyntax-only -verify=expected,precxx17 -std=c++14 
-fdata-sections -fcolor-diagnostics
  // RUN: %clang_cc1 %s -fsyntax-only -verify -std=c++17 -fdata-sections 
-fcolor-diagnostics
  
  ...
TypedefAligned4 TA8c = TA8a + TA8b;  // expected-warning {{passing 4-byte 
aligned argument to 8-byte aligned parameter 'this' of 'operator+' may result 
in an unaligned pointer access}}
 // expected-warning@-1 {{passing 
4-byte aligned argument to 8-byte aligned parameter 1 of 'operator+' may result 
in an unaligned pointer access}}
 // precxx17-warning@-2 {{passing 
4-byte aligned argument to 8-byte aligned parameter 'this' of 'StructAligned8' 
may result in an unaligned pointer access}}

Since every RUN line uses -std=.
Pros: using `-verify` avoids `#if` directives which make the result look better.
Cons: when we upgrade to C++20, 23, ..., the tests will become less relevant.

Discussion
--

Do we want to prefer `#if` in all cases? They work well with `-verify` tests 
but not so well with `FileCheck` since `FileCheck` does not ignore preprocessor 
skipped ranges.
Do all `CodeGenCXX` tests have to be fixed?




Comment at: clang/test/AST/ast-dump-undeduced-expr.cpp:1
-// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck 
%s
+// RUN: not %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown -ast-dump %s 
| FileCheck %s
 

aaron.ballman wrote:
> What from this test requires C++14?
The C++17 diagnostics uses `static inline constexpr` while pre-C++17 uses 
`static constexpr`. Used a regex instead.



Comment at: clang/test/AST/sourceranges.cpp:1-2
-// RUN: %clang_cc1 -triple i686-mingw32 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 -triple i686-mingw32 -ast-dump %s | FileCheck %s
 // RUN: %clang_cc1 -triple i686-mingw32 -std=c++1z -ast-dump %s | FileCheck %s 
-check-prefix=CHECK-1Z
 

aaron.ballman wrote:
> I assume this change is because we're testing c++17 on the next RUN line and 
> you want to be sure we still get the old test coverage?
> 
> The trouble is, when we bump from C++17 to C++20, we'll lose the test 
> coverage for the latest standard.
> 
> (Not your problem per se, but I continue to think we have a lit deficiency 
> where we need some facilities to say "run this test in C++N and later", "run 
> this test in C89 through CN", or "run this test in all C++ language modes", 
> etc.)
`FileCheck` does not ignore preprocessor skipped ranges, so it is very 
difficult to work with both C++14/C++17 defaults, if our intention is to not 
touch such tests in the default changing patch.

I think the best strategy is to do another pass to clean up the tests after the 
transition, not trying to address everything in this patch.



Comment at: clang/test/Analysis/blocks.m:2
 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 
-analyzer-checker=core -fblocks -verify -Wno-strict-prototypes %s
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 
-analyzer-checker=core -fblocks -verify -x objective-c++ %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 
-analyzer-checker=core -fblocks -verify -x objective-c++ -std=c++14 %s
 

aaron.ballman wrote:
> What from this test is invalid in C++17?
Added `__attribute__((__nothrow__))` in C++17 mode.



Comment at: clang/test/CXX/except/except.spec/p2-dynamic-types.cpp:1
-// RUN: %clang_cc1 -fexceptions -fcxx-exceptions -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fexceptions -fcxx-exceptions -fsyntax-only -verify 
-std=c++14 %s
 

aaron.ballman wrote:
> Why not pass `-Wno-dynamic-exception-spec` instead of limiting the test (we 
> support dynamic exception specifications in newer language modes and 

[PATCH] D131464: [test] Make tests pass regardless of gnu++14/gnu++17 default

2022-08-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 451586.
MaskRay marked 5 inline comments as done.
MaskRay edited the summary of this revision.
MaskRay added a comment.
Herald added subscribers: llvm-commits, delcypher.
Herald added a project: LLVM.

Add lit substitutions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131464

Files:
  clang/test/AST/ast-dump-openmp-begin-declare-variant_11.c
  clang/test/AST/ast-dump-openmp-begin-declare-variant_template_3.cpp
  clang/test/AST/ast-dump-undeduced-expr.cpp
  clang/test/AST/sourceranges.cpp
  clang/test/Analysis/blocks.m
  clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
  clang/test/CXX/basic/basic.stc/basic.stc.dynamic/p2.cpp
  clang/test/CXX/class.access/class.friend/p1.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.stc/p2.cpp
  clang/test/CXX/except/except.spec/p2-dynamic-types.cpp
  clang/test/CXX/except/except.spec/p9-dynamic.cpp
  clang/test/CXX/stmt.stmt/stmt.select/p3.cpp
  clang/test/CXX/temp/temp.arg/temp.arg.nontype/p1.cpp
  clang/test/CXX/temp/temp.res/temp.local/p3.cpp
  clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp
  clang/test/CodeGenCXX/align-avx-complete-objects.cpp
  clang/test/CodeGenCXX/copy-constructor-elim-2.cpp
  clang/test/CodeGenCXX/debug-info-template-parameter.cpp
  clang/test/CodeGenCXX/debug-info-template-partial-specialization.cpp
  clang/test/CodeGenCXX/exception-spec-decay.cpp
  clang/test/CodeGenCXX/exceptions-cxx-ehsc.cpp
  clang/test/CodeGenCXX/exceptions-no-rtti.cpp
  clang/test/CodeGenCXX/global-init.cpp
  clang/test/CodeGenCXX/no-exceptions.cpp
  clang/test/CodeGenCXX/override-bit-field-layout.cpp
  clang/test/CodeGenCXX/override-layout.cpp
  clang/test/CodeGenCXX/reference-temporary-ms.cpp
  clang/test/CodeGenCXX/rtti-linkage.cpp
  clang/test/Layout/ms-x86-vtordisp.cpp
  clang/test/Modules/update-exception-spec.cpp
  clang/test/OpenMP/declare_mapper_messages.cpp
  clang/test/PCH/cxx-functions.cpp
  clang/test/Parser/cxx-casting.cpp
  clang/test/Parser/cxx-class.cpp
  clang/test/Parser/cxx-template-argument.cpp
  clang/test/Parser/cxx-template-decl.cpp
  clang/test/Parser/cxx1z-nested-namespace-definition.cpp
  clang/test/Sema/ms_class_layout.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp
  clang/test/SemaCXX/PR12778.cpp
  clang/test/SemaCXX/altivec.cpp
  clang/test/SemaCXX/bool.cpp
  clang/test/SemaCXX/default2.cpp
  clang/test/SemaCXX/exception-spec-no-exceptions.cpp
  clang/test/SemaCXX/exceptions.cpp
  clang/test/SemaCXX/expressions.cpp
  clang/test/SemaCXX/inline.cpp
  clang/test/SemaCXX/libstdcxx_is_pod_hack.cpp
  clang/test/SemaCXX/linkage2.cpp
  clang/test/SemaCXX/member-pointer.cpp
  clang/test/SemaCXX/missing-namespace-qualifier-typo-corrections.cpp
  clang/test/SemaCXX/static-data-member.cpp
  clang/test/SemaCXX/type-definition-in-specifier.cpp
  clang/test/SemaCXX/user-defined-conversions.cpp
  clang/test/SemaCXX/warn-new-overaligned-3.cpp
  clang/test/SemaCXX/warn-new-overaligned.cpp
  clang/test/SemaCXX/writable-strings-deprecated.cpp
  clang/test/SemaSYCL/zero-length-arrays.cpp
  clang/test/SemaTemplate/class-template-id.cpp
  clang/test/SemaTemplate/constructor-template.cpp
  clang/test/SemaTemplate/explicit-instantiation.cpp
  clang/test/SemaTemplate/instantiate-exception-spec.cpp
  clang/test/SemaTemplate/instantiate-non-dependent-types.cpp
  clang/test/SemaTemplate/instantiation-default-2.cpp
  clang/test/SemaTemplate/temp_arg.cpp
  clang/test/SemaTemplate/temp_arg_template.cpp
  clang/test/SemaTemplate/typename-specifier-3.cpp
  clang/unittests/AST/ASTTraverserTest.cpp
  llvm/utils/lit/lit/llvm/config.py

Index: llvm/utils/lit/lit/llvm/config.py
===
--- llvm/utils/lit/lit/llvm/config.py
+++ llvm/utils/lit/lit/llvm/config.py
@@ -563,6 +563,26 @@
 self.config.substitutions.append(
 ('%target_itanium_abi_host_triple', ''))
 
+# Many tests work across many language dialects. We provide substitutions
+# conveniently try every dialect with LIT_CLANG_STD_GROUP.
+clang_std_group = int(os.environ.get('LIT_CLANG_STD_GROUP', '0'))
+clang_std_values = ('98', '11', '14', '17', '20', '2b')
+def add_stdcxx(s):
+t = s[8:]
+if t.endswith('-'):
+t += '2b'
+l = clang_std_values.index(t[0:2])
+h = clang_std_values.index(t[3:5])
+# Let LIT_CLANG_STD_GROUP=0 pick the highest value (likely the most relevant
+# dialect).
+l = h - clang_std_group % (h-l+1)
+self.config.substitutions.append((s, '-std=c++' + clang_std_values[l]))
+
+add_stdcxx('%stdcxx_98-14')
+add_stdcxx('%stdcxx_98-')
+add_stdcxx('%stdcxx_11-14')
+add_stdcxx('%stdcxx_17-')
+
 # FIXME: Find nicer way to prohibit this.
 def prefer(this, to):
 return 

[PATCH] D130108: git-clang-format: format index not worktree when using --staged

2022-08-10 Thread Mészáros Gergely via Phabricator via cfe-commits
Maetveis added a comment.

Sorry, I somehow missed the big obvious checkbox to mark the comments, fixed 
now.
I don't have commit access could you commit if the last change seems okay to 
you?

Name: Gergely Meszaros
Email: meszaros.gergel...@gmail.com


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130108

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


[PATCH] D131084: Add support for specifying the severity of a SARIF Result.

2022-08-10 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y updated this revision to Diff 451585.
vaibhav.y added a comment.

Update diff:

- Create class `SarifReportingConfiguration`:

This should allow rules to specify the `defaultConfiguration` property

Add tests for:

- Creating rules with custom reporting configuration
- Death test for invalid reporting configuration rank
- Death test for creating a result that references a disabled rule


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131084

Files:
  clang/include/clang/Basic/Sarif.h
  clang/lib/Basic/Sarif.cpp
  clang/unittests/Basic/SarifTest.cpp

Index: clang/unittests/Basic/SarifTest.cpp
===
--- clang/unittests/Basic/SarifTest.cpp
+++ clang/unittests/Basic/SarifTest.cpp
@@ -7,7 +7,6 @@
 //===--===//
 
 #include "clang/Basic/Sarif.h"
-#include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
@@ -147,6 +146,47 @@
   ASSERT_DEATH(Writer.appendResult(EmptyResult), Matcher);
 }
 
+TEST_F(SarifDocumentWriterTest, settingInvalidRankWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A SarifReportingConfiguration is created with an invalid "rank"
+  // * Ranks below 0.0 are invalid
+  // * Ranks above 100.0 are invalid
+
+  // THEN: The builder will crash in either case
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(-1.0),
+   ::testing::HasSubstr("Rule rank cannot be smaller than 0.0"));
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(101.0),
+   ::testing::HasSubstr("Rule rank cannot be larger than 100.0"));
+}
+
+TEST_F(SarifDocumentWriterTest, creatingResultWithDisabledRuleWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A disabled Rule is created, and a result is create referencing this rule
+  const auto  = SarifReportingConfiguration::create().disable();
+  auto RuleIdx =
+  Writer.createRule(SarifRule::create().setDefaultConfiguration(Config));
+  const SarifResult  = SarifResult::create(RuleIdx);
+
+  // THEN:
+  // SarifResult::create(...) will produce a crash
+  ASSERT_DEATH(
+  Writer.appendResult(Result),
+  ::testing::HasSubstr("Cannot add a result referencing a disabled Rule"));
+}
+
 // Test adding rule and result shows up in the final document
 TEST_F(SarifDocumentWriterTest, addingResultWithValidRuleAndRunIsOk) {
   // GIVEN:
@@ -199,10 +239,10 @@
   EXPECT_TRUE(Artifacts->empty());
 }
 
-TEST_F(SarifDocumentWriterTest, checkSerializingResults) {
+TEST_F(SarifDocumentWriterTest, checkSerializingResultsWithDefaultRuleConfig) {
   // GIVEN:
   const std::string ExpectedOutput =
-  R"({"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[],"columnKind":"unicodeCodePoints","results":[{"message":{"text":""},"ruleId":"clang.unittest","ruleIndex":0}],"tool":{"driver":{"fullName":"sarif test runner","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"sarif test","rules":[{"fullDescription":{"text":"Example rule created during unit tests"},"id":"clang.unittest","name":"clang unit test"}],"version":"1.0.0"}}}],"version":"2.1.0"})";
+  R"({"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[],"columnKind":"unicodeCodePoints","results":[{"level":"warning","message":{"text":""},"ruleId":"clang.unittest","ruleIndex":0}],"tool":{"driver":{"fullName":"sarif test runner","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"sarif test","rules":[{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":"Example rule created during unit tests"},"id":"clang.unittest","name":"clang unit test"}],"version":"1.0.0"}}}],"version":"2.1.0"})";
 
   SarifDocumentWriter Writer{SourceMgr};
   const SarifRule  =
@@ -213,8 +253,34 @@
 
   // WHEN: A run contains a result
   Writer.createRun("sarif test", "sarif test runner", "1.0.0");
-  unsigned ruleIdx = Writer.createRule(Rule);
-  const SarifResult  = SarifResult::create(ruleIdx);
+  unsigned RuleIdx = Writer.createRule(Rule);
+  const SarifResult  = SarifResult::create(RuleIdx);
+  Writer.appendResult(Result);
+  std::string Output = serializeSarifDocument(Writer.createDocument());
+
+  // THEN:
+  ASSERT_THAT(Output, ::testing::StrEq(ExpectedOutput));
+}
+
+TEST_F(SarifDocumentWriterTest, 

[PATCH] D131479: Handle explicitly defaulted consteval special members.

2022-08-10 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:812
+  fail1 = good0;  // expected-error-re {{call to consteval function 
'{{.*::copy<.*::foo>}}::operator=' is not a constant expression}} \
+ expected-note {{in call to 
'>operator=(good0)'}}
+

aaron.ballman wrote:
> This likely has nothing to do with your changes here, but what the heck is 
> with that leading `&`  in this already-pretty-surprisingly-weird note? Is 
> that aiming for `()->operator=(good0)` for some reason?
Note, we also see a similar diagnostic in 
`SemaCXX/constant-expression-cxx11.cpp` so this looks like it existed before.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131479

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


[PATCH] D130108: git-clang-format: format index not worktree when using --staged

2022-08-10 Thread Mészáros Gergely via Phabricator via cfe-commits
Maetveis updated this revision to Diff 451584.
Maetveis marked 7 inline comments as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130108

Files:
  clang/tools/clang-format/git-clang-format

Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -179,15 +179,17 @@
 
   if len(commits) > 1:
 old_tree = commits[1]
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- revision=commits[1],
- binary=opts.binary,
- style=opts.style)
+revision = old_tree
+  elif opts.staged:
+old_tree = create_tree_from_index(changed_lines)
+revision = ''
   else:
 old_tree = create_tree_from_workdir(changed_lines)
-new_tree = run_clang_format_and_save_to_tree(changed_lines,
- binary=opts.binary,
- style=opts.style)
+revision = None
+  new_tree = run_clang_format_and_save_to_tree(changed_lines,
+   revision,
+   binary=opts.binary,
+   style=opts.style)
   if opts.verbose >= 1:
 print('old tree: %s' % old_tree)
 print('new tree: %s' % new_tree)
@@ -394,11 +396,29 @@
   return create_tree(filenames, '--stdin')
 
 
+def create_tree_from_index(filenames):
+  # Copy the environment, because the files have to be read from the original
+  # index.
+  env = os.environ.copy()
+  def index_contents_generator():
+for filename in filenames:
+  git_ls_files_cmd = ['git', 'ls-files', '--stage', '-z', '--', filename]
+  git_ls_files = subprocess.Popen(git_ls_files_cmd, env=env,
+  stdin=subprocess.PIPE,
+  stdout=subprocess.PIPE)
+  stdout = git_ls_files.communicate()[0]
+  yield convert_string(stdout.split(b'\0')[0])
+  return create_tree(index_contents_generator(), '--index-info')
+
+
 def run_clang_format_and_save_to_tree(changed_lines, revision=None,
   binary='clang-format', style=None):
   """Run clang-format on each file and save the result to a git tree.
 
   Returns the object ID (SHA-1) of the created tree."""
+  # Copy the environment when formatting the files in the index, because the
+  # files have to be read from the original index.
+  env = os.environ.copy() if revision == '' else None
   def iteritems(container):
   try:
   return container.iteritems() # Python 2
@@ -406,11 +426,15 @@
   return container.items() # Python 3
   def index_info_generator():
 for filename, line_ranges in iteritems(changed_lines):
-  if revision:
-git_metadata_cmd = ['git', 'ls-tree',
-'%s:%s' % (revision, os.path.dirname(filename)),
-os.path.basename(filename)]
-git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
+  if revision is not None:
+if len(revision) > 0:
+  git_metadata_cmd = ['git', 'ls-tree',
+  '%s:%s' % (revision, os.path.dirname(filename)),
+  os.path.basename(filename)]
+else:
+  git_metadata_cmd = ['git', 'ls-files', '--stage', '--', filename]
+git_metadata = subprocess.Popen(git_metadata_cmd, env=env,
+stdin=subprocess.PIPE,
 stdout=subprocess.PIPE)
 stdout = git_metadata.communicate()[0]
 mode = oct(int(stdout.split()[0], 8))
@@ -422,7 +446,8 @@
   blob_id = clang_format_to_blob(filename, line_ranges,
  revision=revision,
  binary=binary,
- style=style)
+ style=style,
+ env=env)
   yield '%s %s\t%s' % (mode, blob_id, filename)
   return create_tree(index_info_generator(), '--index-info')
 
@@ -448,11 +473,12 @@
 
 
 def clang_format_to_blob(filename, line_ranges, revision=None,
- binary='clang-format', style=None):
+ binary='clang-format', style=None, env=None):
   """Run clang-format on the given file and save the result to a git blob.
 
   Runs on the file in `revision` if not None, or on the file in the working
-  directory if `revision` is None.
+  directory if `revision` is None. Revision can be set to an empty string to run
+  clang-format on the file in the index.
 
   Returns the object ID (SHA-1) 

[PATCH] D131479: Handle explicitly defaulted consteval special members.

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:812
+  fail1 = good0;  // expected-error-re {{call to consteval function 
'{{.*::copy<.*::foo>}}::operator=' is not a constant expression}} \
+ expected-note {{in call to 
'>operator=(good0)'}}
+

This likely has nothing to do with your changes here, but what the heck is with 
that leading `&`  in this already-pretty-surprisingly-weird note? Is that 
aiming for `()->operator=(good0)` for some reason?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131479

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


[PATCH] D131479: Handle explicitly defaulted consteval special members.

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: rsmith.
aaron.ballman added a comment.

This is generally looking good to me, thank you! Just a few minor points and I 
think this will be ready.




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

On my earlier patch, @rsmith had suggested that we check if `MD` is being 
instantiated here rather than `RD` to more closely match the standards wording. 
I think that's a reasonable suggestion -- WDYT?



Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:805
+void func() {
+  default_ctor fail0; // expected-error-re {{call to consteval function 
'{{.*::default_ctor<.*::foo>}}::default_ctor' is not a constant expression}} \
+  expected-note {{in call to 'default_ctor()'}}

Why do we need to use the regex here (and elsewhere)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131479

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


[PATCH] D131528: [Clang] Restrict non fixed enum to a value outside the range of the enumeration values warning to context requiring a constant expression

2022-08-10 Thread Shafik Yaghmour via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4e458765aaef: [Clang] Restrict non fixed enum to a value 
outside the range of the enumeration… (authored by shafik).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131528

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


Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2421,6 +2421,7 @@
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
   // expected-error@-1 {{integer value 8 is outside the valid range of values 
[-8, 7] for this enumeration type}}
+  E1 x2b = static_cast(8); // ok, not a constant expression context
 
   constexpr E2 x3 = static_cast(-8);
   // expected-error@-1 {{integer value -8 is outside the valid range of values 
[0, 7] for this enumeration type}}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -13533,7 +13533,9 @@
   return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
 }
 
-if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
+if (Info.Ctx.getLangOpts().CPlusPlus &&
+Info.EvalMode == EvalInfo::EM_ConstantExpression &&
+DestType->isEnumeralType()) {
   const EnumType *ET = dyn_cast(DestType.getCanonicalType());
   const EnumDecl *ED = ET->getDecl();
   // Check that the value is within the range of the enumeration values.


Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2421,6 +2421,7 @@
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
   // expected-error@-1 {{integer value 8 is outside the valid range of values [-8, 7] for this enumeration type}}
+  E1 x2b = static_cast(8); // ok, not a constant expression context
 
   constexpr E2 x3 = static_cast(-8);
   // expected-error@-1 {{integer value -8 is outside the valid range of values [0, 7] for this enumeration type}}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -13533,7 +13533,9 @@
   return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
 }
 
-if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
+if (Info.Ctx.getLangOpts().CPlusPlus &&
+Info.EvalMode == EvalInfo::EM_ConstantExpression &&
+DestType->isEnumeralType()) {
   const EnumType *ET = dyn_cast(DestType.getCanonicalType());
   const EnumDecl *ED = ET->getDecl();
   // Check that the value is within the range of the enumeration values.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4e45876 - [Clang] Restrict non fixed enum to a value outside the range of the enumeration values warning to context requiring a constant expression

2022-08-10 Thread Shafik Yaghmour via cfe-commits

Author: Shafik Yaghmour
Date: 2022-08-10T11:12:01-07:00
New Revision: 4e458765aaef7988e687e190d865f331727825c0

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

LOG: [Clang] Restrict non fixed enum to a value outside the range of the 
enumeration values warning to context requiring a constant expression

In D131307 we allowed the diagnostic to be turned into a warning for a
transition period.

This had the side effect of triggering the warning in contexts not required to
be constant expression. This change will restrict the diagnostic to constant
expression contexts. This should reduce the fallout of this diagnostic.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 4a1f0852381db..992bc9aa5008f 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -13533,7 +13533,9 @@ bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) 
{
   return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
 }
 
-if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
+if (Info.Ctx.getLangOpts().CPlusPlus &&
+Info.EvalMode == EvalInfo::EM_ConstantExpression &&
+DestType->isEnumeralType()) {
   const EnumType *ET = dyn_cast(DestType.getCanonicalType());
   const EnumDecl *ED = ET->getDecl();
   // Check that the value is within the range of the enumeration values.

diff  --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index c5742ad8c2cbb..3760fa413174a 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2421,6 +2421,7 @@ void testValueInRangeOfEnumerationValues() {
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
   // expected-error@-1 {{integer value 8 is outside the valid range of values 
[-8, 7] for this enumeration type}}
+  E1 x2b = static_cast(8); // ok, not a constant expression context
 
   constexpr E2 x3 = static_cast(-8);
   // expected-error@-1 {{integer value -8 is outside the valid range of values 
[0, 7] for this enumeration type}}



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


[PATCH] D131563: [WIP] [clang] Fix clang multiarch isssue with musl

2022-08-10 Thread Brahmajit via Phabricator via cfe-commits
listout updated this revision to Diff 451572.

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

https://reviews.llvm.org/D131563

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
@@ -46,6 +46,8 @@
   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
 
+  std::string EnvName = TargetTriple.isMusl() ? "musl" : "gnu";
+
   // For most architectures, just use whatever we have rather than trying to be
   // clever.
   switch (TargetTriple.getArch()) {
@@ -62,34 +64,34 @@
   return "arm-linux-androideabi";
 if (TargetEnvironment == llvm::Triple::GNUEABIHF)
   return "arm-linux-gnueabihf";
-return "arm-linux-gnueabi";
+return "arm-linux-" + EnvName + "eabi";
   case llvm::Triple::armeb:
   case llvm::Triple::thumbeb:
 if (TargetEnvironment == llvm::Triple::GNUEABIHF)
   return "armeb-linux-gnueabihf";
-return "armeb-linux-gnueabi";
+return "armeb-linux-" + EnvName + "eabi";
   case llvm::Triple::x86:
 if (IsAndroid)
   return "i686-linux-android";
-return "i386-linux-gnu";
+return "i386-linux-" + EnvName;
   case llvm::Triple::x86_64:
 if (IsAndroid)
   return "x86_64-linux-android";
 if (TargetEnvironment == llvm::Triple::GNUX32)
   return "x86_64-linux-gnux32";
-return "x86_64-linux-gnu";
+return "x86_64-linux-" + EnvName;
   case llvm::Triple::aarch64:
 if (IsAndroid)
   return "aarch64-linux-android";
-return "aarch64-linux-gnu";
+return "aarch64-linux-" + EnvName;
   case llvm::Triple::aarch64_be:
-return "aarch64_be-linux-gnu";
+return "aarch64_be-linux-" + EnvName;
 
   case llvm::Triple::m68k:
-return "m68k-linux-gnu";
+return "m68k-linux-" + EnvName;
 
   case llvm::Triple::mips:
-return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
+return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-" + EnvName;
   case llvm::Triple::mipsel:
 if (IsAndroid)
   return "mipsel-linux-android";
@@ -117,19 +119,19 @@
   case llvm::Triple::ppc:
 if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
   return "powerpc-linux-gnuspe";
-return "powerpc-linux-gnu";
+return "powerpc-linux-" + EnvName;
   case llvm::Triple::ppcle:
-return "powerpcle-linux-gnu";
+return "powerpcle-linux-" + EnvName;
   case llvm::Triple::ppc64:
-return "powerpc64-linux-gnu";
+return "powerpc64-linux-" + EnvName;
   case llvm::Triple::ppc64le:
-return "powerpc64le-linux-gnu";
+return "powerpc64le-linux-" + EnvName;
   case llvm::Triple::riscv64:
-return "riscv64-linux-gnu";
+return "riscv64-linux-" + EnvName;
   case llvm::Triple::sparc:
-return "sparc-linux-gnu";
+return "sparc-linux-" + EnvName;
   case llvm::Triple::sparcv9:
-return "sparc64-linux-gnu";
+return "sparc64-linux-" + EnvName;
   case llvm::Triple::systemz:
 return "s390x-linux-gnu";
   }


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -46,6 +46,8 @@
   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
 
+  std::string EnvName = TargetTriple.isMusl() ? "musl" : "gnu";
+
   // For most architectures, just use whatever we have rather than trying to be
   // clever.
   switch (TargetTriple.getArch()) {
@@ -62,34 +64,34 @@
   return "arm-linux-androideabi";
 if (TargetEnvironment == llvm::Triple::GNUEABIHF)
   return "arm-linux-gnueabihf";
-return "arm-linux-gnueabi";
+return "arm-linux-" + EnvName + "eabi";
   case llvm::Triple::armeb:
   case llvm::Triple::thumbeb:
 if (TargetEnvironment == llvm::Triple::GNUEABIHF)
   return "armeb-linux-gnueabihf";
-return "armeb-linux-gnueabi";
+return "armeb-linux-" + EnvName + "eabi";
   case llvm::Triple::x86:
 if (IsAndroid)
   return "i686-linux-android";
-return "i386-linux-gnu";
+return "i386-linux-" + EnvName;
   case llvm::Triple::x86_64:
 if (IsAndroid)
   return "x86_64-linux-android";
 if (TargetEnvironment == llvm::Triple::GNUX32)
   return "x86_64-linux-gnux32";
-return "x86_64-linux-gnu";
+return "x86_64-linux-" + EnvName;
   case llvm::Triple::aarch64:
 if (IsAndroid)
   return "aarch64-linux-android";
-return "aarch64-linux-gnu";
+return "aarch64-linux-" + EnvName;
   case llvm::Triple::aarch64_be:
-return "aarch64_be-linux-gnu";
+return "aarch64_be-linux-" + EnvName;
 
   case llvm::Triple::m68k:
-return "m68k-linux-gnu";
+return 

[PATCH] D131528: [Clang] Restrict non fixed enum to a value outside the range of the enumeration values warning to context requiring a constant expression

2022-08-10 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Can this land? Our bots have been red since the default-error-mapped-warning 
patch landed...


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

https://reviews.llvm.org/D131528

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


[PATCH] D126676: [clang] Disallow differences in defines used for creating and using PCH

2022-08-10 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.

LGTM, no issues on our side.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126676

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


[PATCH] D131351: [C] Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaf01f717c48f: Default implicit function pointer conversions 
diagnostic to be an error (authored by aaron.ballman).

Changed prior to commit:
  https://reviews.llvm.org/D131351?vs=451094=451561#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131351

Files:
  clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c
  clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/test/CodeGen/attributes.c
  clang/test/CodeGen/overloadable.c
  clang/test/Sema/aarch64-svepcs.c
  clang/test/Sema/aarch64-vpcs.c
  clang/test/Sema/arm-cmse.c
  clang/test/Sema/attr-nocf_check.c
  clang/test/Sema/block-return.c
  clang/test/Sema/c2x-func-prototype.c
  clang/test/Sema/callingconv-ms_abi.c
  clang/test/Sema/callingconv-sysv_abi.c
  clang/test/Sema/callingconv.c
  clang/test/Sema/incompatible-function-pointer-types.c
  clang/test/Sema/initialize-noreturn.c
  clang/test/Sema/noescape.c
  clang/test/Sema/overloadable.c
  clang/test/Sema/pass-object-size.c
  clang/test/Sema/preserve-call-conv.c
  clang/test/SemaObjC/comptypes-legal.m

Index: clang/test/SemaObjC/comptypes-legal.m
===
--- clang/test/SemaObjC/comptypes-legal.m
+++ clang/test/SemaObjC/comptypes-legal.m
@@ -31,9 +31,9 @@
 
 void foo(void)
 {
-  // GCC currently allows this (it has some fiarly new support for covariant return types and contravariant argument types).
+  // GCC currently allows this (it has some fairly new support for covariant return types and contravariant argument types).
   // Since registerFunc: expects a Derived object as it's second argument, I don't know why this would be legal.
-  [Derived registerFunc: ExternFunc];  // expected-warning{{incompatible function pointer types sending 'NSObject *(NSObject *, NSObject *)' to parameter of type 'FuncSignature *' (aka 'id (*)(NSObject *, Derived *)')}}
+  [Derived registerFunc: ExternFunc];  // expected-error{{incompatible function pointer types sending 'NSObject *(NSObject *, NSObject *)' to parameter of type 'FuncSignature *' (aka 'id (*)(NSObject *, Derived *)')}}
 }
 
 // rdar://10751015
Index: clang/test/Sema/preserve-call-conv.c
===
--- clang/test/Sema/preserve-call-conv.c
+++ clang/test/Sema/preserve-call-conv.c
@@ -14,8 +14,8 @@
 
 void (__attribute__((preserve_most)) *pfoo1)(void *) = foo;
 
-void (__attribute__((cdecl)) *pfoo2)(void *) = foo; // expected-warning {{incompatible function pointer types initializing 'void (*)(void *) __attribute__((cdecl))' with an expression of type 'void (void *) __attribute__((preserve_most))'}}
-void (*pfoo3)(void *) = foo; // expected-warning {{incompatible function pointer types initializing 'void (*)(void *)' with an expression of type 'void (void *) __attribute__((preserve_most))'}}
+void (__attribute__((cdecl)) *pfoo2)(void *) = foo; // expected-error {{incompatible function pointer types initializing 'void (*)(void *) __attribute__((cdecl))' with an expression of type 'void (void *) __attribute__((preserve_most))'}}
+void (*pfoo3)(void *) = foo; // expected-error {{incompatible function pointer types initializing 'void (*)(void *)' with an expression of type 'void (void *) __attribute__((preserve_most))'}}
 
 typedef_fun_t typedef_fun_foo; // expected-note {{previous declaration is here}}
 void __attribute__((preserve_most)) typedef_fun_foo(int x) { } // expected-error {{function declared 'preserve_most' here was previously declared without calling convention}}
@@ -30,8 +30,8 @@
 
 void (__attribute__((preserve_all)) *pboo1)(void *) = boo;
 
-void (__attribute__((cdecl)) *pboo2)(void *) = boo; // expected-warning {{incompatible function pointer types initializing 'void (*)(void *) __attribute__((cdecl))' with an expression of type 'void (void *) __attribute__((preserve_all))'}}
-void (*pboo3)(void *) = boo; // expected-warning {{incompatible function pointer types initializing 'void (*)(void *)' with an expression of type 'void (void *) __attribute__((preserve_all))'}}
+void (__attribute__((cdecl)) *pboo2)(void *) = boo; // expected-error {{incompatible function pointer types initializing 'void (*)(void *) __attribute__((cdecl))' with an expression of type 'void (void *) __attribute__((preserve_all))'}}
+void (*pboo3)(void *) = boo; // expected-error {{incompatible function pointer types initializing 'void (*)(void *)' with an expression of type 'void (void *) __attribute__((preserve_all))'}}
 
 typedef_fun_t typedef_fun_boo; // expected-note {{previous declaration is here}}
 void __attribute__((preserve_all)) typedef_fun_boo(int x) { } // expected-error {{function declared 'preserve_all' here was previously declared without 

[clang-tools-extra] af01f71 - Default implicit function pointer conversions diagnostic to be an error

2022-08-10 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-08-10T13:54:17-04:00
New Revision: af01f717c48f0fd2481600ed6c00441763365b62

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

LOG: Default implicit function pointer conversions diagnostic to be an error

Implicitly converting between incompatible function pointers in C is
currently a default-on warning (it is an error in C++). However, this
is very poor security posture. A mismatch in parameters or return
types, or a mismatch in calling conventions, etc can lead to
exploitable security vulnerabilities. Rather than allow this unsafe
practice with a warning, this patch strengthens the warning to be an
error (while still allowing users the ability to disable the error or
the warning entirely to ease migration). Users should either ensure the
signatures are correctly compatible or they should use an explicit cast
if they believe that's more reasonable.

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

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/test/CodeGen/attributes.c
clang/test/CodeGen/overloadable.c
clang/test/Sema/aarch64-svepcs.c
clang/test/Sema/aarch64-vpcs.c
clang/test/Sema/arm-cmse.c
clang/test/Sema/attr-nocf_check.c
clang/test/Sema/block-return.c
clang/test/Sema/c2x-func-prototype.c
clang/test/Sema/callingconv-ms_abi.c
clang/test/Sema/callingconv-sysv_abi.c
clang/test/Sema/callingconv.c
clang/test/Sema/incompatible-function-pointer-types.c
clang/test/Sema/initialize-noreturn.c
clang/test/Sema/noescape.c
clang/test/Sema/overloadable.c
clang/test/Sema/pass-object-size.c
clang/test/Sema/preserve-call-conv.c
clang/test/SemaObjC/comptypes-legal.m

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c
index 57c58fc6df684..08fb7a694f819 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c
@@ -13,7 +13,9 @@ void handler_bad1(int) {
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: standard function '_exit' may 
not be asynchronous-safe; calling it from a signal handler may be dangerous 
[bugprone-signal-handler]
 }
 
-void handler_bad2(void *dst, const void *src) {
+void handler_bad2(int) {
+  void *dst;
+  const void *src;
   memcpy(dst, src, 10);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: standard function 'memcpy' may 
not be asynchronous-safe; calling it from a signal handler may be dangerous 
[bugprone-signal-handler]
 }

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c
index 51f7b07a39109..edd24a9c36cd9 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c
@@ -14,6 +14,7 @@ typedef void (*sighandler_t)(int);
 sighandler_t signal(int signum, sighandler_t handler);
 
 void f_extern(void);
+void f_extern_handler(int);
 
 void handler_printf(int) {
   printf("1234");
@@ -185,8 +186,8 @@ void test_other(void) {
   signal(SIGINT, _Exit);
   signal(SIGINT, other_call);
   // CHECK-NOTES: :[[@LINE-1]]:18: warning: standard function 'other_call' may 
not be asynchronous-safe; using it as a signal handler may be dangerous 
[bugprone-signal-handler]
-  signal(SIGINT, f_extern);
-  // CHECK-NOTES: :[[@LINE-1]]:18: warning: cannot verify that external 
function 'f_extern' is asynchronous-safe; using it as a signal handler may be 
dangerous [bugprone-signal-handler]
+  signal(SIGINT, f_extern_handler);
+  // CHECK-NOTES: :[[@LINE-1]]:18: warning: cannot verify that external 
function 'f_extern_handler' is asynchronous-safe; using it as a signal handler 
may be dangerous [bugprone-signal-handler]
 
   signal(SIGINT, SIG_IGN);
   signal(SIGINT, SIG_DFL);

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4b01f018005ed..a37120ba2d56c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -85,6 +85,10 @@ Improvements to Clang's diagnostics
 - ``-Wbitfield-constant-conversion`` now diagnoses implicit truncation when 1 
is
   assigned to a 1-bit signed integer bitfield. This fixes
   `Issue 53253 `_.
+- ``-Wincompatible-function-pointer-types`` now defaults to an error in all C
+  language modes. It may be 

[clang] ec08114 - [NFC][Clang] make AtomicConstraint::ParameterMapping const

2022-08-10 Thread Yuanfang Chen via cfe-commits

Author: Yuanfang Chen
Date: 2022-08-10T10:51:39-07:00
New Revision: ec0811413375bfe75a9361264f98ad9b5dab85b6

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

LOG: [NFC][Clang] make AtomicConstraint::ParameterMapping const

It was not const due to the way it is initialized. This is needed for
a following patch.

Added: 


Modified: 
clang/include/clang/Sema/SemaConcept.h
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/SemaConcept.h 
b/clang/include/clang/Sema/SemaConcept.h
index b73a152533d11..a5b65f2edf940 100644
--- a/clang/include/clang/Sema/SemaConcept.h
+++ b/clang/include/clang/Sema/SemaConcept.h
@@ -28,7 +28,7 @@ class Sema;
 
 struct AtomicConstraint {
   const Expr *ConstraintExpr;
-  Optional> ParameterMapping;
+  Optional> ParameterMapping;
 
   AtomicConstraint(Sema , const Expr *ConstraintExpr) :
   ConstraintExpr(ConstraintExpr) { };

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f0ccc0710cfb4..7545b7974ce49 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -754,14 +754,13 @@ static bool substituteParameterMappings(Sema , 
NormalizedConstraint ,
 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
 S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
  /*Depth=*/0, OccurringIndices);
-Atomic.ParameterMapping.emplace(
-MutableArrayRef(
-new (S.Context) TemplateArgumentLoc[OccurringIndices.count()],
-OccurringIndices.count()));
+TemplateArgumentLoc *TempArgs =
+new (S.Context) TemplateArgumentLoc[OccurringIndices.count()];
 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
   if (OccurringIndices[I])
-new (&(*Atomic.ParameterMapping)[J++]) TemplateArgumentLoc(
-S.getIdentityTemplateArgumentLoc(TemplateParams->begin()[I],
+new (&(TempArgs)[J++])
+TemplateArgumentLoc(S.getIdentityTemplateArgumentLoc(
+TemplateParams->begin()[I],
 // Here we assume we do not support things like
 // template
 // concept C = ...;
@@ -770,9 +769,10 @@ static bool substituteParameterMappings(Sema , 
NormalizedConstraint ,
 // struct S { };
 // The above currently yields a diagnostic.
 // We still might have default arguments for concept 
parameters.
-ArgsAsWritten->NumTemplateArgs > I ?
-ArgsAsWritten->arguments()[I].getLocation() :
-SourceLocation()));
+ArgsAsWritten->NumTemplateArgs > I
+? ArgsAsWritten->arguments()[I].getLocation()
+: SourceLocation()));
+Atomic.ParameterMapping.emplace(TempArgs,  OccurringIndices.count());
   }
   Sema::InstantiatingTemplate Inst(
   S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
@@ -781,12 +781,12 @@ static bool substituteParameterMappings(Sema , 
NormalizedConstraint ,
   
ArgsAsWritten->arguments().back().getSourceRange().getEnd()));
   if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
 return true;
-  Atomic.ParameterMapping.emplace(
-MutableArrayRef(
-new (S.Context) TemplateArgumentLoc[SubstArgs.size()],
-SubstArgs.size()));
+
+  TemplateArgumentLoc *TempArgs =
+  new (S.Context) TemplateArgumentLoc[SubstArgs.size()];
   std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
-N.getAtomicConstraint()->ParameterMapping->begin());
+TempArgs);
+  Atomic.ParameterMapping.emplace(TempArgs, SubstArgs.size());
   return false;
 }
 



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


[PATCH] D131600: [clang][dataflow] Don't crash when caller args are missing storage locations

2022-08-10 Thread Sam Estep 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 rG43b298ea1282: [clang][dataflow] Dont crash when caller 
args are missing storage locations (authored by samestep).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131600

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


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,6 +4229,27 @@
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
+TEST(TransferTest, ContextSensitiveReturnInt) {
+  std::string Code = R"(
+int identity(int x) { return x; }
+
+void target() {
+  int y = identity(42);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+// This just tests that the analysis doesn't crash.
+  },
+  {/*.ApplyBuiltinTransfer=*/true,
+   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
+}
+
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,7 +253,8 @@
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-assert(ArgLoc != nullptr);
+if (ArgLoc == nullptr)
+  continue;
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,8 +140,6 @@
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
-  ///
-  ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
   Environment pushCall(const CXXConstructExpr *Call) const;
 


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,6 +4229,27 @@
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
+TEST(TransferTest, ContextSensitiveReturnInt) {
+  std::string Code = R"(
+int identity(int x) { return x; }
+
+void target() {
+  int y = identity(42);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+// This just tests that the analysis doesn't crash.
+  },
+  {/*.ApplyBuiltinTransfer=*/true,
+   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
+}
+
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,7 +253,8 @@
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-assert(ArgLoc != nullptr);
+if (ArgLoc == nullptr)
+  continue;
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,8 +140,6 @@
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
-  ///
-  ///  Each argument of `Call` must already have a 

[clang] 43b298e - [clang][dataflow] Don't crash when caller args are missing storage locations

2022-08-10 Thread Sam Estep via cfe-commits

Author: Sam Estep
Date: 2022-08-10T17:50:34Z
New Revision: 43b298ea1282f29d448fc0f6ca971bc5fa698355

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

LOG: [clang][dataflow] Don't crash when caller args are missing storage 
locations

This patch modifies `Environment`'s `pushCall` method to pass over arguments 
that are missing storage locations, instead of crashing.

Reviewed By: gribozavr2

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 8c169005846ef..b3bc52a79a2fc 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,8 +140,6 @@ class Environment {
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
-  ///
-  ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
   Environment pushCall(const CXXConstructExpr *Call) const;
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index e4af68e53e14e..119ef337c6319 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,7 +253,8 @@ void Environment::pushCallInternal(const FunctionDecl 
*FuncDecl,
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-assert(ArgLoc != nullptr);
+if (ArgLoc == nullptr)
+  continue;
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index af06021abccfd..0e33df3a38008 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,6 +4229,27 @@ TEST(TransferTest, ContextSensitiveReturnArg) {
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
+TEST(TransferTest, ContextSensitiveReturnInt) {
+  std::string Code = R"(
+int identity(int x) { return x; }
+
+void target() {
+  int y = identity(42);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+// This just tests that the analysis doesn't crash.
+  },
+  {/*.ApplyBuiltinTransfer=*/true,
+   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
+}
+
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {



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


[PATCH] D130933: Add docs for function attributes hot/cold

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D130933#3713437 , @OfekShilon 
wrote:

> @aaron.ballman   'Ofek Shilon', ofekshi...@gmail.com is fine.
> Thanks!

Thank you! I've landed on your behalf.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130933

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


[PATCH] D130933: Add docs for function attributes hot/cold

2022-08-10 Thread Aaron Ballman 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 rG73a1b162a4cd: Add docs for function attributes hot/cold 
(authored by OfekShilon, committed by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130933

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td


Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -5241,6 +5241,21 @@
 }];
 }
 
+def HotFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((hot))`` marks a function as hot, as a manual alternative to 
PGO hotness data.
+If PGO data is available, the annotation ``__attribute__((hot))`` overrides 
the profile count based hotness (unlike ``__attribute__((cold))``).
+}];
+}
+
+def ColdFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((cold))`` marks a function as cold, as a manual alternative to 
PGO hotness data.
+If PGO data is available, the profile count based hotness overrides the 
``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).
+}];
+}
 def TransparentUnionDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -1073,7 +1073,7 @@
 def Cold : InheritableAttr {
   let Spellings = [GCC<"cold">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [ColdFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 
@@ -1519,7 +1519,7 @@
 def Hot : InheritableAttr {
   let Spellings = [GCC<"hot">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [HotFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 def : MutualExclusions<[Hot, Cold]>;


Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -5241,6 +5241,21 @@
 }];
 }
 
+def HotFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
+If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).
+}];
+}
+
+def ColdFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
+If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).
+}];
+}
 def TransparentUnionDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -1073,7 +1073,7 @@
 def Cold : InheritableAttr {
   let Spellings = [GCC<"cold">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [ColdFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 
@@ -1519,7 +1519,7 @@
 def Hot : InheritableAttr {
   let Spellings = [GCC<"hot">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [HotFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 def : MutualExclusions<[Hot, Cold]>;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 73a1b16 - Add docs for function attributes hot/cold

2022-08-10 Thread Aaron Ballman via cfe-commits

Author: Ofek Shilon
Date: 2022-08-10T13:48:43-04:00
New Revision: 73a1b162a4cd5850a474b7cf8497aef3006094e2

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

LOG: Add docs for function attributes hot/cold

Following https://reviews.llvm.org/D92493, this add docs for the hot
and cold function attributes.

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 7a660c9005050..670af57c3def5 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1073,7 +1073,7 @@ def CmseNSCall : TypeAttr, TargetSpecificAttr {
 def Cold : InheritableAttr {
   let Spellings = [GCC<"cold">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [ColdFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 
@@ -1519,7 +1519,7 @@ def GNUInline : InheritableAttr {
 def Hot : InheritableAttr {
   let Spellings = [GCC<"hot">];
   let Subjects = SubjectList<[Function]>;
-  let Documentation = [Undocumented];
+  let Documentation = [HotFunctionEntryDocs];
   let SimpleHandler = 1;
 }
 def : MutualExclusions<[Hot, Cold]>;

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 0f428a5647dfc..6afd3063524c9 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5241,6 +5241,21 @@ aarch64/aarch64-be/riscv32/riscv64/i386/x86-64 targets.
 }];
 }
 
+def HotFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((hot))`` marks a function as hot, as a manual alternative to 
PGO hotness data.
+If PGO data is available, the annotation ``__attribute__((hot))`` overrides 
the profile count based hotness (unlike ``__attribute__((cold))``).
+}];
+}
+
+def ColdFunctionEntryDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+``__attribute__((cold))`` marks a function as cold, as a manual alternative to 
PGO hotness data.
+If PGO data is available, the profile count based hotness overrides the 
``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).
+}];
+}
 def TransparentUnionDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{



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


[PATCH] D131600: [clang][dataflow] Don't crash when caller args are missing storage locations

2022-08-10 Thread Sam Estep via Phabricator via cfe-commits
samestep created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
samestep 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/D131600

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


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,6 +4229,27 @@
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
+TEST(TransferTest, ContextSensitiveReturnInt) {
+  std::string Code = R"(
+int identity(int x) { return x; }
+
+void target() {
+  int y = identity(42);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+// This just tests that the analysis doesn't crash.
+  },
+  {/*.ApplyBuiltinTransfer=*/true,
+   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
+}
+
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,7 +253,8 @@
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-assert(ArgLoc != nullptr);
+if (ArgLoc == nullptr)
+  continue;
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,8 +140,6 @@
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
-  ///
-  ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
   Environment pushCall(const CXXConstructExpr *Call) const;
 


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -4229,6 +4229,27 @@
/*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
 }
 
+TEST(TransferTest, ContextSensitiveReturnInt) {
+  std::string Code = R"(
+int identity(int x) { return x; }
+
+void target() {
+  int y = identity(42);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+// This just tests that the analysis doesn't crash.
+  },
+  {/*.ApplyBuiltinTransfer=*/true,
+   /*.BuiltinTransferOptions=*/{/*.ContextSensitive=*/true}});
+}
+
 TEST(TransferTest, ContextSensitiveMethodLiteral) {
   std::string Code = R"(
 class MyClass {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -253,7 +253,8 @@
 
 const Expr *Arg = Args[ArgIndex];
 auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
-assert(ArgLoc != nullptr);
+if (ArgLoc == nullptr)
+  continue;
 
 const VarDecl *Param = *ParamIt;
 auto  = createStorageLocation(*Param);
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -140,8 +140,6 @@
   ///  The body of the callee must not reference globals.
   ///
   ///  The arguments of `Call` must map 1:1 to the callee's parameters.
-  ///
-  ///  Each argument of `Call` must already have a `StorageLocation`.
   Environment pushCall(const CallExpr *Call) const;
   Environment 

[PATCH] D130933: Add docs for function attributes hot/cold

2022-08-10 Thread Ofek Shilon via Phabricator via cfe-commits
OfekShilon added a comment.

@aaron.ballman   'Ofek Shilon', ofekshi...@gmail.com is fine.
Thanks!


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

https://reviews.llvm.org/D130933

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


[PATCH] D130933: Add docs for function attributes hot/cold

2022-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

In D130933#3713277 , @OfekShilon 
wrote:

> My apologies for the mess, hopefully the diff I just uploaded includes all 
> the right fixes.

No worries! If I had a nickel for every time I've been confused by git... I'd 
have a lot of nickels.

This version LGTM! I can land it for you, but what name and email address would 
you like me to use for patch attribution?


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

https://reviews.llvm.org/D130933

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


[PATCH] D131598: [Clang][BPF]: Force sign/zero extension for return values in caller

2022-08-10 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song created this revision.
yonghong-song added reviewers: ast, anakryiko.
Herald added subscribers: pengfei, kristof.beyls.
Herald added a project: All.
yonghong-song requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently bpf supports calling kernel functions (x86_64, arm64, etc.)
in bpf programs. Tejun discovered a problem where the x86_64 func
return value (a unsigned char type) is stored in 8-bit subregister %al
and the other 56-bits in %rax might be garbage. But based on current
bpf ABI, the bpf program assumes the whole %rax holds the correct value
as the callee is supposed to do necessary sign/zero extension.
This mismatch between bpf and x86_64 caused the incorrect results.

To resolve this problem, this patch forced caller to do needed
sign/zero extension for 8/16-bit return values as well. Note that
32-bit return values already had sign/zero extension even without
this patch.

For example, for the test case attached to this patch:

  $  cat t.c
  _Bool bar_bool(void);
  unsigned char bar_char(void);
  short bar_short(void);
  int bar_int(void);
  int foo_bool(void) {
if (bar_bool() != 1) return 0; else return 1;
  }
  int foo_char(void) {
if (bar_char() != 10) return 0; else return 1;
  }
  int foo_short(void) {
if (bar_short() != 10) return 0; else return 1;
  }
  int foo_int(void) {
if (bar_int() != 10) return 0; else return 1;
  }

Without this patch, generated call insns in IR looks like:

  %call = call zeroext i1 @bar_bool()
  %call = call zeroext i8 @bar_char()
  %call = call signext i16 @bar_short()
  %call = call i32 @bar_int()

So it is assumed that zero extension has been done for return values of
bar_bool()and bar_char(). Sign extension has been done for the return
value of bar_short(). The return value of bar_int() does not have any
assumption so caller needs to do necessary shifting to get correct
32bit values.

With this patch, generated call insns in IR looks like:

  %call = call i1 @bar_bool()
  %call = call i8 @bar_char()
  %call = call i16 @bar_short()
  %call = call i32 @bar_int()

There are no assumptions for return values of the above four function calls,
so necessary shifting is necessary for all of them.

The following is the objdump file difference for function foo_char().
Without this patch:

  0010 :
   2:   85 10 00 00 ff ff ff ff call -1
   3:   bf 01 00 00 00 00 00 00 r1 = r0
   4:   b7 00 00 00 01 00 00 00 r0 = 1
   5:   15 01 01 00 0a 00 00 00 if r1 == 10 goto +1 
   6:   b7 00 00 00 00 00 00 00 r0 = 0
  0038 :
   7:   95 00 00 00 00 00 00 00 exit

With this patch:

  0018 :
   3:   85 10 00 00 ff ff ff ff call -1
   4:   bf 01 00 00 00 00 00 00 r1 = r0
   5:   57 01 00 00 ff 00 00 00 r1 &= 255
   6:   b7 00 00 00 01 00 00 00 r0 = 1
   7:   15 01 01 00 0a 00 00 00 if r1 == 10 goto +1 
   8:   b7 00 00 00 00 00 00 00 r0 = 0
  0048 :
   9:   95 00 00 00 00 00 00 00 exit

The zero extension of the return 'char' value is done here.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131598

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/bpf-abiinfo.c


Index: clang/test/CodeGen/bpf-abiinfo.c
===
--- /dev/null
+++ clang/test/CodeGen/bpf-abiinfo.c
@@ -0,0 +1,24 @@
+// REQUIRES: bpf-registered-target
+// RUN: %clang_cc1 -triple bpf -O2 -emit-llvm -disable-llvm-passes %s -o - | 
FileCheck %s
+
+_Bool bar_bool(void);
+unsigned char bar_char(void);
+short bar_short(void);
+int bar_int(void);
+
+int foo_bool(void) {
+if (bar_bool() != 1) return 0; else return 1;
+}
+// CHECK: %call = call i1 @bar_bool()
+int foo_char(void) {
+if (bar_char() != 10) return 0; else return 1;
+}
+// CHECK: %call = call i8 @bar_char()
+int foo_short(void) {
+if (bar_short() != 10) return 0; else return 1;
+}
+// CHECK: %call = call i16 @bar_short()
+int foo_int(void) {
+if (bar_int() != 10) return 0; else return 1;
+}
+// CHECK: %call = call i32 @bar_int()
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -11499,6 +11499,56 @@
 };
 } // end anonymous namespace
 
+//===--===//
+// BPF ABI Implementation
+//===--===//
+
+namespace {
+
+class BPFABIInfo : public DefaultABIInfo {
+public:
+  BPFABIInfo(CodeGenTypes ) : DefaultABIInfo(CGT) {}
+
+  ABIArgInfo classifyReturnType(QualType RetTy) const {
+if (RetTy->isVoidType())
+  return ABIArgInfo::getIgnore();
+
+if (isAggregateTypeForABI(RetTy))
+  return getNaturalAlignIndirect(RetTy);
+
+

  1   2   3   >