[PATCH] D123538: [symbolizer] Parse DW_TAG_variable DIs to show line info for globals

2022-05-11 Thread James Henderson via Phabricator via cfe-commits
jhenderson added a comment.

Okay, nothing else from me, but @dblaikie or another debuginfo person should 
review it too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123538

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


[PATCH] D124341: [clang-tidy][NFC] Replace many instances of std::string where a StringRef would suffice.

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

In D124341#3504427 , @njames93 wrote:

> In D124341#3502659 , @uabelho wrote:
>
>> Hi,
>>
>> I noticed that this patch isn't NFC.
>
> Whoops, good catch. I left in some debugging code, fixed in 
> rGa308a55720249749 
> 

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124341

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


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

2022-05-11 Thread Zakk Chen via Phabricator via cfe-commits
khchen added a comment.
Herald added a subscriber: shiva0217.

Thanks for refactoring!




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

I think vector is not a primitive type in common sense, is it?
why Widening2XVector, Widening4XVector, Widening8XVector and MaskVector is not 
part of VectorTypeModifier?

Sorry, I'm confused and maybe forget something.



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

I think we need to update the comment in riscv_vector.td to sync the word 
"TypeProfile", I feel the new word `TypeProfile` is similar to `modifier` or 
`prototype`, is it?

```
The C/C++ prototype of the builtin is defined by the Prototype attribute.
Prototype is a non-empty sequence of type transformers, the first of which
is the return type of the builtin and the rest are the parameters of the
builtin, in order. For instance if Prototype is "wvv" and TypeRange is "si"
a first builtin will have type
```

we call it  `modifier` or `prototype` is because those words are coming from 
clang intrinsic definition and other target.

https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/Builtins.def#L52
https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/arm_sve.td#L58

personally I think consistent naming maybe better than creating a new word, 
what do you think?


BTW, I think having this new class is really good idea for refactoring!



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

If we allow parameter could `uint8_t`, why other constructors not follow the 
same rule?



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

What's purpose of this function, translate TypeProfile to the Proto string?



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:249
+  /// and LMUL with type transformers). It also record result of type in legal
+  /// or illegal set to avoid compute the  same config again. The result maybe
+  /// have illegal RVVType.

additional space



Comment at: clang/lib/Support/RISCVVIntrinsicUtils.cpp:767
+
+void RVVType::applyFixedLog2LMUL(int Log2LMUL, bool LargerThan) {
+  if (LargerThan) {

In riscv_vector.td is said smaller or larger, I feel little confusing here when 
it call LagerThan. maybe have more comment like `The result of modified type 
should be smaller than giving type` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124730

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


[PATCH] D124977: [NFC][Clang] Modify expect of fail test or XFAIL because CSKY align is different

2022-05-11 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added inline comments.



Comment at: clang/test/Sema/builtin-alloca-with-align.c:32
 void test8(void) {
+#if defined(__csky__)
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
__alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
__builtin_alloca_with_align is supposed to be in bits}}

aaron.ballman wrote:
> rengolin wrote:
> > zixuan-wu wrote:
> > > rengolin wrote:
> > > > This test is platform agnostic, perhaps the extra error could be in a 
> > > > new test, exclusively for csky?
> > > Then I prefer to split the file and add UNSUPPORTED for CSKY in the other 
> > > file which only contains test8
> > But then you wouldn't be testing the extra error you want... hmm.
> > 
> > Maybe it would be fine the way you did it originally.
> > 
> > Would be nice to get a clang person to give their opinion.
>   // Comment which explains why this is special.
> I think I would test this slightly differently:
> ```
> void test8(void) {
>   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
> __alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
> __builtin_alloca_with_align is supposed to be in bits}}
> #ifdef __csky__
>   // expected-error@-2 {{requested alignment must be 8 or greater}}
>   // Comment which explains why this is special.
> #endif // __csky__
> }
> ```
Reusing the first warning is good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124977

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


[PATCH] D124977: [NFC][Clang] Modify expect of fail test or XFAIL because CSKY align is different

2022-05-11 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu updated this revision to Diff 428585.
zixuan-wu added a comment.

Address comments.


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

https://reviews.llvm.org/D124977

Files:
  clang/test/CodeGen/c-strings.c
  clang/test/Sema/builtin-alloca-with-align.c


Index: clang/test/Sema/builtin-alloca-with-align.c
===
--- clang/test/Sema/builtin-alloca-with-align.c
+++ clang/test/Sema/builtin-alloca-with-align.c
@@ -30,4 +30,8 @@
 
 void test8(void) {
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
__alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
__builtin_alloca_with_align is supposed to be in bits}}
+#if defined(__csky__)
+  // expected-error@-1 {{requested alignment must be 8 or greater}}
+  // Because the alignment of long long is 4 in CSKY target
+#endif
 }
Index: clang/test/CodeGen/c-strings.c
===
--- clang/test/CodeGen/c-strings.c
+++ clang/test/CodeGen/c-strings.c
@@ -20,6 +20,11 @@
 // fails the check for "@f3.x = ... align [ALIGN]", since ALIGN is derived
 // from the alignment of a single i8, which is still 1.
 
+// XFAIL: csky
+// CSKY aligns arrays of size 4+ bytes to a 32-bit boundary, which
+// fails the check for "@f2.x = ... align [ALIGN]", since ALIGN is derived
+// from the alignment of a single i8, which is still 1.
+
 #if defined(__s390x__)
 unsigned char align = 2;
 #else
@@ -69,4 +74,3 @@
 }
 
 char x[3] = "ola";
-


Index: clang/test/Sema/builtin-alloca-with-align.c
===
--- clang/test/Sema/builtin-alloca-with-align.c
+++ clang/test/Sema/builtin-alloca-with-align.c
@@ -30,4 +30,8 @@
 
 void test8(void) {
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), __alignof__(__INT64_TYPE__)); // expected-warning {{second argument to __builtin_alloca_with_align is supposed to be in bits}}
+#if defined(__csky__)
+  // expected-error@-1 {{requested alignment must be 8 or greater}}
+  // Because the alignment of long long is 4 in CSKY target
+#endif
 }
Index: clang/test/CodeGen/c-strings.c
===
--- clang/test/CodeGen/c-strings.c
+++ clang/test/CodeGen/c-strings.c
@@ -20,6 +20,11 @@
 // fails the check for "@f3.x = ... align [ALIGN]", since ALIGN is derived
 // from the alignment of a single i8, which is still 1.
 
+// XFAIL: csky
+// CSKY aligns arrays of size 4+ bytes to a 32-bit boundary, which
+// fails the check for "@f2.x = ... align [ALIGN]", since ALIGN is derived
+// from the alignment of a single i8, which is still 1.
+
 #if defined(__s390x__)
 unsigned char align = 2;
 #else
@@ -69,4 +74,3 @@
 }
 
 char x[3] = "ola";
-
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2022-05-11 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added a reviewer: steakhal.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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

Original author: steakhal


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125360

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


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


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

[PATCH] D125362: [NFC][analyzer] Transitive interestingness in BugReporter

2022-05-11 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added a reviewer: steakhal.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When making a region interesting, also mark the subregions interesting.

Original author: steakhal


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125362

Files:
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp


Index: clang/lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2261,6 +2261,12 @@
   // How to handle multiple metadata for the same region?
   if (const auto *meta = dyn_cast(sym))
 markInteresting(meta->getRegion(), TKind);
+
+  auto SubSyms = llvm::make_range(sym->symbol_begin(), sym->symbol_end());
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym))
+  insertToInterestingnessMap(InterestingSymbols, SubSym, TKind);
+  }
 }
 
 void PathSensitiveBugReport::markNotInteresting(SymbolRef sym) {
@@ -2341,10 +2347,25 @@
 return None;
   // We don't currently consider metadata symbols to be interesting
   // even if we know their region is interesting. Is that correct behavior?
-  auto It = InterestingSymbols.find(sym);
-  if (It == InterestingSymbols.end())
-return None;
-  return It->getSecond();
+  auto TryToLookupTrackingKind =
+  [this](SymbolRef Sym) -> Optional {
+auto It = InterestingSymbols.find(Sym);
+if (It == InterestingSymbols.end())
+  return None;
+return It->getSecond();
+  };
+
+  if (auto MaybeTK = TryToLookupTrackingKind(sym))
+return MaybeTK;
+
+  auto SubSyms = llvm::make_range(sym->symbol_begin(), sym->symbol_end());
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym)) {
+  if (auto MaybeTK = TryToLookupTrackingKind(SubSym))
+return MaybeTK;
+}
+  }
+  return None;
 }
 
 Optional


Index: clang/lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2261,6 +2261,12 @@
   // How to handle multiple metadata for the same region?
   if (const auto *meta = dyn_cast(sym))
 markInteresting(meta->getRegion(), TKind);
+
+  auto SubSyms = llvm::make_range(sym->symbol_begin(), sym->symbol_end());
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym))
+  insertToInterestingnessMap(InterestingSymbols, SubSym, TKind);
+  }
 }
 
 void PathSensitiveBugReport::markNotInteresting(SymbolRef sym) {
@@ -2341,10 +2347,25 @@
 return None;
   // We don't currently consider metadata symbols to be interesting
   // even if we know their region is interesting. Is that correct behavior?
-  auto It = InterestingSymbols.find(sym);
-  if (It == InterestingSymbols.end())
-return None;
-  return It->getSecond();
+  auto TryToLookupTrackingKind =
+  [this](SymbolRef Sym) -> Optional {
+auto It = InterestingSymbols.find(Sym);
+if (It == InterestingSymbols.end())
+  return None;
+return It->getSecond();
+  };
+
+  if (auto MaybeTK = TryToLookupTrackingKind(sym))
+return MaybeTK;
+
+  auto SubSyms = llvm::make_range(sym->symbol_begin(), sym->symbol_end());
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym)) {
+  if (auto MaybeTK = TryToLookupTrackingKind(SubSym))
+return MaybeTK;
+}
+  }
+  return None;
 }
 
 Optional
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125365: [NFC][analyzer] Pass down a State and a Pred ExplodedNode in the MallocChecker

2022-05-11 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added a reviewer: steakhal.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Make the predecessor ExplodedNode available in the MallocChecker's state
modeling.

Original author: steakhal


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125365

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

Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -214,16 +214,24 @@
 
 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
 
+namespace {
+struct StateAndPred {
+  ProgramStateRef State;
+  ExplodedNode *Pred;
+};
+} // namespace
+
 /// Check if the memory associated with this symbol was released.
 static bool isReleased(SymbolRef Sym, CheckerContext &C);
 
 /// Update the RefState to reflect the new memory allocation.
 /// The optional \p RetVal parameter specifies the newly allocated pointer
 /// value; if unspecified, the value of expression \p E is used.
-static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
-ProgramStateRef State,
-AllocationFamily Family,
-Optional RetVal = None);
+static StateAndPred MallocUpdateRefState(CheckerContext &C, const Expr *E,
+ ProgramStateRef State,
+ ExplodedNode *Pred,
+ AllocationFamily Family,
+ Optional RetVal = None);
 
 //===--===//
 // The modeling of memory reallocation.
@@ -455,9 +463,9 @@
   /// Process C++ operator new()'s allocation, which is the part of C++
   /// new-expression that goes before the constructor.
   LLVM_NODISCARD
-  ProgramStateRef processNewAllocation(const CXXAllocatorCall &Call,
-   CheckerContext &C,
-   AllocationFamily Family) const;
+  StateAndPred processNewAllocation(const CXXAllocatorCall &Call,
+CheckerContext &C,
+AllocationFamily Family) const;
 
   /// Perform a zero-allocation check.
   ///
@@ -490,9 +498,10 @@
   /// \param [in] State The \c ProgramState right before allocation.
   /// \returns The ProgramState right after allocation.
   LLVM_NODISCARD
-  ProgramStateRef MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
-   const OwnershipAttr *Att,
-   ProgramStateRef State) const;
+  StateAndPred MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
+const OwnershipAttr *Att,
+ProgramStateRef State,
+ExplodedNode *Pred) const;
 
   /// Models memory allocation.
   ///
@@ -504,10 +513,10 @@
   /// \param [in] State The \c ProgramState right before allocation.
   /// \returns The ProgramState right after allocation.
   LLVM_NODISCARD
-  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
-  const Expr *SizeEx, SVal Init,
-  ProgramStateRef State,
-  AllocationFamily Family);
+  static StateAndPred MallocMemAux(CheckerContext &C, const CallEvent &Call,
+   const Expr *SizeEx, SVal Init,
+   ProgramStateRef State, ExplodedNode *Pred,
+   AllocationFamily Family);
 
   /// Models memory allocation.
   ///
@@ -519,17 +528,17 @@
   /// \param [in] State The \c ProgramState right before allocation.
   /// \returns The ProgramState right after allocation.
   LLVM_NODISCARD
-  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
-  SVal Size, SVal Init,
-  ProgramStateRef State,
-  AllocationFamily Family);
+  static StateAndPred MallocMemAux(CheckerContext &C, const CallEvent &Call,
+   SVal Size, SVal Init, ProgramStateRef State,
+   ExplodedNode *Pred, AllocationFamily Family);
 
   // Check if this malloc() for special flags. At present that means 

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

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

Everything passed this time. Thanks for the patience.


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

https://reviews.llvm.org/D124658

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


[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-11 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 9 inline comments as done.
martong added a comment.

Thanks for the review guys!

> It feels like `SymbolCast` is a `UnarySymExpr`, but I like to have a distinct 
> entity for this.

Yes, their implementation is similar, but there are subtle differences.

> Anyway. There are a lot more places where we visit and handle all SymExpr 
> kinds.
> Such as: 
> `SValExplainer`, `SymbolExpressor`, `SymbolicRangeInferrer`, 
> `SimpleSValBuilder::simplifySValOnce()::Simplifier`, `TypeRetrievingVisitor`.
>
> Out of these, I think `SValExplainer`, `SymbolExpressor`, and  
> `TypeRetrievingVisitor` are the crucial ones to have consistent behavior.
> On top of these, the rest of them e.g. the constraint manager and 
> simplification just improve the reasoning about these, so they probably can 
> be done incrementally.

Okay, I've extended the `SValExplainer`, `SymbolExpressor` and the 
`Simplifier`. `TypeRetrievingVisitor` uses the virtual `getType()` function of 
`SymExpr` and we override that in `UnarySymExpr`, so that is already handled. 
I'd like to handle the constraint manager related things 
(`SymbolicRangeInferrer`) in a separate patch.

> I suspect you'll catch a few crashes/assertion failures if you run this on 
> real-world code, due to various parts of the static analyzer being startled 
> by the new thing, so I really recommend doing this.

Yeah, I am on it.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h:321
+  : SymExpr(UnarySymExprKind), Operand(In), Op(Op), T(T) {
+assert(classof(this));
+// Unary expressions are results of arithmetic. Pointer arithmetic is not

steakhal wrote:
> This is always true, right?
Yes. Maybe that is not meaningful anymore (since classof is impelented in the 
class properly). So I've deleted it.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h:325
+// sub-regions to regions.
+assert(isValidTypeForSymbol(T) && !Loc::isLocType(T));
+  }

steakhal wrote:
> I would prefer distinct assertions. This way if it triggers we can know which 
> condition is violated.
Ok, I've split them up.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h:338
+
+  void dumpToStream(raw_ostream &os) const override;
+

NoQ wrote:
> `LLVM_DUMP_METHOD`?
`SymbolManager.cpp` does that for the base class' function:
```
LLVM_DUMP_METHOD void SymExpr::dump() const { dumpToStream(llvm::errs()); }
```



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h:352
+
+  // Implement isa support.
+  static bool classof(const SymExpr *SE) {

steakhal wrote:
> I see that all the rest of the classes have this comment, but I found them 
> not too useful.
I'd like to keep it consistent with the other classes, besides the comment 
might  be useful for newcomers.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:104
+   QualType type) {
+  assert(operand);
+  assert(!Loc::isLocType(type));

NoQ wrote:
> steakhal wrote:
> > I think we should assert that we expect only `UO_Minus` (-), `UO_Not` (~).
> > The rest of the `UO_*` doesn't seem to be relevant anyway: PostInc, 
> > PostDec, PreInc, PreDec, AddrOf, Deref, Plus, LNot, Real, Imag, Extension, 
> > Coawait.
> Actually, let's put such assertion in the constructor. The earlier we catch 
> the problem the better.
Ok, I've added the assertion to the ctor.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:105-106
 return X.castAs().evalComplement(*this);
   default:
 return UnknownVal();
   }

steakhal wrote:
> Also handle it here.
Ok, done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D125318: [analyzer] Add UnarySymExpr

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

- Handle UnarySymExpr in SValExplainer
- Handle UnarySymExpr in SymbolExpressor
- Handle UnarySymExpr in SimpleSvalBuilder's Simplifier
- Better assertions
- Handle UO_Not


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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

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

[PATCH] D125258: [docs][pp-trace] Remove FileNotFound callback

2022-05-11 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125258

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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Do you need help landing this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Sergey Semushin via Phabricator via cfe-commits
predelnik added a comment.

Probably, yes. I didn't know I have to do it myself, sorry.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Sergey Semushin via Phabricator via cfe-commits
predelnik added a comment.

Ok I've found it on a guide here at last 
https://llvm.org/docs/MyFirstTypoFix.html
Please land a patch for me, @curdeius, my author data is “Sergey Semushin 
predel...@gmail.com”
Thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[clang-tools-extra] ba7b6f4 - [docs][pp-trace] Remove FileNotFound callback

2022-05-11 Thread via cfe-commits

Author: CHIANG, YU-HSUN (Tommy Chiang, oToToT)
Date: 2022-05-11T18:14:25+08:00
New Revision: ba7b6f46b37b1926552e96bd102b995f6d36de04

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

LOG: [docs][pp-trace] Remove FileNotFound callback

`FileNotFound` preprocessor callback is removed in D119708.
We should also remove it from the documentation.

Reviewed by: jansvoboda11

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

Added: 


Modified: 
clang-tools-extra/docs/pp-trace.rst

Removed: 




diff  --git a/clang-tools-extra/docs/pp-trace.rst 
b/clang-tools-extra/docs/pp-trace.rst
index 20556cdc697e4..84a5ae6ed6c60 100644
--- a/clang-tools-extra/docs/pp-trace.rst
+++ b/clang-tools-extra/docs/pp-trace.rst
@@ -49,7 +49,6 @@ Command Line Options
 
   * FileChanged
   * FileSkipped
-  * FileNotFound
   * InclusionDirective
   * moduleImport
   * EndOfMainFile
@@ -200,26 +199,6 @@ Example:::
 FilenameTok: "filename.h"
 FileType: C_User
 
-`FileNotFound 
`_
 Callback
-^^
-
-FileNotFound is called when an inclusion directive results in a file-not-found 
error.
-
-Argument descriptions:
-
-==   ==   
== 
=
-Argument NameArgument Value SyntaxClang 
C++ Type Description
-==   ==   
== 
=
-FileName "(file)" 
StringRef  The name of the file being included, as written 
in the source code.
-RecoveryPath (path)   
SmallVectorImpl  If this client indicates that it can recover 
from this missing file, the client should set this as an additional header 
search patch.
-==   ==   
== 
=
-
-Example:::
-
-  - Callback: FileNotFound
-FileName: "/path/filename.h"
-RecoveryPath:
-
 `InclusionDirective 
`_
 Callback
 

 



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


[PATCH] D125258: [docs][pp-trace] Remove FileNotFound callback

2022-05-11 Thread Tommy Chiang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGba7b6f46b37b: [docs][pp-trace] Remove FileNotFound callback 
(authored by oToToT).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125258

Files:
  clang-tools-extra/docs/pp-trace.rst


Index: clang-tools-extra/docs/pp-trace.rst
===
--- clang-tools-extra/docs/pp-trace.rst
+++ clang-tools-extra/docs/pp-trace.rst
@@ -49,7 +49,6 @@
 
   * FileChanged
   * FileSkipped
-  * FileNotFound
   * InclusionDirective
   * moduleImport
   * EndOfMainFile
@@ -200,26 +199,6 @@
 FilenameTok: "filename.h"
 FileType: C_User
 
-`FileNotFound 
`_
 Callback
-^^
-
-FileNotFound is called when an inclusion directive results in a file-not-found 
error.
-
-Argument descriptions:
-
-==   ==   
== 
=
-Argument NameArgument Value SyntaxClang 
C++ Type Description
-==   ==   
== 
=
-FileName "(file)" 
StringRef  The name of the file being included, as written 
in the source code.
-RecoveryPath (path)   
SmallVectorImpl  If this client indicates that it can recover 
from this missing file, the client should set this as an additional header 
search patch.
-==   ==   
== 
=
-
-Example:::
-
-  - Callback: FileNotFound
-FileName: "/path/filename.h"
-RecoveryPath:
-
 `InclusionDirective 
`_
 Callback
 

 


Index: clang-tools-extra/docs/pp-trace.rst
===
--- clang-tools-extra/docs/pp-trace.rst
+++ clang-tools-extra/docs/pp-trace.rst
@@ -49,7 +49,6 @@
 
   * FileChanged
   * FileSkipped
-  * FileNotFound
   * InclusionDirective
   * moduleImport
   * EndOfMainFile
@@ -200,26 +199,6 @@
 FilenameTok: "filename.h"
 FileType: C_User
 
-`FileNotFound `_ Callback
-^^
-
-FileNotFound is called when an inclusion directive results in a file-not-found error.
-
-Argument descriptions:
-
-==   ==   == =
-Argument NameArgument Value SyntaxClang C++ Type Description
-==   ==   == =
-FileName "(file)" StringRef  The name of the file being included, as written in the source code.
-RecoveryPath (path)   SmallVectorImpl  If this client indicates that it can recover from this missing file, the client should set this as an additional header search patch.
-==   ==   == =
-
-Example:::
-
-  - Callback: FileNotFound
-FileName: "/path/filename.h"
-RecoveryPath:
-
 `InclusionDirective `_ Callback
 ^^

[clang] 786c721 - Add extension diagnostic for linemarker directives

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

Author: Ken Matsui
Date: 2022-05-11T06:42:00-04:00
New Revision: 786c721c2bbd2e0646e314671e010859550423bf

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

LOG: Add extension diagnostic for linemarker directives

This adds the -Wgnu-line-marker diagnostic flag, grouped under -Wgnu,
to warn about use of the GNU linemarker preprocessor extension.

Fixes #55067

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

Added: 
clang/test/Preprocessor/line-directive-system-headers.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/lib/Lex/PPDirectives.cpp
clang/test/Preprocessor/line-directive.c
clang/test/SemaCXX/constexpr-string.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9841ae5c52973..5a3b2066d68fc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -214,6 +214,9 @@ Improvements to Clang's diagnostics
   the ``-Wunreachable-code`` flag) which is enabled by default and warns the
   user about ``_Generic`` selection associations which are unreachable because
   the type specified is an array type or a qualified type.
+- Added the ``-Wgnu-line-marker`` diagnostic flag (grouped under the ``-Wgnu``
+  flag) which is a portability warning about use of GNU linemarker preprocessor
+  directives. Fixes `Issue 55067 
`_.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 1159f49e76f71..a7c34038ba3f7 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -450,6 +450,7 @@ def : DiagGroup<"init-self">;
 def : DiagGroup<"inline">;
 def : DiagGroup<"invalid-pch">;
 def GNULabelsAsValue : DiagGroup<"gnu-label-as-value">;
+def GNULineMarker : DiagGroup<"gnu-line-marker">;
 def LiteralRange : DiagGroup<"literal-range">;
 def LocalTypeTemplateArgs : DiagGroup<"local-type-template-args",
   [CXX98CompatLocalTypeTemplateArgs]>;
@@ -1113,7 +1114,7 @@ def GNU : DiagGroup<"gnu", [GNUAlignofExpression, 
GNUAnonymousStruct,
 VLAExtension, GNUFlexibleArrayInitializer,
 GNUFlexibleArrayUnionMember, GNUFoldingConstant,
 GNUImaginaryConstant, GNUIncludeNext,
-GNULabelsAsValue, GNUNullPointerArithmetic,
+GNULabelsAsValue, GNULineMarker, 
GNUNullPointerArithmetic,
 GNUPointerArith, RedeclaredClassMember,
 GNURedeclaredEnum, GNUStatementExpression,
 GNUStaticFloatInit,

diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 543ce8a3649d1..01866d9d0eb7b 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -427,6 +427,10 @@ def note_macro_expansion_here : Note<"expansion of macro 
%0 requested here">;
 def ext_pp_opencl_variadic_macros : Extension<
   "variadic macros are a Clang extension in OpenCL">;
 
+def ext_pp_gnu_line_directive : Extension<
+  "this style of line directive is a GNU extension">,
+  InGroup;
+
 def err_pp_invalid_directive : Error<"invalid preprocessing directive">;
 def err_pp_directive_required : Error<
   "%0 must be used within a preprocessing directive">;

diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 2d942aacbf1db..1ef1ba16bcd31 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1431,6 +1431,7 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) {
   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
   // string followed by eod.
   if (StrTok.is(tok::eod)) {
+Diag(StrTok, diag::ext_pp_gnu_line_directive);
 // Treat this like "#line NN", which doesn't change file characteristics.
 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
   } else if (StrTok.isNot(tok::string_literal)) {
@@ -1458,6 +1459,9 @@ void Preprocessor::HandleDigitDirective(Token &DigitTok) {
 // If a filename was present, read any flags that are present.
 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
   return;
+if (!SourceMgr.isWrittenInBuiltinFile(DigitTok.getLocation()) &&
+!SourceMgr.isWrittenInCommandLineFile(DigitTok.getLocation()))
+  Diag(StrTok, diag::ext_pp_gnu_line_directive);
 
 //

[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-11 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 rG786c721c2bbd: Add extension diagnostic for linemarker 
directives (authored by ken-matsui, committed by aaron.ballman).

Changed prior to commit:
  https://reviews.llvm.org/D124534?vs=428450&id=428615#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Preprocessor/line-directive-system-headers.c
  clang/test/Preprocessor/line-directive.c
  clang/test/SemaCXX/constexpr-string.cpp

Index: clang/test/SemaCXX/constexpr-string.cpp
===
--- clang/test/SemaCXX/constexpr-string.cpp
+++ clang/test/SemaCXX/constexpr-string.cpp
@@ -7,7 +7,7 @@
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only -verify -pedantic -Wno-vla-extension -fno-signed-char
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only -verify -pedantic -Wno-vla-extension -fno-wchar -DNO_PREDEFINED_WCHAR_T
 
-# 9 "/usr/include/string.h" 1 3 4
+# 9 "/usr/include/string.h" 1 3 4  // expected-warning {{this style of line directive is a GNU extension}}
 extern "C" {
   typedef decltype(sizeof(int)) size_t;
 
@@ -29,7 +29,7 @@
 }
 # 25 "SemaCXX/constexpr-string.cpp" 2
 
-# 27 "/usr/include/wchar.h" 1 3 4
+# 27 "/usr/include/wchar.h" 1 3 4  // expected-warning {{this style of line directive is a GNU extension}}
 extern "C" {
 #if NO_PREDEFINED_WCHAR_T
   typedef decltype(L'0') wchar_t;
Index: clang/test/Preprocessor/line-directive.c
===
--- clang/test/Preprocessor/line-directive.c
+++ clang/test/Preprocessor/line-directive.c
@@ -9,8 +9,8 @@
 # 20 "" 2
 
 // a push/pop before any other line control
-# 10 "enter-0" 1
-# 11 "" 2 // pop to main file
+# 10 "enter-0" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 11 "" 2 // pop to main file: expected-warning {{this style of line directive is a GNU extension}}
 #error MAIN7
 // expected-error@-1{{MAIN7}}
 
@@ -27,13 +27,15 @@
 #define A 42 "foo"
 #line A
 
-# 42
-# 42 "foo"
+# 42 // expected-warning {{this style of line directive is a GNU extension}}
+# 42 "foo" // expected-warning {{this style of line directive is a GNU extension}}
 # 42 "foo" 2 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}}
+// The next two lines do not get diagnosed because they are considered to be
+// within the system header, where diagnostics are suppressed.
 # 42 "foo" 1 3  // enter
 # 42 "foo" 2 3  // exit
 # 42 "foo" 2 3 4 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}}
-# 42 "foo" 3 4
+# 42 "foo" 3 4 // expected-warning {{this style of line directive is a GNU extension}}
 
 # 'a'// expected-error {{invalid preprocessing directive}}
 # 42 'f' // expected-error {{invalid filename for line marker directive}}
@@ -54,7 +56,7 @@
 
 // Verify that linemarker diddling of the system header flag works.
 
-# 192 "glomp.h" // not a system header.
+# 192 "glomp.h" // not a system header.: expected-warning {{this style of line directive is a GNU extension}}
 typedef int x;  // expected-note {{previous definition is here}}
 typedef int x;  // expected-warning {{redefinition of typedef 'x' is a C11 feature}}
 
@@ -97,7 +99,7 @@
 #line 010  // expected-warning {{#line directive interprets number as decimal, not octal}}
 extern int array[__LINE__ == 10 ? 1:-1];
 
-# 020  // expected-warning {{GNU line marker directive interprets number as decimal, not octal}}
+# 020  // expected-warning {{GNU line marker directive interprets number as decimal, not octal}} expected-warning {{this style of line directive is a GNU extension}}
 extern int array_gnuline[__LINE__ == 20 ? 1:-1];
 
 /* PR3917 */
@@ -106,7 +108,7 @@
 _\
 _LINE__ == 42 ? 1: -1];  /* line marker is location of first _ */
 
-# 51
+# 51 // expected-warning {{this style of line directive is a GNU extension}}
 extern char array2_gnuline[\
 _\
 _LINE__ == 52 ? 1: -1];  /* line marker is location of first _ */
@@ -115,12 +117,12 @@
 #line 0 "line-directive.c" // expected-warning {{#line directive with zero argument is a GNU extension}}
 undefined t; // expected-error {{unknown type name 'undefined'}}
 
-# 115 "main"
-# 116 "enter-1" 1
-# 117 "enter-2" 1
-# 118 "" 2 // pop to enter-1
+# 115 "main" // expected-warning {{this style of line directive is a GNU extension}}
+# 116 "enter-1" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 117 "enter-2" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 118 "" 2 // pop to enter-1: expected-warn

[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

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

In D124534#3504641 , @ken-matsui 
wrote:

> In D124534#3504610 , @aaron.ballman 
> wrote:
>
>> LGTM, thank you for all the hard work on this! I assume you need me to land 
>> this on your behalf -- if so, can you let me know what name and email 
>> address you would like me to use for patch attribution?
>
> Thank you so much for your support and approval!

Happy to help!

> Yes, I do not have commit access; could you please use the following info for 
> this patch?
>
> Name: Ken Matsui
> Email: 26405363+ken-mat...@users.noreply.github.com
>
> (I use this info for every commit on GitHub, but is this what you expected? 
> Please let me know if you need an email where you can be reached out.)

That looks to be exactly what I needed, but you can double-check that you were 
properly attributed here: 
https://github.com/llvm/llvm-project/commit/786c721c2bbd2e0646e314671e010859550423bf

>> I think we should add a release note for this to let folks know about the 
>> new warning group (there's a "Improvements to Clang's diagnostics" in 
>> clang/docs/ReleaseNotes.rst). You can either add one to this patch, or I can 
>> add one for you when I go to land, I'm fine either way.
>
> Could you please add it to this patch for this time?
> I would like to add one next time by referring to how you do.

I added one when I landed. I also adjusted the commit message slightly from 
what you have here in Phab for some added clarity.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D125340: [clang][NFC][AST] rename the ImportError to ASTImportError

2022-05-11 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

What are the benefits of this renaming? I mean is there a name clash? Do we 
have another kind of "import" in Clang or in some of the dependent projects, 
don't we?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125340

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


[clang] c7ba568 - Fix test; we now expect a pedantic warning

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

Author: Aaron Ballman
Date: 2022-05-11T06:52:21-04:00
New Revision: c7ba568f40b2d6cbae781223529f63063785b0cf

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

LOG: Fix test; we now expect a pedantic warning

This fixes:
https://lab.llvm.org/buildbot/#/builders/109/builds/38337

Added: 


Modified: 
clang/test/SemaCUDA/noinline.cu

Removed: 




diff  --git a/clang/test/SemaCUDA/noinline.cu b/clang/test/SemaCUDA/noinline.cu
index bd963436c2138..ce4dfe35ceaa8 100644
--- a/clang/test/SemaCUDA/noinline.cu
+++ b/clang/test/SemaCUDA/noinline.cu
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify=cuda %s
-// RUN: %clang_cc1 -fsyntax-only -verify=cuda -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify=pedantic -pedantic %s
 // RUN: %clang_cc1 -fsyntax-only -verify=cpp -x c++ %s
 
 // cuda-no-diagnostics
@@ -14,6 +14,6 @@ __attribute__((__noinline__)) void fun3() { }
 __noinline__ void fun5() {}
 
 #undef __noinline__
-#10 "cuda.h" 3
+#10 "cuda.h" 3 // pedantic-warning {{this style of line directive is a GNU 
extension}}
 #define __noinline__ __attribute__((__noinline__))
 __noinline__ void fun6() {}



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


[PATCH] D124750: [MLIR] Add a utility to sort the operands of commutative ops

2022-05-11 Thread Jeff Niu via Phabricator via cfe-commits
Mogball added a comment.

I'm open to iterating in tree. Landing this utility first and then try adding 
it as a canonicalization SGTM.

The string could be replaced with an array of tuples (yuck) for now. An enum 
(constant, block arg, everything else) plus the OperationName.

Attributes need to be handled somehow possibly by adding the op's dictionary 
attribute and using a deep compare.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124750

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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

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

In D124534#3505709 , @aaron.ballman 
wrote:

> In D124534#3504641 , @ken-matsui 
> wrote:
>
>> (I use this info for every commit on GitHub, but is this what you expected? 
>> Please let me know if you need an email where you can be reached out.)
>
> That looks to be exactly what I needed, but you can double-check that you 
> were properly attributed here: 
> https://github.com/llvm/llvm-project/commit/786c721c2bbd2e0646e314671e010859550423bf

Actually, it does raise an interesting issue -- I don't think you'll get build 
failure emails when using that address. After a patch is landed, a bunch of 
build bots test the patch out and when there's a failure, they send email to 
everyone on the blame list. You should probably use an email address that 
receives email for future commits (or when you go to obtain your own commit 
privileges) so that you can receive those emails.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

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



> That looks to be exactly what I needed, but you can double-check that you 
> were properly attributed here: 
> https://github.com/llvm/llvm-project/commit/786c721c2bbd2e0646e314671e010859550423bf
> I added one when I landed. I also adjusted the commit message slightly from 
> what you have here in Phab for some added clarity.

Thank you! I was able to confirm that I was attributed.

In D124534#3505729 , @aaron.ballman 
wrote:

> In D124534#3505709 , @aaron.ballman 
> wrote:
>
>> In D124534#3504641 , @ken-matsui 
>> wrote:
>>
>>> (I use this info for every commit on GitHub, but is this what you expected? 
>>> Please let me know if you need an email where you can be reached out.)
>>
>> That looks to be exactly what I needed, but you can double-check that you 
>> were properly attributed here: 
>> https://github.com/llvm/llvm-project/commit/786c721c2bbd2e0646e314671e010859550423bf
>
> Actually, it does raise an interesting issue -- I don't think you'll get 
> build failure emails when using that address. After a patch is landed, a 
> bunch of build bots test the patch out and when there's a failure, they send 
> email to everyone on the blame list. You should probably use an email address 
> that receives email for future commits (or when you go to obtain your own 
> commit privileges) so that you can receive those emails.

Ah, sorry. I also have a public email for GitHub (just mostly used the private 
one), so I'll share a public one in the future.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D125142: [clang][auto-init] Remove -enable flag for "zero" mode

2022-05-11 Thread JF Bastien via Phabricator via cfe-commits
jfb added a subscriber: Florian.
jfb added a comment.

I think the most relevant post from @rsmith is: 
https://discourse.llvm.org/t/making-ftrivial-auto-var-init-zero-a-first-class-option/55143/40

He has a prototype: https://reviews.llvm.org/D79249
I assume he would like someone to pursue it further, it was a good faith 
attempt at not just demanding. I'd played with it and it needed a few fixes, 
but overall it was pretty complete. Does someone want to give it a go?

That prototype would still diverge from the GCC option, which I hear isn't 
desirable.
The discussions on standardizing this are perpetually stalled whenever they 
come up, so it's not an avenue that I ever expect to turn positive.

The fact remains that people have deployed zero init widely (you're likely 
running multiple zero-init codebases to read this), and they would not ever 
deploy zero-or-trap init. That's simply a fact.

Richard had said:

> If we want a separate flag to control whether / how much we use such a 
> trapping mode, I think that could be reasonable, subject to having a good 
> answer to the language dialect concern I expressed previously (eg, maybe 
> there’s never a guarantee that we won’t insert a trap, even though with the 
> flag on its lowest setting that is actually what happens).

If someone pursues Richard's patch above, then this would seem like a mutually 
agreeable resolution.

Separately, we'd discussed narrowing the performance gap between pattern and 
zero-init, @Florian and team had done a bunch of work 2+ years ago, but I don't 
know how "done" we can claim that work is since I haven't been tracking the 
work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125142

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


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

2022-05-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaAttr.cpp:1070
+SourceLocation Loc, const llvm::SmallVectorImpl &NoBuiltins) {
+  if (!CurContext->getRedeclContext()->isFileContext()) {
+Diag(Loc, diag::err_pragma_intrinsic_function_scope) << "function";

Now that we solved the mystery of the context -- do we need 
`getRedeclContext()` here?



Comment at: clang/lib/Sema/SemaAttr.cpp:1099
 
+void Sema::AddRangeBasedNoBuiltin(FunctionDecl *FD) {
+  SmallVector V(MSFunctionNoBuiltins.begin(),

I think we should rename this function to be more specific to the pragma. How 
about `AddImplicitMSFunctionNoBuiltinAttr()` -- it's a mouthful, but it's at 
least a descriptive mouthful that won't be called too often.



Comment at: clang/lib/Sema/SemaDecl.cpp:10224
+  if (D.isFunctionDefinition()) {
 AddRangeBasedOptnone(NewFD);
+AddRangeBasedNoBuiltin(NewFD);

I'd be delighted if a follow-up NFC commit changed this name as well -- 
"RangeBased" doesn't tell me much of anything in these identifiers (it leaves 
me wondering why there's no range passed in to the function).



Comment at: clang/test/Preprocessor/pragma_microsoft.c:210-211
+#pragma function(main)   // expected-warning {{'main' is not a 
recognized builtin; consider including }}
+#pragma function(// expected-warning {{missing ')' 
after}}
+#pragma function(int)// expected-warning {{missing ')' 
after}}
+#pragma function(strcmp) asdf// expected-warning {{extra tokens at 
end}}

It's a bit unfortunate that these don't suggest that an identifier is what's 
missing given that empty parens isn't a particularly useful pragma, however, I 
don't insist on a change either.



Comment at: clang/test/Preprocessor/pragma_microsoft.c:220
+
+void pragma_function_foo() {
+#pragma function(memset) // expected-error {{'#pragma function' can only 
appear at file scope}}

It'd be pretty reasonable to add the `struct` test here as well with a comment 
that Microsoft accepts it but we reject it on purpose with an appeal to the MS 
docs that say it must appear at file scope.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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


[PATCH] D125373: [pp-trace] Print HashLoc in InclusionDirective callback

2022-05-11 Thread Tommy Chiang via Phabricator via cfe-commits
oToToT created this revision.
oToToT added reviewers: jtsoftware, klimek.
Herald added subscribers: kbarton, nemanjai.
Herald added a project: All.
oToToT requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

The HashLoc in InclusionDirective callback is an unused parameter.
Since pp-trace is also used as a test of Clang’s PPCallbacks interface,
add it to the output of pp-trace could avoid some unintended change on
it.

This shuold resolves PR52673


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125373

Files:
  clang-tools-extra/docs/pp-trace.rst
  clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
  clang-tools-extra/test/pp-trace/pp-trace-include.cpp


Index: clang-tools-extra/test/pp-trace/pp-trace-include.cpp
===
--- clang-tools-extra/test/pp-trace/pp-trace-include.cpp
+++ clang-tools-extra/test/pp-trace/pp-trace-include.cpp
@@ -51,6 +51,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (getFileEntryForID failed)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:3:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -65,6 +66,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1A.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -95,6 +97,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: "{{.*}}{{[/\\]}}Inputs/Level1A.h"
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:4:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1B.h"
 // CHECK-NEXT:   IsAngled: false
@@ -109,6 +112,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1B.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2B.h"
 // CHECK-NEXT:   IsAngled: false
Index: clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
===
--- clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
+++ clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
@@ -137,6 +137,7 @@
 llvm::StringRef SearchPath, llvm::StringRef RelativePath,
 const Module *Imported, SrcMgr::CharacteristicKind FileType) {
   beginCallback("InclusionDirective");
+  appendArgument("HashLoc", HashLoc);
   appendArgument("IncludeTok", IncludeTok);
   appendFilePathArgument("FileName", FileName);
   appendArgument("IsAngled", IsAngled);
Index: clang-tools-extra/docs/pp-trace.rst
===
--- clang-tools-extra/docs/pp-trace.rst
+++ clang-tools-extra/docs/pp-trace.rst
@@ -223,6 +223,7 @@
 Example:::
 
   - Callback: InclusionDirective
+HashLoc: 
"D:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:4:1"
 IncludeTok: include
 FileName: "Input/Level1B.h"
 IsAngled: false


Index: clang-tools-extra/test/pp-trace/pp-trace-include.cpp
===
--- clang-tools-extra/test/pp-trace/pp-trace-include.cpp
+++ clang-tools-extra/test/pp-trace/pp-trace-include.cpp
@@ -51,6 +51,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (getFileEntryForID failed)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:3:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -65,6 +66,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1A.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -95,6 +97,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: "{{.*}}{{[/\\]}}Inputs/Level1A.h"
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:4:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1B.h"
 // CHECK-NEXT:   IsAngled: false
@@ -109,6 +112,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1B.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2B.h"
 // CHECK-NEXT:   IsAngled: false
Index: clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
=

[PATCH] D125243: [OpenCL] Make -cl-ext a driver option

2022-05-11 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM; just a few minor suggestions that you can address at commit time.




Comment at: clang/docs/UsersManual.rst:3145-3146
+
+Note that some targets e.g. SPIR/SPIR-V enable all extensions/features in 
clang by
+default.
+

Was this meant to go after the command example?



Comment at: clang/docs/UsersManual.rst:3215
+  All known OpenCL extensions and features are set to supported in the generic 
targets,
+  however :option:`-cl-ext` flag can be used to alter these settings.
+




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

https://reviews.llvm.org/D125243

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


[clang] 0035f71 - [CUDA] Create offloading entries when using the new driver

2022-05-11 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-05-11T07:30:21-04:00
New Revision: 0035f7154c2a80c58aea6c6dfcac548050e4c5e0

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

LOG: [CUDA] Create offloading entries when using the new driver

The changes made in D123460 generalized the code generation for OpenMP's
offloading entries. We can use the same scheme to register globals for
CUDA code. This patch adds the code generation to create these
offloading entries when compiling using the new offloading driver mode.
The offloading entries are simple structs that contain the information
necessary to register the global. The struct used is as follows:

```
Type struct __tgt_offload_entry {
  void*addr;  // Pointer to the offload entry info.
  // (function or global)
  char*name;  // Name of the function or global.
  size_t  size;   // Size of the entry info (0 if it a function).
  int32_t flags;
  int32_t reserved;
};
```

Currently CUDA handles RDC code generation by deferring the registration
of globals in the current TU to a callback function containing the
modules ID. Later all the module IDs will be used to register all of the
globals at once. Rather than mimic this, offloading entries allow us to
mimic the way OpenMP registers globals. That is, we create a simple
global struct for each device global to be registered. These are placed
at a special section `cuda_offloading_entires`. Because this section is
a valid C-identifier, the linker will profide a `__start` and `__stop`
pointer that we can use to iterate and register all globals at runtime.

the registration requires a flag variable to indicate which registration
function to use. I have assigned the flags somewhat arbitrarily, but
these use the following values.

Kernel: 0
Variable: 0
Managed: 1
Surface: 2
Texture: 3

Depends on D120272

Reviewed By: tra

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

Added: 
clang/test/CodeGenCUDA/offloading-entries.cu

Modified: 
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/CodeGen/CGCUDARuntime.h
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index d852fe8f886ee..e7192875c4a74 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -266,6 +266,7 @@ LANGOPT(GPUAllowDeviceInit, 1, 0, "allowing device side 
global init functions fo
 LANGOPT(GPUMaxThreadsPerBlock, 32, 1024, "default max threads per block for 
kernel launch bounds for HIP")
 LANGOPT(GPUDeferDiag, 1, 0, "defer host/device related diagnostic messages for 
CUDA/HIP")
 LANGOPT(GPUExcludeWrongSideOverloads, 1, 0, "always exclude wrong side 
overloads in overloading resolution for CUDA/HIP")
+LANGOPT(OffloadingNewDriver, 1, 0, "use the new driver for generating 
offloading code.")
 
 LANGOPT(SYCLIsDevice  , 1, 0, "Generate code for SYCL device")
 LANGOPT(SYCLIsHost, 1, 0, "SYCL host compilation")

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index ae0048f2a24e6..a9dd4ca65333c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2526,9 +2526,9 @@ defm openmp_optimistic_collapse : 
BoolFOption<"openmp-optimistic-collapse",
   PosFlag, NegFlag, 
BothFlags<[NoArgumentUnused, HelpHidden]>>;
 def static_openmp: Flag<["-"], "static-openmp">,
   HelpText<"Use the static host OpenMP runtime while linking.">;
-def offload_new_driver : Flag<["--"], "offload-new-driver">, 
Flags<[CC1Option]>, Group,
-  HelpText<"Use the new driver for offloading compilation.">;
-def no_offload_new_driver : Flag<["--"], "no-offload-new-driver">, 
Flags<[CC1Option]>, Group,
+def offload_new_driver : Flag<["--"], "offload-new-driver">, 
Flags<[CC1Option]>, Group,
+  MarshallingInfoFlag>, HelpText<"Use the new 
driver for offloading compilation.">;
+def no_offload_new_driver : Flag<["--"], "no-offload-new-driver">, 
Flags<[CC1Option]>, Group,
   HelpText<"Don't Use the new driver for offloading compilation.">;
 def offload_device_only : Flag<["--"], "offload-device-only">,
   HelpText<"Only compile for the offloading device.">;
@@ -2543,7 +2543,7 @@ def cuda_host_only : Flag<["--"], "cuda-host-only">, 
Alias,
 def cuda_compile_host_device : Flag<["--"], "cuda-compile-host-device">, 
Alias,
   HelpText<"Compile CUDA code for both host and device (default). Has no "
"effect on non-CUDA compilations.">;
-def fopenmp_new_driver : Flag<["-"], "fopenmp-new-driver">, 
Flags<[CC1Option]>, Group,
+def fopenmp_new_driver : Flag<["-"], "fopenmp-new-driver">, 
Flags<[CC1Option]>, Gr

[clang] e7858a9 - [Cuda] Add initial support for wrapping CUDA images in the new driver.

2022-05-11 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-05-11T07:30:23-04:00
New Revision: e7858a9fab8c11a44868ad4e0572c6c7618b219a

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

LOG: [Cuda] Add initial support for wrapping CUDA images in the new driver.

This patch adds the initial support for wrapping CUDA images. This
requires changing some of the logic for how we bundle images. We now
need to copy the image for all kinds that are active for the
architecture. Then we need to run a separate wrapping job if the Kind is
Cuda. For cuda wrapping we need to use the `fatbinary` program from the
CUDA SDK to bundle all the binaries together. This is then passed to a
new function to perfom the actual module code generation that will be
implemented in a later patch.

Depends on D120273 D123471

Reviewed By: tra

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

Added: 


Modified: 
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
clang/tools/clang-linker-wrapper/OffloadWrapper.h
llvm/include/llvm/Object/OffloadBinary.h

Removed: 




diff  --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index b9555df3d16f6..68e2f3dd7def5 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -166,12 +166,12 @@ static constexpr unsigned FatbinaryOffset = 0x50;
 
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
-  DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
+  DeviceFile(OffloadKind Kind, StringRef TheTriple, StringRef Arch,
  StringRef Filename, bool IsLibrary = false)
   : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename),
 IsLibrary(IsLibrary) {}
 
-  std::string Kind;
+  OffloadKind Kind;
   std::string TheTriple;
   std::string Arch;
   std::string Filename;
@@ -183,15 +183,28 @@ namespace llvm {
 /// assume device files with matching architectures and triples but 
diff erent
 /// offloading kinds should be handlded together, this may not be true in the
 /// future.
+
+// Provide DenseMapInfo for OffloadKind.
+template <> struct DenseMapInfo {
+  static inline OffloadKind getEmptyKey() { return OFK_LAST; }
+  static inline OffloadKind getTombstoneKey() {
+return static_cast(OFK_LAST + 1);
+  }
+  static unsigned getHashValue(const OffloadKind &Val) { return Val * 37U; }
+
+  static bool isEqual(const OffloadKind &LHS, const OffloadKind &RHS) {
+return LHS == RHS;
+  }
+};
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
-return {DenseMapInfo::getEmptyKey(),
+return {DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey()};
   }
   static DeviceFile getTombstoneKey() {
-return {DenseMapInfo::getTombstoneKey(),
+return {DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey()};
@@ -233,7 +246,7 @@ DeviceFile getBitcodeLibrary(StringRef LibraryStr) {
   auto DeviceAndPath = StringRef(LibraryStr).split('=');
   auto StringAndArch = DeviceAndPath.first.rsplit('-');
   auto KindAndTriple = StringAndArch.first.split('-');
-  return DeviceFile(KindAndTriple.first, KindAndTriple.second,
+  return DeviceFile(getOffloadKind(KindAndTriple.first), KindAndTriple.second,
 StringAndArch.second, DeviceAndPath.second);
 }
 
@@ -364,8 +377,8 @@ Error extractOffloadFiles(StringRef Contents, StringRef 
Prefix,
 if (Error E = Output->commit())
   return E;
 
-DeviceFiles.emplace_back(Kind, Binary.getTriple(), Binary.getArch(),
- TempFile, IsLibrary);
+DeviceFiles.emplace_back(Binary.getOffloadKind(), Binary.getTriple(),
+ Binary.getArch(), TempFile, IsLibrary);
 
 Offset += Binary.getSize();
   }
@@ -689,6 +702,39 @@ Expected link(ArrayRef 
InputFiles, Triple TheTriple,
 
   return static_cast(TempFile);
 }
+
+Expected fatbinary(ArrayRef InputFiles,
+Triple TheTriple, ArrayRef Archs) {
+  // NVPTX uses the fatbinary program to bundle the linked images.
+  Expected FatBinaryPath =
+  findProgram("fatbinary", {CudaBinaryPath});
+  if (!FatBinaryPath)
+return FatBinaryPath.takeError();
+
+  // Create a new file to write the linked device image to.
+  SmallString<128> TempFile;
+  if (Error Err = createOutputFile(sys::path::filename(ExecutableName) +
+   "-device-" + TheTriple.getArchName(),
+   

[clang] f49d576 - [CUDA] Add wrapper code generation for registering CUDA images

2022-05-11 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-05-11T07:30:25-04:00
New Revision: f49d576a882da81292b5730af442fa38899af312

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

LOG: [CUDA] Add wrapper code generation for registering CUDA images

This patch adds the necessary code generation to create the wrapper code
that registers all the globals in CUDA. We create the necessary
functions and iterate through the list of
`__start_cuda_offloading_entries` to find which globals must be
registered. This is very similar to the code generation done currently
in Clang for non-rdc builds, but here we are registering a fully linked
fatbinary and finding the globals via the above sections.

With this we should be able to fully support basic RDC / LTO building of CUDA
code.

It's also worth noting that this does not include the necessary PTX to JIT the
image, so to use this support the offloading architecture must match the
system's architecture.

Depends on D123810

Reviewed By: tra

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

Added: 


Modified: 
clang/test/Driver/linker-wrapper-image.c
clang/test/Driver/linker-wrapper.c
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Removed: 




diff  --git a/clang/test/Driver/linker-wrapper-image.c 
b/clang/test/Driver/linker-wrapper-image.c
index c10b4c5a45e03..6badd97e2eb16 100644
--- a/clang/test/Driver/linker-wrapper-image.c
+++ b/clang/test/Driver/linker-wrapper-image.c
@@ -27,3 +27,65 @@
 // OPENMP-NEXT:   call void @__tgt_unregister_lib(%__tgt_bin_desc* 
@.omp_offloading.descriptor)
 // OPENMP-NEXT:   ret void
 // OPENMP-NEXT: }
+
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
+// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,cuda,nvptx64-nvida-cuda,sm_70
+// RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple 
x86_64-unknown-linux-gnu \
+// RUN:   -linker-path /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=CUDA
+
+// CUDA: @.fatbin_image = internal constant [0 x i8] zeroinitializer, section 
".nv_fatbin"
+// CUDA-NEXT: @.fatbin_wrapper = internal constant %fatbin_wrapper { i32 
1180844977, i32 1, i8* getelementptr inbounds ([0 x i8], [0 x i8]* 
@.fatbin_image, i32 0, i32 0), i8* null }, section ".nvFatBinSegment", align 8
+// CUDA-NEXT: @__dummy.cuda_offloading.entry = hidden constant [0 x 
%__tgt_offload_entry] zeroinitializer, section "cuda_offloading_entries"
+// CUDA-NEXT: @.cuda.binary_handle = internal global i8** null
+// CUDA-NEXT: @__start_cuda_offloading_entries = external hidden constant [0 x 
%__tgt_offload_entry]
+// CUDA-NEXT: @__stop_cuda_offloading_entries = external hidden constant [0 x 
%__tgt_offload_entry]
+// CUDA-NEXT: @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* 
}] [{ i32, void ()*, i8* } { i32 1, void ()* @.cuda.fatbin_reg, i8* null }]
+
+// CUDA: define internal void @.cuda.fatbin_reg() section ".text.startup" {
+// CUDA-NEXT: entry:
+// CUDA-NEXT:   %0 = call i8** @__cudaRegisterFatBinary(i8* bitcast 
(%fatbin_wrapper* @.fatbin_wrapper to i8*))
+// CUDA-NEXT:   store i8** %0, i8*** @.cuda.binary_handle, align 8
+// CUDA-NEXT:   call void @.cuda.globals_reg(i8** %0)
+// CUDA-NEXT:   call void @__cudaRegisterFatBinaryEnd(i8** %0)
+// CUDA-NEXT:   %1 = call i32 @atexit(void ()* @.cuda.fatbin_unreg)
+// CUDA-NEXT:   ret void
+// CUDA-NEXT: }
+
+// CUDA: define internal void @.cuda.fatbin_unreg() section ".text.startup" {
+// CUDA-NEXT: entry:
+// CUDA-NEXT:   %0 = load i8**, i8*** @.cuda.binary_handle, align 8
+// CUDA-NEXT:   call void @__cudaUnregisterFatBinary(i8** %0)
+// CUDA-NEXT:   ret void
+// CUDA-NEXT: }
+
+// CUDA: define internal void @.cuda.globals_reg(i8** %0) section 
".text.startup" {
+// CUDA-NEXT: entry:
+// CUDA-NEXT:   br i1 icmp ne ([0 x %__tgt_offload_entry]* 
@__start_cuda_offloading_entries, [0 x %__tgt_offload_entry]* 
@__stop_cuda_offloading_entries), label %while.entry, label %while.end
+
+// CUDA: while.entry:
+// CUDA-NEXT:   %entry1 = phi %__tgt_offload_entry* [ getelementptr inbounds 
([0 x %__tgt_offload_entry], [0 x %__tgt_offload_entry]* 
@__start_cuda_offloading_entries, i64 0, i64 0), %entry ], [ %7, %if.end ]
+// CUDA-NEXT:   %1 = getelementptr inbounds %__tgt_offload_entry, 
%__tgt_offload_entry* %entry1, i64 0, i32 0
+// CUDA-NEXT:   %addr = load i8*, i8** %1, align 8
+// CUDA-NEXT:   %2 = getelementptr inbounds %__tgt_offload_entry, 
%__tgt_offload_entry* %entry1, i64 0, i32 1
+// CUDA-NEXT:   %name = load i8*, i8** %2, align 8
+// CUDA-NEXT:   %3 = getelementptr inbounds %__tgt_offload_entry, 
%__tgt_offload_entry* %entry1, i64 0, i32 2
+// CUDA-NEXT:   %size = load i64, i64* %3, align 4
+// CUDA-NEXT:   %4 = icmp eq i

[PATCH] D123471: [CUDA] Create offloading entries when using the new driver

2022-05-11 Thread Joseph Huber 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 rG0035f7154c2a: [CUDA] Create offloading entries when using 
the new driver (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123471

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGCUDARuntime.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenCUDA/offloading-entries.cu

Index: clang/test/CodeGenCUDA/offloading-entries.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/offloading-entries.cu
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-globals
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-linux-gnu \
+// RUN:   --offload-new-driver -emit-llvm -o - -x cuda  %s | FileCheck \
+// RUN:   --check-prefix=HOST %s
+
+#include "Inputs/cuda.h"
+
+//.
+// HOST: @x = internal global i32 undef, align 4
+// HOST: @.omp_offloading.entry_name = internal unnamed_addr constant [8 x i8] c"_Z3foov\00"
+// HOST: @.omp_offloading.entry._Z3foov = weak constant %struct.__tgt_offload_entry { ptr @_Z18__device_stub__foov, ptr @.omp_offloading.entry_name, i64 0, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+// HOST: @.omp_offloading.entry_name.1 = internal unnamed_addr constant [8 x i8] c"_Z3barv\00"
+// HOST: @.omp_offloading.entry._Z3barv = weak constant %struct.__tgt_offload_entry { ptr @_Z18__device_stub__barv, ptr @.omp_offloading.entry_name.1, i64 0, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+// HOST: @.omp_offloading.entry_name.2 = internal unnamed_addr constant [2 x i8] c"x\00"
+// HOST: @.omp_offloading.entry.x = weak constant %struct.__tgt_offload_entry { ptr @x, ptr @.omp_offloading.entry_name.2, i64 4, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+//.
+// HOST-LABEL: @_Z18__device_stub__foov(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__foov)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void foo() {}
+// HOST-LABEL: @_Z18__device_stub__barv(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__barv)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void bar() {}
+__device__ int x = 1;
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6086,6 +6086,10 @@
options::OPT_fno_openmp_extensions);
   }
 
+  // Forward the new driver to change offloading code generation.
+  if (Args.hasArg(options::OPT_offload_new_driver))
+CmdArgs.push_back("--offload-new-driver");
+
   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
 
   const XRayArgs &XRay = TC.getXRayArgs();
Index: clang/lib/CodeGen/CGCUDARuntime.h
===
--- clang/lib/CodeGen/CGCUDARuntime.h
+++ clang/lib/CodeGen/CGCUDARuntime.h
@@ -52,6 +52,19 @@
   Texture,  // Builtin texture
 };
 
+/// The kind flag for an offloading entry.
+enum OffloadEntryKindFlag : uint32_t {
+  /// Mark the entry as a global entry. This indicates the presense of a
+  /// kernel if the size size field is zero and a variable otherwise.
+  OffloadGlobalEntry = 0x0,
+  /// Mark the entry as a managed global variable.
+  OffloadGlobalManagedEntry = 0x1,
+  /// Mark the entry as a surface variable.
+  OffloadGlobalSurfaceEntry = 0x2,
+  /// Mark the entry as a texture variable.
+  OffloadGlobalTextureEntry = 0x3,
+};
+
   private:
 unsigned Kind : 2;
 unsigned Extern : 1;
Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -157,6 +157,8 @@
   llvm::Function *makeModuleDtorFunction();
   /// Transform managed variables for device compilation.
   void transformManagedVars();
+  /// Create offloading entries to register globals in RDC mode.
+  void createOffloadingEntries();
 
 public:
   CGNVCUDARuntime(CodeGenModule &CGM);
@@ -210,7 +212,8 @@
 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
   TheModule(CGM.getModule()),
-  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
+  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode ||
+CGM.getLangOpts().OffloadingNewDriver),
   Dev

[PATCH] D123810: [Cuda] Add initial support for wrapping CUDA images in the new driver.

2022-05-11 Thread Joseph Huber 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 rGe7858a9fab8c: [Cuda] Add initial support for wrapping CUDA 
images in the new driver. (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123810

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.h
  llvm/include/llvm/Object/OffloadBinary.h

Index: llvm/include/llvm/Object/OffloadBinary.h
===
--- llvm/include/llvm/Object/OffloadBinary.h
+++ llvm/include/llvm/Object/OffloadBinary.h
@@ -31,6 +31,7 @@
   OFK_OpenMP,
   OFK_Cuda,
   OFK_HIP,
+  OFK_LAST,
 };
 
 /// The type of contents the offloading image contains.
@@ -41,6 +42,7 @@
   IMG_Cubin,
   IMG_Fatbinary,
   IMG_PTX,
+  IMG_LAST,
 };
 
 /// A simple binary serialization of an offloading file. We use this format to
Index: clang/tools/clang-linker-wrapper/OffloadWrapper.h
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.h
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.h
@@ -1,4 +1,4 @@
-//===- OffloadWrapper.h ---*- C++ -*-===//
+//===- OffloadWrapper.h --r-*- C++ -*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -12,9 +12,13 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/IR/Module.h"
 
-/// Wrap the input device images into the module \p M as global symbols and
+/// Wraps the input device images into the module \p M as global symbols and
 /// registers the images with the OpenMP Offloading runtime libomptarget.
-llvm::Error wrapBinaries(llvm::Module &M,
- llvm::ArrayRef> Images);
+llvm::Error wrapOpenMPBinaries(llvm::Module &M,
+   llvm::ArrayRef> Images);
+
+/// Wraps the input fatbinary image into the module \p M as global symbols and
+/// registers the images with the CUDA runtime.
+llvm::Error wrapCudaBinary(llvm::Module &M, llvm::ArrayRef Images);
 
 #endif
Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -257,7 +257,7 @@
 
 } // namespace
 
-Error wrapBinaries(Module &M, ArrayRef> Images) {
+Error wrapOpenMPBinaries(Module &M, ArrayRef> Images) {
   GlobalVariable *Desc = createBinDesc(M, Images);
   if (!Desc)
 return createStringError(inconvertibleErrorCode(),
@@ -266,3 +266,8 @@
   createUnregisterFunction(M, Desc);
   return Error::success();
 }
+
+llvm::Error wrapCudaBinary(llvm::Module &M, llvm::ArrayRef Images) {
+  // TODO: Implement this.
+  return Error::success();
+}
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -166,12 +166,12 @@
 
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
-  DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
+  DeviceFile(OffloadKind Kind, StringRef TheTriple, StringRef Arch,
  StringRef Filename, bool IsLibrary = false)
   : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename),
 IsLibrary(IsLibrary) {}
 
-  std::string Kind;
+  OffloadKind Kind;
   std::string TheTriple;
   std::string Arch;
   std::string Filename;
@@ -183,15 +183,28 @@
 /// assume device files with matching architectures and triples but different
 /// offloading kinds should be handlded together, this may not be true in the
 /// future.
+
+// Provide DenseMapInfo for OffloadKind.
+template <> struct DenseMapInfo {
+  static inline OffloadKind getEmptyKey() { return OFK_LAST; }
+  static inline OffloadKind getTombstoneKey() {
+return static_cast(OFK_LAST + 1);
+  }
+  static unsigned getHashValue(const OffloadKind &Val) { return Val * 37U; }
+
+  static bool isEqual(const OffloadKind &LHS, const OffloadKind &RHS) {
+return LHS == RHS;
+  }
+};
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
-return {DenseMapInfo::getEmptyKey(),
+return {DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey()};
   }
   static DeviceFile getTombstoneKey() {
-return {DenseMapInfo::getTombstoneKey(),
+return {DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey(),

[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-05-11 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf49d576a882d: [CUDA] Add wrapper code generation for 
registering CUDA images (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D123812?vs=426467&id=428622#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

Files:
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -20,6 +20,8 @@
 using namespace llvm;
 
 namespace {
+/// Magic number that begins the section containing the CUDA fatbinary.
+constexpr unsigned CudaFatMagic = 0x466243b1;
 
 IntegerType *getSizeTTy(Module &M) {
   LLVMContext &C = M.getContext();
@@ -255,6 +257,278 @@
   appendToGlobalDtors(M, Func, /*Priority*/ 1);
 }
 
+// struct fatbin_wrapper {
+//  int32_t magic;
+//  int32_t version;
+//  void *image;
+//  void *reserved;
+//};
+StructType *getFatbinWrapperTy(Module &M) {
+  LLVMContext &C = M.getContext();
+  StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
+  if (!FatbinTy)
+FatbinTy = StructType::create("fatbin_wrapper", Type::getInt32Ty(C),
+  Type::getInt32Ty(C), Type::getInt8PtrTy(C),
+  Type::getInt8PtrTy(C));
+  return FatbinTy;
+}
+
+/// Embed the image \p Image into the module \p M so it can be found by the
+/// runtime.
+GlobalVariable *createFatbinDesc(Module &M, ArrayRef Image) {
+  LLVMContext &C = M.getContext();
+  llvm::Type *Int8PtrTy = Type::getInt8PtrTy(C);
+  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+
+  // Create the global string containing the fatbinary.
+  StringRef FatbinConstantSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
+  auto *Data = ConstantDataArray::get(C, Image);
+  auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
+GlobalVariable::InternalLinkage, Data,
+".fatbin_image");
+  Fatbin->setSection(FatbinConstantSection);
+
+  // Create the fatbinary wrapper
+  StringRef FatbinWrapperSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+  Constant *FatbinWrapper[] = {
+  ConstantInt::get(Type::getInt32Ty(C), CudaFatMagic),
+  ConstantInt::get(Type::getInt32Ty(C), 1),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
+  ConstantPointerNull::get(Type::getInt8PtrTy(C))};
+
+  Constant *FatbinInitializer =
+  ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
+
+  auto *FatbinDesc =
+  new GlobalVariable(M, getFatbinWrapperTy(M),
+ /*isConstant*/ true, GlobalValue::InternalLinkage,
+ FatbinInitializer, ".fatbin_wrapper");
+  FatbinDesc->setSection(FatbinWrapperSection);
+  FatbinDesc->setAlignment(Align(8));
+
+  // We create a dummy entry to ensure the linker will define the begin / end
+  // symbols. The CUDA runtime should ignore the null address if we attempt to
+  // register it.
+  auto *DummyInit =
+  ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
+  auto *DummyEntry = new GlobalVariable(
+  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, DummyInit,
+  "__dummy.cuda_offloading.entry");
+  DummyEntry->setSection("cuda_offloading_entries");
+  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
+
+  return FatbinDesc;
+}
+
+/// Create the register globals function. We will iterate all of the offloading
+/// entries stored at the begin / end symbols and register them according to
+/// their type. This creates the following function in IR:
+///
+/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
+/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
+///
+/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
+///void *, void *, void *, void *, int *);
+/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
+///   int64_t, int32_t, int32_t);
+///
+/// void __cudaRegisterTest(void **fatbinHandle) {
+///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
+///entry != &__stop_cuda_offloading_entries; ++entry) {
+/// if (!entry->size)
+///   __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
+///  entry->name, -1, 0, 0, 0, 0, 0);
+/// else
+///   __cudaRegisterVar(fatbinHandle, entry->addr, entr

[PATCH] D125011: [MSVC] Add support for pragma alloc_text

2022-05-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1136-1137
   "expected non-wide string literal in '#pragma %0'">, InGroup;
+def warn_pragma_expected_ascii_string : Warning<
+  "expected ascii string literal in '#pragma %0'">, InGroup;
 // - Generic errors

We use `warn_pragma_expected_non_wide_string` for all the other MS pragmas, so 
I think we should use that one here. Then, if we really care to, we can make 
`warn_pragma_expected_non_wide_string` more generally about non-ASCII string 
literals in a follow up.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:991-994
+def err_pragma_expected_file_scope : Error<
+  "'#pragma %0' can only appear at file scope">;
+
+def err_pragma_alloc_text_c_linkage: Error<





Comment at: clang/lib/Parse/ParsePragma.cpp:1206
+
+  ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen, 
PragmaName);
+  if (ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,

Should we be returning `false` if this comes back `true`? I'm worried about the 
case where there's a missing right paren, we warn about the pragma being 
ignored, find the EOL token and then actually handle the pragma.



Comment at: clang/lib/Parse/ParsePragma.cpp:1176-1179
+  if (SegmentName->getCharByteWidth() != 1) {
+PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
+<< PragmaName;
+return false;

aaron.ballman wrote:
> I think we want to test `isAscii()` instead of looking at the byte width; we 
> don't want to accept `u8"whatever"` any more than we want to accept 
> `L"whatever"`.
> 
> (The diagnostic text is also pretty bad because it'll diagnose non-wide 
> literals as being wide, but that's an existing deficiency with the diagnostic 
> and can be addressed separately.)
Ugh, I'm sorry, but I steered you wrong with this comment. I didn't notice 
until now that all the other MS pragmas use `getCharByteWidth() != 1` rather 
than `isAscii()`. I think we should replicate that mistake here, and then in a 
follow-up we can fix all the MS pragmas at once so that they consistently 
handle that case. WDYT?



Comment at: clang/lib/Sema/SemaAttr.cpp:748
+&Functions) {
+  if (!CurContext->getRedeclContext()->isFileContext()) {
+Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";

Same question here about whether we need to get the redecl context or not.



Comment at: clang/test/Sema/pragma-ms-alloc-text.cpp:5
+#pragma alloc_text(a// expected-warning {{expected ',' in '#pragma 
alloc_text'}}
+#pragma alloc_text(a, a // expected-warning {{missing ')' after '#pragma 
alloc_text'}} expected-error {{use of undeclared a}}
+#pragma alloc_text(L"a", a) // expected-warning {{expected a string literal 
for the section name}}

This shows we have the parsing logic wrong -- we shouldn't get the use of 
undeclared identifier a because we shouldn't have gotten into Sema for this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125011

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


[PATCH] D125338: [HLSL] add -D option for dxc mode.

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

LGTM aside from a testing suggestion.




Comment at: clang/test/Driver/dxc_D.hlsl:5
+// CHECK:"-D" "TEST=2"
+

Maybe we should also test that the macro is actually defined?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125338

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


[PATCH] D125178: Warn if using `elifdef` & `elifndef` in not C2x & C++2b mode

2022-05-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticLexKinds.td:698
+def warn_c2x_compat_pp_directive : Warning<
+  "use of a '#%select{elifdef|elifndef}0' directive is incompatible with C 
standards before C2x">,
+  InGroup, DefaultIgnore;

(You may also need to rewrap to 80 col limits.)

And do the same for the other three, so that you can use `PPElifDiag` for it.



Comment at: clang/lib/Lex/PPDirectives.cpp:663
+
+Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef) - 1;
+

I like the way you're thinking about this, but I don't like how clever the code 
is. I'd rather update the comment on `PPElifDiag` to mention 
`warn_*_compat_pp_directive` and `ext_*_pp_directive`, and then update those 
diagnostics to have a bogus select slot for the `PED_Elif` that will never be 
used.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125178

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Preprocessor/suggest-typoed-directive.c:10
+// expected-warning@+11 {{'#elfidef' directive not found, did you mean 
'#elifdef'?}}
+// expected-warning@+11 {{'#elfindef' directive not found, did you mean 
'#elifdef'?}}
+// expected-warning@+11 {{'#elsi' directive not found, did you mean '#else'?}}

ken-matsui wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > aaron.ballman wrote:
> > > > ken-matsui wrote:
> > > > > aaron.ballman wrote:
> > > > > > ken-matsui wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > ken-matsui wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > It's interesting that this one suggested `#elifdef` instead 
> > > > > > > > > > of `#elifndef` -- is there anything that can be done for 
> > > > > > > > > > that?
> > > > > > > > > > 
> > > > > > > > > > Also, one somewhat interesting question is whether we want 
> > > > > > > > > > to recommend `#elifdef` and `#elifndef` outside of 
> > > > > > > > > > C2x/C++2b mode. Those directives only exist in the latest 
> > > > > > > > > > language standard, but Clang supports them as a conforming 
> > > > > > > > > > extension in all language modes. Given that this diagnostic 
> > > > > > > > > > is about typos, I think I'm okay suggesting the directives 
> > > > > > > > > > even in older language modes. That's as likely to be a 
> > > > > > > > > > correct suggestion as not, IMO.
> > > > > > > > > > It's interesting that this one suggested `#elifdef` instead 
> > > > > > > > > > of `#elifndef` -- is there anything that can be done for 
> > > > > > > > > > that?
> > > > > > > > > 
> > > > > > > > > I found I have to use `std::min_element` instead of 
> > > > > > > > > `std::max_element` because we are finding the nearest (most 
> > > > > > > > > minimum distance) string. Meanwhile, `#elfindef` has 2 
> > > > > > > > > distance with both `#elifdef` and `#elifndef`. After 
> > > > > > > > > replacing `std::max_element` with `std::min_element`, I could 
> > > > > > > > > suggest `#elifndef` from `#elfinndef`.
> > > > > > > > > 
> > > > > > > > > > Also, one somewhat interesting question is whether we want 
> > > > > > > > > > to recommend `#elifdef` and `#elifndef` outside of 
> > > > > > > > > > C2x/C++2b mode. Those directives only exist in the latest 
> > > > > > > > > > language standard, but Clang supports them as a conforming 
> > > > > > > > > > extension in all language modes. Given that this diagnostic 
> > > > > > > > > > is about typos, I think I'm okay suggesting the directives 
> > > > > > > > > > even in older language modes. That's as likely to be a 
> > > > > > > > > > correct suggestion as not, IMO.
> > > > > > > > > 
> > > > > > > > > I agree with you because Clang implements those directives, 
> > > > > > > > > and the suggested code will also be compilable. I personally 
> > > > > > > > > think only not compilable suggestions should be avoided. (Or, 
> > > > > > > > > we might place additional info for outside of C2x/C++2b mode 
> > > > > > > > > like `this is a C2x/C++2b feature but compilable on Clang`?)
> > > > > > > > > 
> > > > > > > > > ---
> > > > > > > > > 
> > > > > > > > > According to the algorithm of `std::min_element`, we only get 
> > > > > > > > > an iterator of the first element even if there is another 
> > > > > > > > > element that has the same distance. So, `#elfindef` only 
> > > > > > > > > suggests `#elifdef` in accordance with the order of 
> > > > > > > > > `Candidates`, and I don't think it is beautiful to depend on 
> > > > > > > > > the order of candidates. I would say that we can suggest all 
> > > > > > > > > the same distance like the following, but I'm not sure this 
> > > > > > > > > is preferable:
> > > > > > > > > 
> > > > > > > > > ```
> > > > > > > > > #elfindef // diag: unknown directive, did you mean #elifdef 
> > > > > > > > > or #elifndef?
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > I agree with you because Clang implements those directives, 
> > > > > > > > > and the suggested code will also be compilable. I personally 
> > > > > > > > > think only not compilable suggestions should be avoided. (Or, 
> > > > > > > > > we might place additional info for outside of C2x/C++2b mode 
> > > > > > > > > like this is a C2x/C++2b feature but compilable on Clang?)
> > > > > > > > 
> > > > > > > > I may be changing my mind on this a bit. I now see we don't 
> > > > > > > > issue an extension warning when using `#elifdef` or `#elifndef` 
> > > > > > > > in older language modes. That means suggesting those will be 
> > > > > > > > correct but only for Clang, and the user won't have any other 
> > > > > > > > diagnostics to tell them about the portability issue. And those 
> > > > > > > > particular macros are reasonably likely to be used in a header 
> > > > > > > > where the user is trying to aim for portability. So I'm 
> > > > > > > > starting to think we should on

[clang] dab5e10 - [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Marek Kurdej via cfe-commits

Author: Sergey Semushin
Date: 2022-05-11T14:02:51+02:00
New Revision: dab5e10ea5dbc2e6314e0e7ce54a9c51fbcb44bd

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

LOG: [clang-format] fix nested angle brackets parse inside concept definition

Due to how parseBracedList always stopped on the first closing angle
bracket and was used in parsing angle bracketed expression inside concept
definition, nested brackets inside concepts were parsed incorrectly.

nextToken() call before calling parseBracedList is required because
we were processing opening angle bracket inside parseBracedList second
time leading to incorrect logic after my fix.

Fixes https://github.com/llvm/llvm-project/issues/54943
Fixes https://github.com/llvm/llvm-project/issues/54837

Reviewed By: HazardyKnusperkeks, curdeius

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index f13e3d725cbd3..f90e8fcb834c7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2180,7 +2180,8 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto) {
+  if (Style.Language == FormatStyle::LK_Proto ||
+  ClosingBraceKind == tok::greater) {
 nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
@@ -3220,6 +3221,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
   if (!FormatTok->is(tok::less))
 return;
 
+  nextToken();
   parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
   /*ClosingBraceKind=*/tok::greater);
   break;
@@ -3260,9 +3262,11 @@ void UnwrappedLineParser::parseConstraintExpression() {
 
   // Read identifier with optional template declaration.
   nextToken();
-  if (FormatTok->is(tok::less))
+  if (FormatTok->is(tok::less)) {
+nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
+  }
   break;
 }
   } while (!eof());

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 78f7eee809c4d..8f9c7215d6193 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24114,6 +24114,12 @@ TEST_F(FormatTest, Concepts) {
   verifyFormat("template \n"
"concept Same = __is_same_as;");
 
+  verifyFormat(
+  "template \n"
+  "concept _Can_reread_dest =\n"
+  "std::forward_iterator<_OutIt> &&\n"
+  "std::same_as, 
std::iter_value_t<_OutIt>>;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3d2c3a498c724..138cab9b6b257 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -390,6 +390,18 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
   EXPECT_TOKEN(Tokens[21], tok::r_brace, TT_Unknown);
   EXPECT_EQ(Tokens[21]->MatchingParen, Tokens[15]);
   EXPECT_TRUE(Tokens[21]->ClosesRequiresClause);
+
+  Tokens =
+  annotate("template  concept C ="
+   "std::same_as, std::iter_value_t>;");
+  ASSERT_EQ(Tokens.size(), 31u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_concept, TT_Unknown);
+  EXPECT_TOKEN(Tokens[14], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[18], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[20], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[25], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[27], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[28], tok::greater, TT_TemplateCloser);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {



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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Marek Kurdej 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 rGdab5e10ea5db: [clang-format] fix nested angle brackets parse 
inside concept definition (authored by predelnik, committed by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -390,6 +390,18 @@
   EXPECT_TOKEN(Tokens[21], tok::r_brace, TT_Unknown);
   EXPECT_EQ(Tokens[21]->MatchingParen, Tokens[15]);
   EXPECT_TRUE(Tokens[21]->ClosesRequiresClause);
+
+  Tokens =
+  annotate("template  concept C ="
+   "std::same_as, std::iter_value_t>;");
+  ASSERT_EQ(Tokens.size(), 31u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_concept, TT_Unknown);
+  EXPECT_TOKEN(Tokens[14], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[18], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[20], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[25], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[27], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[28], tok::greater, TT_TemplateCloser);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24114,6 +24114,12 @@
   verifyFormat("template \n"
"concept Same = __is_same_as;");
 
+  verifyFormat(
+  "template \n"
+  "concept _Can_reread_dest =\n"
+  "std::forward_iterator<_OutIt> &&\n"
+  "std::same_as, 
std::iter_value_t<_OutIt>>;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2180,7 +2180,8 @@
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto) {
+  if (Style.Language == FormatStyle::LK_Proto ||
+  ClosingBraceKind == tok::greater) {
 nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
@@ -3220,6 +3221,7 @@
   if (!FormatTok->is(tok::less))
 return;
 
+  nextToken();
   parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
   /*ClosingBraceKind=*/tok::greater);
   break;
@@ -3260,9 +3262,11 @@
 
   // Read identifier with optional template declaration.
   nextToken();
-  if (FormatTok->is(tok::less))
+  if (FormatTok->is(tok::less)) {
+nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
+  }
   break;
 }
   } while (!eof());


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -390,6 +390,18 @@
   EXPECT_TOKEN(Tokens[21], tok::r_brace, TT_Unknown);
   EXPECT_EQ(Tokens[21]->MatchingParen, Tokens[15]);
   EXPECT_TRUE(Tokens[21]->ClosesRequiresClause);
+
+  Tokens =
+  annotate("template  concept C ="
+   "std::same_as, std::iter_value_t>;");
+  ASSERT_EQ(Tokens.size(), 31u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_concept, TT_Unknown);
+  EXPECT_TOKEN(Tokens[14], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[18], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[20], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[25], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[27], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[28], tok::greater, TT_TemplateCloser);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24114,6 +24114,12 @@
   verifyFormat("template \n"
"concept Same = __is_same_as;");
 
+  verifyFormat(
+  "template \n"
+  "concept _Can_reread_dest =\n"
+  "std::forward_iterator<_OutIt> &&\n"
+  "std::same_as, std::iter_value_t<_OutIt>>;");
+
   auto Style = getLLVMStyle();
   St

[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 created this revision.
Herald added subscribers: jdoerfert, hiraditya.
Herald added a reviewer: aaron.ballman.
Herald added a project: All.
skc7 requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This change introduces shuffle as function attribute in clang and llvm IR. It 
is used to identify __shfl_sync like cross-lane APIs [allows exchange of 
variable across all active threads]. At clang codegen, noundef attribute is 
skipped to arguments and return types for functions with shuffle attribute.

Shuffle attribute has been added as per suggestions/comments from review: 
D124158 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125378

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHIP/shuffle-attr-verify.hip
  clang/test/CodeGenHIP/shuffle-noundef-attr.hip
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/include/llvm/IR/Function.h
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -960,6 +960,7 @@
   case Attribute::NoCfCheck:
   case Attribute::MustProgress:
   case Attribute::NoProfile:
+  case Attribute::Shuffle:
 break;
   // These attributes cannot be applied to functions.
   case Attribute::Alignment:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -1804,7 +1804,8 @@
   .addAttribute(Attribute::StructRet)
   .addAttribute(Attribute::ByRef)
   .addAttribute(Attribute::ElementType)
-  .addAttribute(Attribute::AllocatedPointer);
+  .addAttribute(Attribute::AllocatedPointer)
+  .addAttribute(Attribute::Shuffle);
   }
 
 // Attributes that only apply to pointers or vectors of pointers.
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -778,6 +778,8 @@
   case Attribute::EmptyKey:
   case Attribute::TombstoneKey:
 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
+  case Attribute::Shuffle:
+return bitc::ATTR_KIND_SHUFFLE;
   }
 
   llvm_unreachable("Trying to encode unknown attribute");
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1632,6 +1632,8 @@
 return Attribute::MustProgress;
   case bitc::ATTR_KIND_HOT:
 return Attribute::Hot;
+  case bitc::ATTR_KIND_SHUFFLE:
+return Attribute::Shuffle;
   }
 }
 
Index: llvm/include/llvm/IR/Function.h
===
--- llvm/include/llvm/IR/Function.h
+++ llvm/include/llvm/IR/Function.h
@@ -626,6 +626,12 @@
 return AttributeSets.getUWTableKind();
   }
 
+  /// Determine if the function is __shfl_sync like.
+  bool isShuffle() const {
+return hasFnAttribute(Attribute::Shuffle);
+  }
+  void setShuffle() { addFnAttr(Attribute::Shuffle); }
+
   /// True if the ABI mandates (or the user requested) that this
   /// function be in a unwind table.
   bool hasUWTable() const {
Index: llvm/include/llvm/IR/Attributes.td
===
--- llvm/include/llvm/IR/Attributes.td
+++ llvm/include/llvm/IR/Attributes.td
@@ -300,6 +300,9 @@
 /// Function is required to make Forward Progress.
 def MustProgress : EnumAttr<"mustprogress", [FnAttr]>;
 
+/// Function is a __shfl_sync like API.
+def Shuffle : EnumAttr<"shuffle", [FnAttr]>;
+
 /// Target-independent string attributes.
 def LessPreciseFPMAD : StrBoolAttr<"less-precise-fpmad">;
 def NoInfsFPMath : StrBoolAttr<"no-infs-fp-math">;
Index: llvm/include/llvm/Bitcode/LLVMBitCodes.h
===
--- llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -684,6 +684,7 @@
   ATTR_KIND_NO_SANITIZE_BOUNDS = 79,
   ATTR_KIND_ALLOC_ALIGN = 80,
   ATTR_KIND_ALLOCATED_POINTER = 81,
+  ATTR_KIND_SHUFFLE = 82,
 };
 
 enum ComdatSelectionKindCodes {
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test

[clang] 06a9832 - [ASTMatchers][NFC] Fix name of matcher in docs and add a missing test

2022-05-11 Thread via cfe-commits

Author: Whisperity
Date: 2022-05-11T14:15:53+02:00
New Revision: 06a98328fc7b70756782fafff5ebfbec815cf1f5

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

LOG: [ASTMatchers][NFC] Fix name of matcher in docs and add a missing test

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index d552f4ccd7668..55c4da639a815 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -1012,7 +1012,7 @@ Node Matchers
 Matches a C++ 
static_assert declaration.
 
 Example:
-  staticAssertExpr()
+  staticAssertDecl()
 matches
   static_assert(sizeof(S) == sizeof(int))
 in

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index c16bc5f0eafde..221cab03b0ecb 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2523,7 +2523,7 @@ extern const internal::VariadicDynCastAllOfMatcher
 /// Matches a C++ static_assert declaration.
 ///
 /// Example:
-///   staticAssertExpr()
+///   staticAssertDecl()
 /// matches
 ///   static_assert(sizeof(S) == sizeof(int))
 /// in

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
index ed222a1fdf877..6723e1657c1ab 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -735,6 +735,17 @@ TEST_P(ASTMatchersTest, ParmVarDecl) {
   EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
 }
 
+TEST_P(ASTMatchersTest, StaticAssertDecl) {
+  if (!GetParam().isCXX11OrLater())
+return;
+
+  EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
+  EXPECT_TRUE(
+  notMatches("constexpr bool staticassert(bool B, const char *M) "
+ "{ return true; };\n void f() { staticassert(true, \"\"); }",
+ staticAssertDecl()));
+}
+
 TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
   if (!GetParam().isCXX()) {
 return;



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


[PATCH] D125379: [analyzer][solver] Do not negate unsigned ranges

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

This is a bugfix. Simply put, 2u - 1u != 2u - 1u. See the static
assertion in the test file. The fix simply ban the negation of unsigned
expressions. This way the we are getting a little bit more conservatie,
but at least we do not infer wrong values.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125379

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/constraint_manager_negate_difference.c


Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -122,31 +122,37 @@
   }
 }
 
+_Static_assert(12u - 1u != 1u - 12u, "Good modulo arithmetic");
 void negate_unsigned_mid(unsigned m, unsigned n) {
   if (m - n == UINT_MID) {
-clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}} 
expected-warning{{TRUE}}
   }
 }
 
 void negate_unsigned_mid2(unsigned m, unsigned n) {
   if (m - n < UINT_MID && m - n > UINT_MIN) {
-clang_analyzer_eval(n - m > UINT_MID); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m < UINT_MID); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m > UINT_MID); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m < UINT_MID); // expected-warning{{FALSE}} 
expected-warning{{TRUE}}
   }
 }
 
+
+_Static_assert(1u - 2u == UINT_MAX, "Good modulo arithmetic");
+_Static_assert(2u - 1u == 1, "Good modulo arithmetic");
 void negate_unsigned_max(unsigned m, unsigned n) {
   if (m - n == UINT_MAX) {
-clang_analyzer_eval(n - m == 1); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m != 1); // expected-warning{{FALSE}}
+// FIXME only the TRUE case should appear. But it is better to be
+// conservative than faulty.
+clang_analyzer_eval(n - m == 1); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != 1); // expected-warning{{FALSE}} 
expected-warning{{TRUE}}
   }
 }
-
 void negate_unsigned_one(unsigned m, unsigned n) {
   if (m - n == 1) {
-clang_analyzer_eval(n - m == UINT_MAX); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m < UINT_MAX);  // expected-warning{{FALSE}}
+// FIXME only the TRUE case should appear.
+clang_analyzer_eval(n - m == UINT_MAX); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m < UINT_MAX);  // expected-warning{{FALSE}} 
expected-warning{{TRUE}}
   }
 }
 
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -1454,8 +1454,7 @@
 QualType T = Sym->getType();
 
 // Do not negate unsigned ranges
-if (!T->isUnsignedIntegerOrEnumerationType() &&
-!T->isSignedIntegerOrEnumerationType())
+if (T->isUnsignedIntegerOrEnumerationType())
   return llvm::None;
 
 SymbolManager &SymMgr = State->getSymbolManager();


Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -122,31 +122,37 @@
   }
 }
 
+_Static_assert(12u - 1u != 1u - 12u, "Good modulo arithmetic");
 void negate_unsigned_mid(unsigned m, unsigned n) {
   if (m - n == UINT_MID) {
-clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}} expected-warning{{TRUE}}
   }
 }
 
 void negate_unsigned_mid2(unsigned m, unsigned n) {
   if (m - n < UINT_MID && m - n > UINT_MIN) {
-clang_analyzer_eval(n - m > UINT_MID); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m < UINT_MID); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m > UINT_MID); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+clang

[PATCH] D125006: [pseudo] Support parsing variant target symbols.

2022-05-11 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 428634.
hokein added a comment.

add a comment in cxx.bnf explaining why not making all nonterminals as start 
symbol by default.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125006

Files:
  clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
  clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRGraph.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRTable.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/Grammar.cpp
  clang-tools-extra/pseudo/lib/LRGraph.cpp
  clang-tools-extra/pseudo/lib/LRTable.cpp
  clang-tools-extra/pseudo/lib/LRTableBuild.cpp
  clang-tools-extra/pseudo/lib/cxx.bnf
  clang-tools-extra/pseudo/test/glr-variant-start.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -112,7 +112,7 @@
 b := a
   )cpp");
 
-  EXPECT_EQ(G->startSymbol(), id("_"));
+  EXPECT_EQ(G->underscore(), id("_"));
   EXPECT_THAT(Diags, UnorderedElementsAre(
  "Rule '_ := ,_opt' has a nullable RHS",
  "Rule 'null := ' has a nullable RHS",
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -344,7 +344,8 @@
   const TokenStream &Tokens = cook(lex("{ abc", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   // Verify that there is no duplicated sequence node of `expr := IDENTIFIER`
   // in the forest, see the `#1` and `=#1` in the dump string.
   EXPECT_EQ(Parsed.dumpRecursive(*G),
@@ -381,7 +382,8 @@
   const TokenStream &Tokens = cook(lex("IDENTIFIER", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   EXPECT_EQ(Parsed.dumpRecursive(*G),
 "[  0, end) test := \n"
 "[  0, end) ├─test := IDENTIFIER\n"
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -43,6 +43,9 @@
 desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
+static opt StartSymbol("start-symbol",
+desc("specify the start symbol to parse"),
+init("translation-unit"));
 
 static std::string readOrDie(llvm::StringRef Path) {
   llvm::ErrorOr> Text =
@@ -110,9 +113,9 @@
 if (ParseableStream) {
   clang::pseudo::ForestArena Arena;
   clang::pseudo::GSS GSS;
-  auto &Root =
-  glrParse(*ParseableStream,
-   clang::pseudo::ParseParams{*G, LRTable, Arena, GSS});
+  auto &Root = glrParse(
+  *ParseableStream, clang::pseudo::ParseParams{*G, LRTable, Arena, GSS},
+  clang::pseudo::findNonterminal(StartSymbol, G->table()));
   if (PrintForest)
 llvm::outs() << Root.dumpRecursive(*G, /*Abbreviated=*/true);
 
Index: clang-tools-extra/pseudo/test/glr-variant-start.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/glr-variant-start.cpp
@@ -0,0 +1,9 @@
+// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --start-symbol=statement-seq --print-forest | FileCheck %s
+
+a + a;
+// CHECK:  statement-seq~expression-statement := expression ;
+// CHECK-NEXT: ├─expression~additive-expression := additive-expression + multiplicative-expression
+// CHECK-NEXT: │ ├─additive-expression~IDENTIFIER :=
+// CHECK-NEXT: │ ├─+ :=
+// CHECK-NEXT: │ └─multiplicative-expression~IDENTIFIER :=
+// CHECK-NEXT: └─; :=
Index: clang-tools-extra/pseudo/lib/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx.bnf
@@ -23,10 +23,15 @@
 #   - optional symbols 

[PATCH] D125006: [pseudo] Support parsing variant target symbols.

2022-05-11 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

> Would including *every* nonterminal as a start symbol would blow the size up 
> a bit?
> This would eliminate some complexity in the interface.

This does increase the size, some datapoints:

- ~240 start symbols
- number of states: 1.4K -> 2K
- number of actions: 83K -> 96K
- size of table(bytes): 334K -> 388K

As discussed, the benefit is not obvious, let's leave it out now and revisit it 
when needed (added a comment in the cxx.bnf).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125006

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


[PATCH] D125379: [analyzer][solver] Do not negate unsigned ranges

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

Seems reasonable.




Comment at: clang/test/Analysis/constraint_manager_negate_difference.c:145-148
+// FIXME only the TRUE case should appear. But it is better to be
+// conservative than faulty.
+clang_analyzer_eval(n - m == 1); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != 1); // expected-warning{{FALSE}} 
expected-warning{{TRUE}}

It's not immediately clear what you refer to by the `TRUE` case. The two evals 
the opposite condition, consequently one of them should be `FALSE`. Same for 
the next case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125379

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


[PATCH] D125318: [analyzer] Add UnarySymExpr

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



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

I'm not sure if we should rely on `SVal::getType()`. I think the calling 
context should pass the type along here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 updated this revision to Diff 428635.
skc7 added a comment.

clang-format


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

https://reviews.llvm.org/D125378

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHIP/shuffle-attr-verify.hip
  clang/test/CodeGenHIP/shuffle-noundef-attr.hip
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/include/llvm/IR/Function.h
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -960,6 +960,7 @@
   case Attribute::NoCfCheck:
   case Attribute::MustProgress:
   case Attribute::NoProfile:
+  case Attribute::Shuffle:
 break;
   // These attributes cannot be applied to functions.
   case Attribute::Alignment:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -1804,7 +1804,8 @@
   .addAttribute(Attribute::StructRet)
   .addAttribute(Attribute::ByRef)
   .addAttribute(Attribute::ElementType)
-  .addAttribute(Attribute::AllocatedPointer);
+  .addAttribute(Attribute::AllocatedPointer)
+  .addAttribute(Attribute::Shuffle);
   }
 
 // Attributes that only apply to pointers or vectors of pointers.
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -778,6 +778,8 @@
   case Attribute::EmptyKey:
   case Attribute::TombstoneKey:
 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
+  case Attribute::Shuffle:
+return bitc::ATTR_KIND_SHUFFLE;
   }
 
   llvm_unreachable("Trying to encode unknown attribute");
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1632,6 +1632,8 @@
 return Attribute::MustProgress;
   case bitc::ATTR_KIND_HOT:
 return Attribute::Hot;
+  case bitc::ATTR_KIND_SHUFFLE:
+return Attribute::Shuffle;
   }
 }
 
Index: llvm/include/llvm/IR/Function.h
===
--- llvm/include/llvm/IR/Function.h
+++ llvm/include/llvm/IR/Function.h
@@ -626,6 +626,10 @@
 return AttributeSets.getUWTableKind();
   }
 
+  /// Determine if the function is __shfl_sync like.
+  bool isShuffle() const { return hasFnAttribute(Attribute::Shuffle); }
+  void setShuffle() { addFnAttr(Attribute::Shuffle); }
+
   /// True if the ABI mandates (or the user requested) that this
   /// function be in a unwind table.
   bool hasUWTable() const {
Index: llvm/include/llvm/IR/Attributes.td
===
--- llvm/include/llvm/IR/Attributes.td
+++ llvm/include/llvm/IR/Attributes.td
@@ -300,6 +300,9 @@
 /// Function is required to make Forward Progress.
 def MustProgress : EnumAttr<"mustprogress", [FnAttr]>;
 
+/// Function is a __shfl_sync like API.
+def Shuffle : EnumAttr<"shuffle", [FnAttr]>;
+
 /// Target-independent string attributes.
 def LessPreciseFPMAD : StrBoolAttr<"less-precise-fpmad">;
 def NoInfsFPMath : StrBoolAttr<"no-infs-fp-math">;
Index: llvm/include/llvm/Bitcode/LLVMBitCodes.h
===
--- llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -684,6 +684,7 @@
   ATTR_KIND_NO_SANITIZE_BOUNDS = 79,
   ATTR_KIND_ALLOC_ALIGN = 80,
   ATTR_KIND_ALLOCATED_POINTER = 81,
+  ATTR_KIND_SHUFFLE = 82,
 };
 
 enum ComdatSelectionKindCodes {
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -161,6 +161,7 @@
 // CHECK-NEXT: ScopedLockable (SubjectMatchRule_record)
 // CHECK-NEXT: Section (SubjectMatchRule_function, SubjectMatchRule_variable_is_global, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property)
 // CHECK-NEXT: SetTypestate (SubjectMatchRule_function_is_member)
+// CHECK-NEXT: Shuffle (SubjectMatchRule_function)
 // CHECK-NEXT: SpeculativeLoadHardening (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHE

[PATCH] D125178: Warn if using `elifdef` & `elifndef` in not C2x & C++2b mode

2022-05-11 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui updated this revision to Diff 428636.
ken-matsui added a comment.

Update the code as reviewed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125178

Files:
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Lexer/Inputs/unsafe-macro-2.h
  clang/test/Lexer/deprecate-macro.c
  clang/test/Preprocessor/elifdef.c
  clang/test/Preprocessor/ext-c2x-pp-directive.c
  clang/test/Preprocessor/ext-cpp2b-pp-directive.cpp
  clang/test/Preprocessor/if_warning.c
  clang/test/Preprocessor/ifdef-recover.c
  clang/test/Preprocessor/macro_misc.c
  clang/test/Preprocessor/macro_vaopt_check.cpp

Index: clang/test/Preprocessor/macro_vaopt_check.cpp
===
--- clang/test/Preprocessor/macro_vaopt_check.cpp
+++ clang/test/Preprocessor/macro_vaopt_check.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 %s -Eonly -verify -Wno-all -pedantic -std=c++20
-// RUN: %clang_cc1 %s -Eonly -verify -Wno-all -pedantic -std=c++11
-// RUN: %clang_cc1 -x c %s -Eonly -verify -Wno-all -pedantic -std=c99
+// RUN: %clang_cc1 %s -Eonly -verify -Wno-all -Wno-c++2b-extensions -pedantic -std=c++20
+// RUN: %clang_cc1 %s -Eonly -verify -Wno-all -Wno-c++2b-extensions -pedantic -std=c++11
+// RUN: %clang_cc1 -x c %s -Eonly -verify -Wno-all -Wno-c2x-extensions -pedantic -std=c99
 
 //expected-error@+1{{missing '('}}
 #define V1(...) __VA_OPT__  
Index: clang/test/Preprocessor/macro_misc.c
===
--- clang/test/Preprocessor/macro_misc.c
+++ clang/test/Preprocessor/macro_misc.c
@@ -4,6 +4,7 @@
 #ifdef defined
 #elifdef defined
 #endif
+// expected-warning@-2 {{use of a '#elifdef' directive is a C2x extension}}
 
 
 
Index: clang/test/Preprocessor/ifdef-recover.c
===
--- clang/test/Preprocessor/ifdef-recover.c
+++ clang/test/Preprocessor/ifdef-recover.c
@@ -19,12 +19,14 @@
 #if f(2
 #endif
 
-/* expected-error@+2 {{macro name missing}} */
+/* expected-error@+3 {{macro name missing}} */
+// expected-warning@+2 {{use of a '#elifdef' directive is a C2x extension}}
 #ifdef FOO
 #elifdef
 #endif
 
-/* expected-error@+2 {{macro name must be an identifier}} */
+/* expected-error@+3 {{macro name must be an identifier}} */
+// expected-warning@+2 {{use of a '#elifdef' directive is a C2x extension}}
 #ifdef FOO
 #elifdef !
 #endif
Index: clang/test/Preprocessor/if_warning.c
===
--- clang/test/Preprocessor/if_warning.c
+++ clang/test/Preprocessor/if_warning.c
@@ -5,6 +5,7 @@
 #if foo   // expected-error {{'foo' is not defined, evaluates to 0}}
 #endif
 
+// expected-warning@+2 {{use of a '#elifdef' directive is a C2x extension}}
 #ifdef foo
 #elifdef foo
 #endif
@@ -14,6 +15,7 @@
 
 
 // PR3938
+// expected-warning@+3 {{use of a '#elifdef' directive is a C2x extension}}
 #if 0
 #ifdef D
 #elifdef D
Index: clang/test/Preprocessor/ext-cpp2b-pp-directive.cpp
===
--- /dev/null
+++ clang/test/Preprocessor/ext-cpp2b-pp-directive.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify=pre-cpp2b-pedantic -pedantic %s
+// RUN: %clang_cc1 -x c++ -std=c++2b -fsyntax-only -verify=pre-cpp2b-compat -Wpre-c++2b-compat %s
+// RUN: not %clang_cc1 -x c++ -fsyntax-only -verify %s
+// RUN: not %clang_cc1 -x c++ -std=c++2b -fsyntax-only -verify -pedantic %s
+// RUN: not %clang_cc1 -x c++ -std=c++2b -fsyntax-only -verify %s
+
+int x;
+
+#if 1
+#elifdef A // #1
+#endif
+// pre-cpp2b-pedantic-warning@#1 {{use of a '#elifdef' directive is a C++2b extension}}
+// pre-cpp2b-compat-warning@#1 {{use of a '#elifdef' directive is incompatible with C++ standards before C++2b}}
+
+#if 1
+#elifndef B // #2
+#endif
+// pre-cpp2b-pedantic-warning@#2 {{use of a '#elifndef' directive is a C++2b extension}}
+// pre-cpp2b-compat-warning@#2 {{use of a '#elifndef' directive is incompatible with C++ standards before C++2b}}
+
+#if 0
+#elifdef C
+#endif
+// pre-cpp2b-pedantic-warning@-2 {{use of a '#elifdef' directive is a C++2b extension}}
+// pre-cpp2b-compat-warning@-3 {{use of a '#elifdef' directive is incompatible with C++ standards before C++2b}}
+
+#if 0
+#elifndef D
+#endif
+// pre-cpp2b-pedantic-warning@-2 {{use of a '#elifndef' directive is a C++2b extension}}
+// pre-cpp2b-compat-warning@-3 {{use of a '#elifndef' directive is incompatible with C++ standards before C++2b}}
Index: clang/test/Preprocessor/ext-c2x-pp-directive.c
===
--- /dev/null
+++ clang/test/Preprocessor/ext-c2x-pp-directive.c
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=c99-pedantic -pedantic %s
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify=pre-c2x-compat -Wpre-c2x-compat %s
+// RUN: not %clang_c

[PATCH] D125178: Warn if using `elifdef` & `elifndef` in not C2x & C++2b mode

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

Thank you for your review! I updated the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125178

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


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

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

It turns out this only makes sense for `Obj-C` code :D
Anyway, it looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125360

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 updated this revision to Diff 428637.
skc7 added a comment.

rebase


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

https://reviews.llvm.org/D125378

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHIP/shuffle-attr-verify.hip
  clang/test/CodeGenHIP/shuffle-noundef-attr.hip
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/include/llvm/IR/Function.h
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -960,6 +960,7 @@
   case Attribute::NoCfCheck:
   case Attribute::MustProgress:
   case Attribute::NoProfile:
+  case Attribute::Shuffle:
 break;
   // These attributes cannot be applied to functions.
   case Attribute::Alignment:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -1804,7 +1804,8 @@
   .addAttribute(Attribute::StructRet)
   .addAttribute(Attribute::ByRef)
   .addAttribute(Attribute::ElementType)
-  .addAttribute(Attribute::AllocatedPointer);
+  .addAttribute(Attribute::AllocatedPointer)
+  .addAttribute(Attribute::Shuffle);
   }
 
 // Attributes that only apply to pointers or vectors of pointers.
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -779,6 +779,8 @@
   case Attribute::EmptyKey:
   case Attribute::TombstoneKey:
 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
+  case Attribute::Shuffle:
+return bitc::ATTR_KIND_SHUFFLE;
   }
 
   llvm_unreachable("Trying to encode unknown attribute");
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1632,6 +1632,8 @@
 return Attribute::MustProgress;
   case bitc::ATTR_KIND_HOT:
 return Attribute::Hot;
+  case bitc::ATTR_KIND_SHUFFLE:
+return Attribute::Shuffle;
   }
 }
 
Index: llvm/include/llvm/IR/Function.h
===
--- llvm/include/llvm/IR/Function.h
+++ llvm/include/llvm/IR/Function.h
@@ -626,6 +626,10 @@
 return AttributeSets.getUWTableKind();
   }
 
+  /// Determine if the function is __shfl_sync like.
+  bool isShuffle() const { return hasFnAttribute(Attribute::Shuffle); }
+  void setShuffle() { addFnAttr(Attribute::Shuffle); }
+
   /// True if the ABI mandates (or the user requested) that this
   /// function be in a unwind table.
   bool hasUWTable() const {
Index: llvm/include/llvm/IR/Attributes.td
===
--- llvm/include/llvm/IR/Attributes.td
+++ llvm/include/llvm/IR/Attributes.td
@@ -300,6 +300,9 @@
 /// Function is required to make Forward Progress.
 def MustProgress : EnumAttr<"mustprogress", [FnAttr]>;
 
+/// Function is a __shfl_sync like API.
+def Shuffle : EnumAttr<"shuffle", [FnAttr]>;
+
 /// Target-independent string attributes.
 def LessPreciseFPMAD : StrBoolAttr<"less-precise-fpmad">;
 def NoInfsFPMath : StrBoolAttr<"no-infs-fp-math">;
Index: llvm/include/llvm/Bitcode/LLVMBitCodes.h
===
--- llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -684,6 +684,7 @@
   ATTR_KIND_NO_SANITIZE_BOUNDS = 79,
   ATTR_KIND_ALLOC_ALIGN = 80,
   ATTR_KIND_ALLOCATED_POINTER = 81,
+  ATTR_KIND_SHUFFLE = 82,
 };
 
 enum ComdatSelectionKindCodes {
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -161,6 +161,7 @@
 // CHECK-NEXT: ScopedLockable (SubjectMatchRule_record)
 // CHECK-NEXT: Section (SubjectMatchRule_function, SubjectMatchRule_variable_is_global, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property)
 // CHECK-NEXT: SetTypestate (SubjectMatchRule_function_is_member)
+// CHECK-NEXT: Shuffle (SubjectMatchRule_function)
 // CHECK-NEXT: SpeculativeLoadHardening (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEX

[PATCH] D125362: [NFC][analyzer] Transitive interestingness in BugReporter

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

I think since it changes how taint spreads, this patch deserves a test.
Could you please demonstrate the correctness of this patch?




Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:2267
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym))
+  insertToInterestingnessMap(InterestingSymbols, SubSym, TKind);





Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:2361-2366
+  auto SubSyms = llvm::make_range(sym->symbol_begin(), sym->symbol_end());
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym)) {
+  if (auto MaybeTK = TryToLookupTrackingKind(SubSym))
+return MaybeTK;
+}

The comment of `symbol_iterator` suggests that for `SymbolData` this will be 
always the symbol data itself; thus it would iterate only once.
Is this the case? If so, can we replace the loop with just the 
`isa(sym)` check?

```
  /// Iterator over symbols that the current symbol depends on.
  ///
  /// For SymbolData, it's the symbol itself; for expressions, it's the
  /// expression symbol and all the operands in it. Note, SymbolDerived is
  /// treated as SymbolData - the iterator will NOT visit the parent region.
  class symbol_iterator {...
```



Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:2363
+  for (SymbolRef SubSym : SubSyms) {
+if (SymbolData::classof(SubSym)) {
+  if (auto MaybeTK = TryToLookupTrackingKind(SubSym))




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125362

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


[PATCH] D125365: [NFC][analyzer] Pass down a State and a Pred ExplodedNode in the MallocChecker

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

Also mention in the summary that we are doing this because we want to do 
multiple transitions with different NoteTags at different handlers there.
For E.g. we want to put NoteTags when we do a taint propagation.

That being said, now we model the extent of the allocated region by simply 
binding the size argument of the allocation call to the extent map.
We won't need to propagate taint to the extent if the size expression was 
already tainted. Thus, I'm not even sure we actually need this change anymore.
Could you please check it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125365

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


[PATCH] D124874: [clang] add -fmodule-file-home-is-cwd

2022-05-11 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan accepted this revision.
urnathan 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/D124874/new/

https://reviews.llvm.org/D124874

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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-11 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan added a comment.

Hi, this patch causes a test failure on AIX 
https://lab.llvm.org/buildbot/#/builders/214/builds/1221/steps/6/logs/FAIL__Clang__noinline_cu

Could you please make a fix or revert if it takes too long?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread Nikita Popov via Phabricator via cfe-commits
nikic requested changes to this revision.
nikic added a comment.
This revision now requires changes to proceed.

Please specify the semantics of the new LLVM attribute in LangRef -- though I 
don't really understand why you need an LLVM-side attribute at all.


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

https://reviews.llvm.org/D125378

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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

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

Hello @Jake-Egan,

I believe the problem was already fixed by the @aaron.ballman's patch here 
.

Thank you for fixing it, @aaron.ballman!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


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

2022-05-11 Thread Whisperity via Phabricator via cfe-commits
whisperity created this revision.
whisperity added reviewers: aaron.ballman, klimek, hokein, njames93.
whisperity added projects: clang, clang-tools-extra.
Herald added subscribers: carlosgalvezp, gamesh411, Szelethus, dkrupp, 
rnkovacs, xazax.hun.
Herald added a project: All.
whisperity requested review of this revision.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125383

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

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

[clang] 75bb815 - [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

2022-05-11 Thread Matt Devereau via cfe-commits

Author: Matt Devereau
Date: 2022-05-11T13:33:56Z
New Revision: 75bb815231f6967bd5f4e24143141b9fe69d01f8

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

LOG: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

Enable function attribute aarch64_sve_pcs at the C level, which correspondes to
aarch64_sve_vector_pcs at the LLVM IR level.

This requirement was created by this addition to the ARM C Language Extension:
https://github.com/ARM-software/acle/pull/194

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

Added: 
clang/test/CodeGen/aarch64-svepcs.c
clang/test/Sema/aarch64-svepcs.c

Modified: 
clang/include/clang-c/Index.h
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/Specifiers.h
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/Type.cpp
clang/lib/AST/TypePrinter.cpp
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaType.cpp
clang/test/Sema/callingconv.c
clang/tools/libclang/CXType.cpp

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index f28601c37d8ef..c4da7df6595d1 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -3445,6 +3445,7 @@ enum CXCallingConv {
   CXCallingConv_PreserveAll = 15,
   CXCallingConv_AArch64VectorCall = 16,
   CXCallingConv_SwiftAsync = 17,
+  CXCallingConv_AArch64SVEPCS = 18,
 
   CXCallingConv_Invalid = 100,
   CXCallingConv_Unexposed = 200

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 39359f414ae78..3c41edb474e89 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2313,6 +2313,11 @@ def AArch64VectorPcs: DeclOrTypeAttr {
   let Documentation = [AArch64VectorPcsDocs];
 }
 
+def AArch64SVEPcs: DeclOrTypeAttr {
+  let Spellings = [Clang<"aarch64_sve_pcs">];
+  let Documentation = [AArch64SVEPcsDocs];
+}
+
 def Pure : InheritableAttr {
   let Spellings = [GCC<"pure">];
   let Documentation = [Undocumented];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c7ef52f67afa3..b389ff9c02c45 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -2551,6 +2551,32 @@ the Arm Developer website.
   }];
 }
 
+def AArch64SVEPcsDocs : Documentation {
+  let Category = DocCatCallingConvs;
+  let Content = [{
+On AArch64 targets, this attribute changes the calling convention of a
+function to preserve additional Scalable Vector registers and Scalable
+Predicate registers relative to the default calling convention used for
+AArch64.
+
+This means it is more efficient to call such functions from code that performs
+extensive scalable vector and scalable predicate calculations, because fewer
+live SVE registers need to be saved. This property makes it well-suited for SVE
+math library functions, which are typically leaf functions that require a small
+number of registers.
+
+However, using this attribute also means that it is more expensive to call
+a function that adheres to the default calling convention from within such
+a function. Therefore, it is recommended that this attribute is only used
+for leaf functions.
+
+For more information, see the documentation for `aarch64_sve_pcs` in the
+ARM C Language Extension (ACLE) documentation.
+
+.. _`aarch64_sve_pcs`: 
https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute
+  }];
+}
+
 def RegparmDocs : Documentation {
   let Category = DocCatCallingConvs;
   let Content = [{

diff  --git a/clang/include/clang/Basic/Specifiers.h 
b/clang/include/clang/Basic/Specifiers.h
index 52ca7cce9d961..7a727e7088deb 100644
--- a/clang/include/clang/Basic/Specifiers.h
+++ b/clang/include/clang/Basic/Specifiers.h
@@ -280,6 +280,7 @@ namespace clang {
 CC_PreserveMost, // __attribute__((preserve_most))
 CC_PreserveAll,  // __attribute__((preserve_all))
 CC_AArch64VectorCall, // __attribute__((aarch64_vector_pcs))
+CC_AArch64SVEPCS, // __attribute__((aarch64_sve_pcs))
   };
 
   /// Checks whether the given calling convention supports variadic

diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 8d90575385fc4..1be70487c1b4e 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -3149,6 +3149,7 @@ StringRef 
CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
   case CC_AAPCS:
   case CC_AAPCS_VFP:
   case CC_AArch64VectorCall:
+  case CC_AArch64SVEPCS:
   case CC_IntelOclBicc:
   case CC_SpirFunction:
   case CC_OpenCLKernel:

diff

[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

2022-05-11 Thread Matt Devereau via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG75bb815231f6: [AArch64][SVE] Add aarch64_sve_pcs attribute 
to Clang (authored by MattDevereau).

Changed prior to commit:
  https://reviews.llvm.org/D124998?vs=427335&id=428644#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/Specifiers.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/aarch64-svepcs.c
  clang/test/Sema/aarch64-svepcs.c
  clang/test/Sema/callingconv.c
  clang/tools/libclang/CXType.cpp

Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -666,6 +666,7 @@
   TCALLINGCONV(X86RegCall);
   TCALLINGCONV(X86VectorCall);
   TCALLINGCONV(AArch64VectorCall);
+  TCALLINGCONV(AArch64SVEPCS);
   TCALLINGCONV(Win64);
   TCALLINGCONV(X86_64SysV);
   TCALLINGCONV(AAPCS);
Index: clang/test/Sema/callingconv.c
===
--- clang/test/Sema/callingconv.c
+++ clang/test/Sema/callingconv.c
@@ -52,6 +52,7 @@
 int __attribute__((pcs("foo"))) pcs7(void); // expected-error {{invalid PCS type}}
 
 int __attribute__((aarch64_vector_pcs)) aavpcs(void); // expected-warning {{'aarch64_vector_pcs' calling convention is not supported for this target}}
+int __attribute__((aarch64_sve_pcs)) aasvepcs(void);  // expected-warning {{'aarch64_sve_pcs' calling convention is not supported for this target}}
 
 // PR6361
 void ctest3();
Index: clang/test/Sema/aarch64-svepcs.c
===
--- /dev/null
+++ clang/test/Sema/aarch64-svepcs.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -verify %s
+
+typedef __attribute__((aarch64_sve_pcs)) int invalid_typedef; // expected-warning {{'aarch64_sve_pcs' only applies to function types; type here is 'int'}}
+
+void __attribute__((aarch64_sve_pcs(0))) foo0(void); // expected-error {{'aarch64_sve_pcs' attribute takes no arguments}}
+
+void __attribute__((aarch64_sve_pcs, preserve_all)) foo1(void); // expected-error {{not compatible}}
+
+void __attribute__((cdecl)) foo2(void); // expected-note {{previous declaration is here}}
+void __attribute__((aarch64_sve_pcs)) foo2(void) {} // expected-error {{function declared 'aarch64_sve_pcs' here was previously declared 'cdecl'}}
+
+void foo3(void);// expected-note {{previous declaration is here}}
+void __attribute__((aarch64_sve_pcs)) foo3(void) {} // expected-error {{function declared 'aarch64_sve_pcs' here was previously declared without calling convention}}
+
+typedef int (*fn_ty)(void);
+typedef int __attribute__((aarch64_sve_pcs)) (*aasvepcs_fn_ty)(void);
+void foo4(fn_ty ptr1, aasvepcs_fn_ty ptr2) {
+  ptr1 = ptr2; // expected-warning {{incompatible function pointer types}}
+}
Index: clang/test/CodeGen/aarch64-svepcs.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-svepcs.c
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - %s | FileCheck %s -check-prefix=CHECKC
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -x c++ -o - %s | FileCheck %s -check-prefix=CHECKCXX
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -verify %s
+
+void __attribute__((aarch64_sve_pcs)) f(int *); // expected-warning {{'aarch64_sve_pcs' calling convention is not supported for this target}}
+
+// CHECKC: define{{.*}} void @g(
+// CHECKCXX: define{{.*}} void @_Z1gPi(
+void g(int *a) {
+
+  // CHECKC: call aarch64_sve_vector_pcs void @f(
+  // CHECKCXX: call aarch64_sve_vector_pcs void @_Z1fPi
+  f(a);
+}
+
+// CHECKC: declare aarch64_sve_vector_pcs void @f(
+// CHECKCXX: declare aarch64_sve_vector_pcs void @_Z1fPi
+
+void __attribute__((aarch64_sve_pcs)) h(int *a) { // expected-warning {{'aarch64_sve_pcs' calling convention is not supported for this target}}
+  // CHECKC: define{{.*}} aarch64_sve_vector_pcs void @h(
+  // CHECKCXX: define{{.*}} aarch64_sve_vector_pcs void @_Z1hPi(
+  f(a);
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -121,6 +121,7 @@
   case ParsedAttr::AT_SwiftAsyncCall:  \
   case ParsedAttr::A

[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread Christudasan Devadasan via Phabricator via cfe-commits
cdevadas added inline comments.



Comment at: clang/test/CodeGenHIP/shuffle-attr-verify.hip:34
+// CHECK-DAG: attributes #[[attr1]] = { {{[^}]*}}shuffle{{[^}]*}} }
\ No newline at end of file


Add a new line.



Comment at: clang/test/CodeGenHIP/shuffle-noundef-attr.hip:49
+}
\ No newline at end of file


Ditto


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

https://reviews.llvm.org/D125378

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


[clang] 26eb042 - [Clang] Introduce clang-offload-packager tool to bundle device files

2022-05-11 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-05-11T09:39:13-04:00
New Revision: 26eb04268f4c9c0e2d4ff5bc53ae90cbb7f6c731

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

LOG: [Clang] Introduce clang-offload-packager tool to bundle device files

In order to do offloading compilation we need to embed files into the
host and create fatbainaries. Clang uses a special binary format to
bundle several files along with their metadata into a single binary
image. This is currently performed using the `-fembed-offload-binary`
option. However this is not very extensibile since it requires changing
the command flag every time we want to add something and makes optional
arguments difficult. This patch introduces a new tool called
`clang-offload-packager` that behaves similarly to CUDA's `fatbinary`.
This tool takes several input files with metadata and embeds it into a
single image that can then be embedded in the host.

Reviewed By: tra

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

Added: 
clang/docs/ClangOffloadPackager.rst
clang/tools/clang-offload-packager/CMakeLists.txt
clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Modified: 
clang/include/clang/Basic/CodeGenOptions.h
clang/include/clang/Driver/Action.h
clang/include/clang/Driver/ToolChain.h
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/Action.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Clang.h
clang/test/Driver/amdgpu-openmp-toolchain-new.c
clang/test/Driver/cuda-openmp-driver.cu
clang/test/Driver/cuda-phases.cu
clang/test/Driver/linker-wrapper-image.c
clang/test/Driver/linker-wrapper.c
clang/test/Driver/openmp-offload-gpu-new.c
clang/test/Driver/openmp-offload-infer.c
clang/test/Frontend/embed-object.c
clang/test/Frontend/embed-object.ll
clang/test/lit.cfg.py
clang/tools/CMakeLists.txt

Removed: 




diff  --git a/clang/docs/ClangOffloadPackager.rst 
b/clang/docs/ClangOffloadPackager.rst
new file mode 100644
index 0..5d15cc4c5caf6
--- /dev/null
+++ b/clang/docs/ClangOffloadPackager.rst
@@ -0,0 +1,72 @@
+==
+Clang Offload Packager
+==
+
+.. contents::
+   :local:
+
+.. _clang-offload-packager:
+
+Introduction
+
+
+This tool bundles device files into a single image containing necessary
+metadata. We use a custom binary format for bundling all the device images
+together. The image format is a small header wrapping around a string map. This
+tool creates bundled binaries so that they can be embedded into the host to
+create a fat-binary.
+
+An embedded binary is marked by the ``0x10FF10AD`` magic bytes, followed by a
+version. Each created binary contains its own magic bytes. This allows us to
+locate all the embedded offloading sections even after they may have been 
merged
+by the linker, such as when using relocatable linking. The format used is
+primarily a binary serialization of the following struct.
+
+.. code-block:: c++
+
+  struct OffloadingImage {
+uint16_t TheImageKind;
+uint16_t TheOffloadKind;
+uint32_t Flags;
+StringMap StringData;
+MemoryBufferRef Image;
+  };
+
+Usage
+=
+
+This tool can be used with the following arguments. Generally information is
+passed as a key-value pair to the ``image=`` argument. The ``file``, 
``triple``,
+and ``arch`` arguments are considered mandatory to make a valid image.
+
+.. code-block:: console
+
+  OVERVIEW: A utility for bundling several object files into a single binary.
+  The output binary can then be embedded into the host section table
+  to create a fatbinary containing offloading code.
+  
+  USAGE: clang-offload-packager [options]
+  
+  OPTIONS:
+  
+  Generic Options:
+  
+--help  - Display available options (--help-hidden for 
more)
+--help-list - Display list of available options 
(--help-list-hidden for more)
+--version   - Display the version of this program
+  
+  clang-offload-packager options:
+  
+--image=<=,...> - List of key and value arguments. Required
+  keywords are 'file' and 'triple'.
+-o=   - Write output to .
+
+Example
+===
+
+This tool simply takes many input files from the ``image`` option and creates a
+single output file with all the images combined.
+
+.. code-block:: console
+
+  clang-offload-packager -o out.bin 
--image=file=input.o,triple=nvptx64,arch=sm_70

diff  --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index 48a41244afa32..23d76c308d847 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/

[PATCH] D125165: [Clang] Introduce clang-offload-packager tool to bundle device files

2022-05-11 Thread Joseph Huber 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 rG26eb04268f4c: [Clang] Introduce clang-offload-packager tool 
to bundle device files (authored by jhuber6).
Herald added a subscriber: kosarev.

Changed prior to commit:
  https://reviews.llvm.org/D125165?vs=428443&id=428645#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125165

Files:
  clang/docs/ClangOffloadPackager.rst
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Action.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/test/Driver/amdgpu-openmp-toolchain-new.c
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/cuda-phases.cu
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/test/Driver/openmp-offload-gpu-new.c
  clang/test/Driver/openmp-offload-infer.c
  clang/test/Frontend/embed-object.c
  clang/test/Frontend/embed-object.ll
  clang/test/lit.cfg.py
  clang/tools/CMakeLists.txt
  clang/tools/clang-offload-packager/CMakeLists.txt
  clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Index: clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
===
--- /dev/null
+++ clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
@@ -0,0 +1,114 @@
+//===-- clang-offload-packager/ClangOffloadPackager.cpp - file bundler ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-===//
+//
+// This tool takes several device object files and bundles them into a single
+// binary image using a custom binary format. This is intended to be used to
+// embed many device files into an application to create a fat binary.
+//
+//===-===//
+
+#include "clang/Basic/Version.h"
+
+#include "llvm/Object/Binary.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
+
+using namespace llvm;
+using namespace llvm::object;
+
+static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
+
+static cl::OptionCategory
+ClangOffloadPackagerCategory("clang-offload-packager options");
+
+static cl::opt OutputFile("o", cl::Required,
+   cl::desc("Write output to ."),
+   cl::value_desc("file"),
+   cl::cat(ClangOffloadPackagerCategory));
+
+static cl::list
+DeviceImages("image", cl::ZeroOrMore,
+ cl::desc("List of key and value arguments. Required keywords "
+  "are 'file' and 'triple'."),
+ cl::value_desc("=,..."),
+ cl::cat(ClangOffloadPackagerCategory));
+
+static void PrintVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-offload-packager") << '\n';
+}
+
+int main(int argc, const char **argv) {
+  sys::PrintStackTraceOnErrorSignal(argv[0]);
+  cl::HideUnrelatedOptions(ClangOffloadPackagerCategory);
+  cl::SetVersionPrinter(PrintVersion);
+  cl::ParseCommandLineOptions(
+  argc, argv,
+  "A utility for bundling several object files into a single binary.\n"
+  "The output binary can then be embedded into the host section table\n"
+  "to create a fatbinary containing offloading code.\n");
+
+  if (Help) {
+cl::PrintHelpMessage();
+return EXIT_SUCCESS;
+  }
+
+  auto reportError = [argv](Error E) {
+logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
+return EXIT_FAILURE;
+  };
+
+  SmallVector BinaryData;
+  raw_svector_ostream OS(BinaryData);
+  for (StringRef Image : DeviceImages) {
+StringMap Args;
+for (StringRef Arg : llvm::split(Image, ","))
+  Args.insert(Arg.split("="));
+
+if (!Args.count("triple") || !Args.count("file"))
+  return reportError(createStringError(
+  inconvertibleErrorCode(),
+  "'file' and 'triple' are required image arguments"));
+
+OffloadBinary::OffloadingImage ImageBinary{};
+std::unique_ptr DeviceImage;
+for (const auto &KeyAndValue : Args) {
+  StringRef Key = KeyAndValue.getKey();
+  if (Key == "file") {
+llvm::ErrorOr> ObjectOrErr =
+  

[PATCH] D124446: [clang-tidy] Add the misc-discarded-return-value check

2022-05-11 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:96-99
+AST_MATCHER_P(StaticAssertDecl, hasAssertExpr,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getAssertExpr(), Finder, Builder);
+}

This is superfluous. The error message of a `static_assert` is always a string 
literal that has to be //right there// (i.e. a `constexpr const char *` 
function is NOT accepted). So if you are matching and ignoring the 
`ImplicitCastExpr`s, the following //SHOULD// match the static assert just fine:

```lang=cpp
staticAssertDecl(has(callExpr()))
```

http://godbolt.org/z/oeWfh3Mjo



Comment at: 
clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:106-126
+// FIXME: Move ASTMatcher library.
+// Note: Taken from UnusedUsingDeclsCheck.
+AST_POLYMORPHIC_MATCHER_P(
+forEachTemplateArgument,
+AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
+TemplateSpecializationType, FunctionDecl),
+clang::ast_matchers::internal::Matcher, InnerMatcher) {

martong wrote:
> Could you please have this in an independent parent patch?
D125383



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/misc-discarded-return-value-50p.cpp:631-635
+  // FIXME: Because call is a template, calls to it, even with 
different
+  // lambdas are calculated together, but the resulting diagnostic message is
+  // wrong. The culprit seems to be the USR generated for
+  // 'call<(lambda in lambdaCallerTest)>' being
+  // 
"c:misc-discarded-return-value-50p.cpp@F@call<#&$@F@lambdaCallerTest#@Sa>#S0_#"

(⏰ Stale comment leaked back in time from the later cross-TU implementation. 
This patch does not involve USRs yet.)



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/misc-discarded-return-value-50p.cpp:645-646
+
+  // Here, call<...> has a different key:
+  // 
"c:misc-discarded-return-value-50p.cpp@F@call<#&$@F@lambdaCallerTest2#@Sa>#S0_#"
+}

[⏰ Ditto]


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124446

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


[PATCH] D125386: [clang][ppc] Creating Seperate Install Target for PPC htm Headers

2022-05-11 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 created this revision.
qiongsiwu1 added reviewers: jsji, rzurob.
qiongsiwu1 added projects: clang, PowerPC.
Herald added subscribers: shchenz, mgorny.
Herald added a project: All.
qiongsiwu1 requested review of this revision.
Herald added a subscriber: cfe-commits.

This patch splits out the htm intrinsic headers from the PPC headers list.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125386

Files:
  clang/lib/Headers/CMakeLists.txt


Index: clang/lib/Headers/CMakeLists.txt
===
--- clang/lib/Headers/CMakeLists.txt
+++ clang/lib/Headers/CMakeLists.txt
@@ -73,6 +73,9 @@
 
 set(ppc_files
   altivec.h
+  )
+
+set(ppc_htm_files
   htmintrin.h
   htmxlintrin.h
   )
@@ -212,6 +215,7 @@
   ${mips_msa_files}
   ${opencl_files}
   ${ppc_files}
+  ${ppc_htm_files}
   ${systemz_files}
   ${ve_files}
   ${x86_files}
@@ -370,6 +374,7 @@
  "hip-resource-headers"
  "mips-resource-headers"
  "ppc-resource-headers"
+ "ppc-htm-resource-headers"
  "riscv-resource-headers"
  "systemz-resource-headers"
  "ve-resource-headers"
@@ -392,6 +397,7 @@
 add_header_target("hip-resource-headers" "${hip_files}")
 add_header_target("mips-resource-headers" "${mips_msa_files}")
 add_header_target("ppc-resource-headers" "${ppc_files};${ppc_wrapper_files}")
+add_header_target("ppc-htm-resource-headers" "${ppc_htm_files}")
 add_header_target("riscv-resource-headers" "${riscv_generated_files}")
 add_header_target("systemz-resource-headers" "${systemz_files}")
 add_header_target("ve-resource-headers" "${ve_files}")
@@ -491,11 +497,17 @@
   COMPONENT ppc-resource-headers)
 
 install(
-  FILES ${ppc_files} ${utility_files}
+  FILES ${ppc_files}
   DESTINATION ${header_install_dir}
   EXCLUDE_FROM_ALL
   COMPONENT ppc-resource-headers)
 
+install(
+  FILES ${ppc_htm_files}
+  DESTINATION ${header_install_dir}
+  EXCLUDE_FROM_ALL
+  COMPONENT ppc-htm-resource-headers)
+
 install(
   FILES ${riscv_generated_files}
   DESTINATION ${header_install_dir}
@@ -583,6 +595,9 @@
   add_llvm_install_targets(install-ppc-resource-headers
DEPENDS ppc-resource-headers
COMPONENT ppc-resource-headers)
+  add_llvm_install_targets(install-ppc-htm-resource-headers
+   DEPENDS ppc-htm-resource-headers
+   COMPONENT ppc-htm-resource-headers)
   add_llvm_install_targets(install-riscv-resource-headers
DEPENDS riscv-resource-headers
COMPONENT riscv-resource-headers)


Index: clang/lib/Headers/CMakeLists.txt
===
--- clang/lib/Headers/CMakeLists.txt
+++ clang/lib/Headers/CMakeLists.txt
@@ -73,6 +73,9 @@
 
 set(ppc_files
   altivec.h
+  )
+
+set(ppc_htm_files
   htmintrin.h
   htmxlintrin.h
   )
@@ -212,6 +215,7 @@
   ${mips_msa_files}
   ${opencl_files}
   ${ppc_files}
+  ${ppc_htm_files}
   ${systemz_files}
   ${ve_files}
   ${x86_files}
@@ -370,6 +374,7 @@
  "hip-resource-headers"
  "mips-resource-headers"
  "ppc-resource-headers"
+ "ppc-htm-resource-headers"
  "riscv-resource-headers"
  "systemz-resource-headers"
  "ve-resource-headers"
@@ -392,6 +397,7 @@
 add_header_target("hip-resource-headers" "${hip_files}")
 add_header_target("mips-resource-headers" "${mips_msa_files}")
 add_header_target("ppc-resource-headers" "${ppc_files};${ppc_wrapper_files}")
+add_header_target("ppc-htm-resource-headers" "${ppc_htm_files}")
 add_header_target("riscv-resource-headers" "${riscv_generated_files}")
 add_header_target("systemz-resource-headers" "${systemz_files}")
 add_header_target("ve-resource-headers" "${ve_files}")
@@ -491,11 +497,17 @@
   COMPONENT ppc-resource-headers)
 
 install(
-  FILES ${ppc_files} ${utility_files}
+  FILES ${ppc_files}
   DESTINATION ${header_install_dir}
   EXCLUDE_FROM_ALL
   COMPONENT ppc-resource-headers)
 
+install(
+  FILES ${ppc_htm_files}
+  DESTINATION ${header_install_dir}
+  EXCLUDE_FROM_ALL
+  COMPONENT ppc-htm-resource-headers)
+
 install(
   FILES ${riscv_generated_files}
   DESTINATION ${header_install_dir}
@@ -583,6 +595,9 @@
   add_llvm_install_targets(install-ppc-resource-headers
DEPENDS ppc-resource-headers
COMPONENT ppc-resource-headers)
+  add_llvm_install_targets(install-ppc-htm-resource-headers
+   DEPENDS ppc-htm-resource-headers
+   COMPONENT ppc-htm-resource-headers)
   add_llvm_install_targets(install-riscv-resource-headers
DEPENDS riscv-resource-headers
COMPONENT riscv-resource-headers)
___
cfe

[PATCH] D125011: [MSVC] Add support for pragma alloc_text

2022-05-11 Thread Stephen Long via Phabricator via cfe-commits
steplong added inline comments.



Comment at: clang/test/Sema/pragma-ms-alloc-text.cpp:5
+#pragma alloc_text(a// expected-warning {{expected ',' in '#pragma 
alloc_text'}}
+#pragma alloc_text(a, a // expected-warning {{missing ')' after '#pragma 
alloc_text'}} expected-error {{use of undeclared a}}
+#pragma alloc_text(L"a", a) // expected-warning {{expected a string literal 
for the section name}}

aaron.ballman wrote:
> This shows we have the parsing logic wrong -- we shouldn't get the use of 
> undeclared identifier a because we shouldn't have gotten into Sema for this 
> one.
MSVC accepts it and only warns about the missing paren if the identifier is 
declared like on Line 14. That's why I decided to handle it that way. We can 
decide to reject it though


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125011

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-11 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added inline comments.



Comment at: clang/test/Preprocessor/suggest-typoed-directive.c:10
+// expected-warning@+11 {{'#elfidef' directive not found, did you mean 
'#elifdef'?}}
+// expected-warning@+11 {{'#elfindef' directive not found, did you mean 
'#elifdef'?}}
+// expected-warning@+11 {{'#elsi' directive not found, did you mean '#else'?}}

aaron.ballman wrote:
> ken-matsui wrote:
> > aaron.ballman wrote:
> > > erichkeane wrote:
> > > > aaron.ballman wrote:
> > > > > ken-matsui wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > ken-matsui wrote:
> > > > > > > > aaron.ballman wrote:
> > > > > > > > > ken-matsui wrote:
> > > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > > It's interesting that this one suggested `#elifdef` 
> > > > > > > > > > > instead of `#elifndef` -- is there anything that can be 
> > > > > > > > > > > done for that?
> > > > > > > > > > > 
> > > > > > > > > > > Also, one somewhat interesting question is whether we 
> > > > > > > > > > > want to recommend `#elifdef` and `#elifndef` outside of 
> > > > > > > > > > > C2x/C++2b mode. Those directives only exist in the latest 
> > > > > > > > > > > language standard, but Clang supports them as a 
> > > > > > > > > > > conforming extension in all language modes. Given that 
> > > > > > > > > > > this diagnostic is about typos, I think I'm okay 
> > > > > > > > > > > suggesting the directives even in older language modes. 
> > > > > > > > > > > That's as likely to be a correct suggestion as not, IMO.
> > > > > > > > > > > It's interesting that this one suggested `#elifdef` 
> > > > > > > > > > > instead of `#elifndef` -- is there anything that can be 
> > > > > > > > > > > done for that?
> > > > > > > > > > 
> > > > > > > > > > I found I have to use `std::min_element` instead of 
> > > > > > > > > > `std::max_element` because we are finding the nearest (most 
> > > > > > > > > > minimum distance) string. Meanwhile, `#elfindef` has 2 
> > > > > > > > > > distance with both `#elifdef` and `#elifndef`. After 
> > > > > > > > > > replacing `std::max_element` with `std::min_element`, I 
> > > > > > > > > > could suggest `#elifndef` from `#elfinndef`.
> > > > > > > > > > 
> > > > > > > > > > > Also, one somewhat interesting question is whether we 
> > > > > > > > > > > want to recommend `#elifdef` and `#elifndef` outside of 
> > > > > > > > > > > C2x/C++2b mode. Those directives only exist in the latest 
> > > > > > > > > > > language standard, but Clang supports them as a 
> > > > > > > > > > > conforming extension in all language modes. Given that 
> > > > > > > > > > > this diagnostic is about typos, I think I'm okay 
> > > > > > > > > > > suggesting the directives even in older language modes. 
> > > > > > > > > > > That's as likely to be a correct suggestion as not, IMO.
> > > > > > > > > > 
> > > > > > > > > > I agree with you because Clang implements those directives, 
> > > > > > > > > > and the suggested code will also be compilable. I 
> > > > > > > > > > personally think only not compilable suggestions should be 
> > > > > > > > > > avoided. (Or, we might place additional info for outside of 
> > > > > > > > > > C2x/C++2b mode like `this is a C2x/C++2b feature but 
> > > > > > > > > > compilable on Clang`?)
> > > > > > > > > > 
> > > > > > > > > > ---
> > > > > > > > > > 
> > > > > > > > > > According to the algorithm of `std::min_element`, we only 
> > > > > > > > > > get an iterator of the first element even if there is 
> > > > > > > > > > another element that has the same distance. So, `#elfindef` 
> > > > > > > > > > only suggests `#elifdef` in accordance with the order of 
> > > > > > > > > > `Candidates`, and I don't think it is beautiful to depend 
> > > > > > > > > > on the order of candidates. I would say that we can suggest 
> > > > > > > > > > all the same distance like the following, but I'm not sure 
> > > > > > > > > > this is preferable:
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > #elfindef // diag: unknown directive, did you mean #elifdef 
> > > > > > > > > > or #elifndef?
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > I agree with you because Clang implements those directives, 
> > > > > > > > > > and the suggested code will also be compilable. I 
> > > > > > > > > > personally think only not compilable suggestions should be 
> > > > > > > > > > avoided. (Or, we might place additional info for outside of 
> > > > > > > > > > C2x/C++2b mode like this is a C2x/C++2b feature but 
> > > > > > > > > > compilable on Clang?)
> > > > > > > > > 
> > > > > > > > > I may be changing my mind on this a bit. I now see we don't 
> > > > > > > > > issue an extension warning when using `#elifdef` or 
> > > > > > > > > `#elifndef` in older language modes. That means suggesting 
> > > > > > > > > those will be correct but only for Clang, and the user won't 
> > > > > > > > > have any other diagnostics to tell them about the portability 
> > > 

[PATCH] D125386: [clang][ppc] Creating Seperate Install Target for PPC htm Headers

2022-05-11 Thread Jinsong Ji via Phabricator via cfe-commits
jsji accepted this revision.
jsji added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125386

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


[PATCH] D125340: [clang][NFC][AST] rename the ImportError to ASTImportError

2022-05-11 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added a comment.

In D125340#3505723 , @martong wrote:

> What are the benefits of this renaming? I mean is there a name clash? Do we 
> have another kind of "import" in Clang or in some of the dependent projects, 
> don't we?

AS it suggested by @balazske in the previous patch , and I also think if we 
moved the ImportError into it's own header then it's better to be named as 
ASTImportError .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125340

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


[PATCH] D124256: [OpenCL] Add cl_khr_subgroup_rotate builtins

2022-05-11 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 428652.
svenvh added a comment.

Added macro and macro test.  Added reference to Extension spec section.


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

https://reviews.llvm.org/D124256

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/Headers/opencl-c-header.cl


Index: clang/test/Headers/opencl-c-header.cl
===
--- clang/test/Headers/opencl-c-header.cl
+++ clang/test/Headers/opencl-c-header.cl
@@ -127,6 +127,9 @@
 #if cl_khr_subgroup_clustered_reduce != 1
 #error "Incorrectly defined cl_khr_subgroup_clustered_reduce"
 #endif
+#if cl_khr_subgroup_rotate != 1
+#error "Incorrectly defined cl_khr_subgroup_rotate"
+#endif
 #if cl_khr_extended_bit_ops != 1
 #error "Incorrectly defined cl_khr_extended_bit_ops"
 #endif
@@ -208,6 +211,9 @@
 #ifdef cl_khr_subgroup_clustered_reduce
 #error "Incorrect cl_khr_subgroup_clustered_reduce define"
 #endif
+#ifdef cl_khr_subgroup_rotate
+#error "Incorrect cl_khr_subgroup_rotate define"
+#endif
 #ifdef cl_khr_extended_bit_ops
 #error "Incorrect cl_khr_extended_bit_ops define"
 #endif
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -1832,6 +1832,12 @@
   def : Builtin<"dot_acc_sat_4x8packed_su_int", [Int, UInt, UInt, Int], 
Attr.Const>;
 }
 
+// Section 48.3 - cl_khr_subgroup_rotate
+let Extension = FunctionExtension<"cl_khr_subgroup_rotate"> in {
+  def : Builtin<"sub_group_rotate", [AGenType1, AGenType1, Int], 
Attr.Convergent>;
+  def : Builtin<"sub_group_clustered_rotate", [AGenType1, AGenType1, Int, 
UInt], Attr.Convergent>;
+}
+
 //
 // Arm extensions.
 let Extension = ArmIntegerDotProductInt8 in {
Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -17275,6 +17275,40 @@
 int __ovld __cnfn dot_acc_sat_4x8packed_su_int(uint, uint, int);
 #endif // __opencl_c_integer_dot_product_input_4x8bit_packed
 
+#if defined(cl_khr_subgroup_rotate)
+char __ovld __conv sub_group_rotate(char, int);
+uchar __ovld __conv sub_group_rotate(uchar, int);
+short __ovld __conv sub_group_rotate(short, int);
+ushort __ovld __conv sub_group_rotate(ushort, int);
+int __ovld __conv sub_group_rotate(int, int);
+uint __ovld __conv sub_group_rotate(uint, int);
+long __ovld __conv sub_group_rotate(long, int);
+ulong __ovld __conv sub_group_rotate(ulong, int);
+float __ovld __conv sub_group_rotate(float, int);
+#if defined(cl_khr_fp64)
+double __ovld __conv sub_group_rotate(double, int);
+#endif // cl_khr_fp64
+#if defined(cl_khr_fp16)
+half __ovld __conv sub_group_rotate(half, int);
+#endif // cl_khr_fp16
+
+char __ovld __conv sub_group_clustered_rotate(char, int, uint);
+uchar __ovld __conv sub_group_clustered_rotate(uchar, int, uint);
+short __ovld __conv sub_group_clustered_rotate(short, int, uint);
+ushort __ovld __conv sub_group_clustered_rotate(ushort, int, uint);
+int __ovld __conv sub_group_clustered_rotate(int, int, uint);
+uint __ovld __conv sub_group_clustered_rotate(uint, int, uint);
+long __ovld __conv sub_group_clustered_rotate(long, int, uint);
+ulong __ovld __conv sub_group_clustered_rotate(ulong, int, uint);
+float __ovld __conv sub_group_clustered_rotate(float, int, uint);
+#if defined(cl_khr_fp64)
+double __ovld __conv sub_group_clustered_rotate(double, int, uint);
+#endif // cl_khr_fp64
+#if defined(cl_khr_fp16)
+half __ovld __conv sub_group_clustered_rotate(half, int, uint);
+#endif // cl_khr_fp16
+#endif // cl_khr_subgroup_rotate
+
 #if defined(cl_intel_subgroups)
 // Intel-Specific Sub Group Functions
 float   __ovld __conv intel_sub_group_shuffle( float , uint );
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -21,6 +21,7 @@
 #define cl_khr_subgroup_shuffle 1
 #define cl_khr_subgroup_shuffle_relative 1
 #define cl_khr_subgroup_clustered_reduce 1
+#define cl_khr_subgroup_rotate 1
 #define cl_khr_extended_bit_ops 1
 #define cl_khr_integer_dot_product 1
 #define __opencl_c_integer_dot_product_input_4x8bit 1


Index: clang/test/Headers/opencl-c-header.cl
===
--- clang/test/Headers/opencl-c-header.cl
+++ clang/test/Headers/opencl-c-header.cl
@@ -127,6 +127,9 @@
 #if cl_khr_subgroup_clustered_reduce != 1
 #error "Incorrectly defined cl_khr_subgroup_clustered_reduce"
 #endif
+#if cl_khr_subgroup_rotate != 1
+#error "Incorrectly defined cl_khr_subgroup_rotate"
+#endif
 #if cl_khr_extended_bit_ops != 1
 #error "Incorrectly defined cl_khr_extended_bit_ops"
 #endif
@@ -208,6 +21

[PATCH] D124256: [OpenCL] Add cl_khr_subgroup_rotate builtins

2022-05-11 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added a comment.

In D124256#3474043 , @Anastasia wrote:

> LGTM! I imagine tablegen side is being tested automatically?

The TableGen definitions are tested by `clang/test/Headers/opencl-builtins.cl`

> Btw do we need to set the feature macro for SPIR/SPIR-V target and then test 
> it too?

Good point!  Added.


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

https://reviews.llvm.org/D124256

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


[PATCH] D125165: [Clang] Introduce clang-offload-packager tool to bundle device files

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

We now have clang-offload-bundler, clang-offload-packager, 
clang-offload-wrapper. Do we really need that many distinct binaries for 
offloading? Any chance we could combine some of those?




Comment at: clang/test/Driver/linker-wrapper.c:5
 
-// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
-// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70 \
-// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70
+// RUN: clang-offload-packager -o %t.out \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70
 \

Since you're calling this from a test, you have to edit 
clang/test/CMakeLists.txt and add a dep on the new tool.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125165

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


[PATCH] D125165: [Clang] Introduce clang-offload-packager tool to bundle device files

2022-05-11 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/test/Driver/linker-wrapper.c:5
 
-// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
-// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70 \
-// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70
+// RUN: clang-offload-packager -o %t.out \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70
 \

thakis wrote:
> Since you're calling this from a test, you have to edit 
> clang/test/CMakeLists.txt and add a dep on the new tool.
Sorry, I missed the `add_dependencies(clang clang-offload-packager)` line in 
the new cmakelists.txt file. All good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125165

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


[PATCH] D125165: [Clang] Introduce clang-offload-packager tool to bundle device files

2022-05-11 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D125165#3506172 , @thakis wrote:

> We now have clang-offload-bundler, clang-offload-packager, 
> clang-offload-wrapper. Do we really need that many distinct binaries for 
> offloading? Any chance we could combine some of those?

Yeah, it's not ideal. I would've liked to use `clang-offload-bundler` for this 
tool but we're keeping the old ones around for backwards compatibility. The 
`clang-offload-bundler` and `clang-offload-wrapper` have already been merged 
into `clang` and the `clang-linker-wrapper` respectively, they're kept around 
for backwards compatibility currently. I think HIP still uses the 
`clang-offload-bundler` but I'm in the process of changing that. I'm not sure 
if it's possible to delete these tools once they're introduced since someone 
might rely on the binary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125165

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


[PATCH] D125340: [clang][NFC][AST] rename the ImportError to ASTImportError

2022-05-11 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Initially the `ImportError` was very related to `ASTImporter` but now the class 
is used at other less related places and files. `ImportError` is a too generic 
name for this unless it can be used at any other "import" in clang which is not 
the case (the class can be extended with other special data about the import 
error). Maybe the whole ASTImporter should go into a new namespace, specially 
if `ASTImporter.cpp` would be split into parts?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125340

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


[libunwind] c631e33 - [runtimes] Print the testing configuration in use in libunwind and libc++abi

2022-05-11 Thread Louis Dionne via cfe-commits

Author: Louis Dionne
Date: 2022-05-11T10:18:09-04:00
New Revision: c631e33f316d891b39c1e01217a7422fdc29ced1

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

LOG: [runtimes] Print the testing configuration in use in libunwind and 
libc++abi

We do it for libc++, and it's rather useful for debugging e.g. CI.

Added: 


Modified: 
libcxxabi/CMakeLists.txt
libunwind/CMakeLists.txt

Removed: 




diff  --git a/libcxxabi/CMakeLists.txt b/libcxxabi/CMakeLists.txt
index 8d583df2ef78a..e7e29dd69937d 100644
--- a/libcxxabi/CMakeLists.txt
+++ b/libcxxabi/CMakeLists.txt
@@ -198,6 +198,7 @@ set(LIBCXXABI_TEST_CONFIG 
"${CMAKE_CURRENT_SOURCE_DIR}/test/lit.site.cfg.in" CAC
 if (NOT IS_ABSOLUTE "${LIBCXXABI_TEST_CONFIG}")
   set(LIBCXXABI_TEST_CONFIG 
"${CMAKE_CURRENT_SOURCE_DIR}/test/configs/${LIBCXXABI_TEST_CONFIG}")
 endif()
+message(STATUS "Using libc++abi testing configuration: 
${LIBCXXABI_TEST_CONFIG}")
 set(LIBCXXABI_TEST_PARAMS "" CACHE STRING
 "A list of parameters to run the Lit test suite with.")
 

diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index 632316bc5065c..eabb55256b27a 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -118,6 +118,7 @@ set(LIBUNWIND_TEST_CONFIG 
"${LIBUNWIND_DEFAULT_TEST_CONFIG}" CACHE STRING
 if (NOT IS_ABSOLUTE "${LIBUNWIND_TEST_CONFIG}")
   set(LIBUNWIND_TEST_CONFIG 
"${CMAKE_CURRENT_SOURCE_DIR}/test/configs/${LIBUNWIND_TEST_CONFIG}")
 endif()
+message(STATUS "Using libunwind testing configuration: 
${LIBUNWIND_TEST_CONFIG}")
 set(LIBUNWIND_TEST_PARAMS "" CACHE STRING
 "A list of parameters to run the Lit test suite with.")
 



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


[PATCH] D125195: [asan][ARMCXXABI] Added missing asan poison array cookie hooks.

2022-05-11 Thread Roy Sundahl via Phabricator via cfe-commits
rsundahl marked an inline comment as not done.
rsundahl added inline comments.



Comment at: compiler-rt/test/asan/TestCases/Posix/new_array_cookie_test.cpp:19
   C *buffer = new C[argc];
-  buffer[-2].x = 10;
+  buffer[-1].x = 10;
 // CHECK: AddressSanitizer: heap-buffer-overflow

rsundahl wrote:
> yln wrote:
> > Can we try to simulate a 1-byte buffer-underflow (and leave the definition 
> > of `struct C` as-is)?  This would show that ASan still reports the smallest 
> > possible infraction.
> That's a good idea, but it's not about leaving the struct the same because 
> it's definitely wrong in that type "int" has nothing to do with the cookie 
> and it only happens to be true that  (buffer[-2].x) gets to the beginning of 
> the cookie since two "int"s happen to fit inside of a "size_t". (This may not 
> always be true as in most 64-on-32 type arrangements) It's better to treat 
> the cookie as [-1] of an array of size_t elements so that when indexing [-1] 
> you get all of the cookie at once (see: 
> https://itanium-cxx-abi.github.io/cxx-abi/abi.html#array-cookies). The reason 
> I write to the *whole* cookie at once is because of endian-ness. The existing 
> code which only writes to the first half of the cookie would reach a 
> different half of the cookie on a big-endian machine so this covers both. But 
> you have a good point, we should see if the minimum underflow is caught so 
> I'll think of a way to do that in an endian-agnostic way... 
I believe that because the existing code: 
```
buffer[-1].x = 10
```
uses a negative address from an array of int, I took that as something 
unchangeable and if it were, my arguments for making the size of the elements 
size_t have some context, //But...//now I see that unjustified and merely 
clever in some way and your approach explicitly separating the type of the 
elements of the allocation from the overflow is better in at least two ways. 
First, it removes any such "cleverness" from the test (which is really more 
distracting than it is useful) and second, it allows us to test the smallest 
possible ingress into the cookie area. Sorry that was a hard sell but 
appreciate the insight. 
```
buffer[-1].x = 10
```



Comment at: 
compiler-rt/test/asan/TestCases/Posix/new_array_cookie_uaf_test.cpp:20
 __attribute__((no_sanitize_address)) void Write42ToCookie(C *c) {
-  long *p = reinterpret_cast(c);
+  size_t *p = reinterpret_cast(c);
   p[-1] = 42;

rsundahl wrote:
> yln wrote:
> > Can we try to simulate a 1-byte buffer-underflow (and leave the definition 
> > of struct C as-is)? This would show that ASan still reports the smallest 
> > possible infraction.
> (Same answer as above)
In this situation the UAF isn't caught until the corrupted cookie has called 
delete on all 42 (supposed) elements of the array. The test depends on seeing 
all 42 members' being deleted so the write must go the low-byte. If you place 
the 42 (or anything non-zero) in the high byte, the cookie becomes > 2^54 with 
a corresponding number of calls to delete each member. If all the deletes are 
not allowed to execute, the actual UAF detection does not get executed. 
Therefore I'm going to leave this one as it is and leave the 
"minimum-underflow" to new_array_cookie_test. (The test explicitly disables 
sanitizing the underflow to the cookie but what is not clear to me is why 
access to the cookie by the second "delete" after the free doesn't trap the 
read of the poisoned cookie //before// deleting the (supposed) members. We 
might want to instrument ASan to check for a poisoned cookie earlier.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125195

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


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

2022-05-11 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 428657.
steplong added a comment.

- Renamed `AddRangeBasedNoBuiltin` to `AddImplicitMSFunctionNoBuiltinAttr`
- Renamed `err_pragma_intrinsic_function_scope` to 
`err_pragma_expected_file_scope`
- Added comment about MSVC accepting struct test
- Removed `->getRedeclContext()`. Seems to be ok (i.e. tests are still passing)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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

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

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

2022-05-11 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 428658.
ldionne marked 2 inline comments as done.
ldionne added a comment.

Rebase and address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120727

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

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

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

2022-05-11 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added inline comments.



Comment at: libcxxabi/CMakeLists.txt:201
 endif()
+message(STATUS "Using libc++abi testing configuration: 
${LIBCXXABI_TEST_CONFIG}")
 set(LIBCXXABI_TEST_PARAMS "" CACHE STRING

mstorsjo wrote:
> Unrelated to the rest of the patch?
Indeed, let me do that separately as a NFC.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120727

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


[PATCH] D125340: [clang][NFC][AST] rename the ImportError to ASTImportError

2022-05-11 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

I found one other place in **LibASTImporter.rst** where `ImportError` is used. 
LLDB should be checked too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125340

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


[PATCH] D124996: [clang][preprocessor] Fix unsigned-ness of utf8 char literals

2022-05-11 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/test/Lexer/utf8-char-literal.cpp:54-56
+#  if !(u8'\xff' == 0xff)
+#error u8 char literal is not unsigned
+#  endif

tbaeder wrote:
> tahonermann wrote:
> > The C++ case looks good now, but the condition doesn't look right for the C 
> > case. The expectation is that `u8'\xff'` should not match `'\xff'` in C23 
> > mode, but the test treats this as an error. If the test is passing, that 
> > indicates something is not being validated correctly. Shouldn't unexpected 
> > error diagnostics cause the test to fail?
> I used `u8'\xff' != 0xff` here because that's the condition you mentioned in 
> the phab review adding the `u8` prefix. Using `u8'\xff' != '\xff'` indeed 
> fails with:
> 
> ```
> clang/test/Lexer/utf8-char-literal.cpp Line 55: u8 char literal is not 
> unsigned
> clang/test/Lexer/utf8-char-literal.cpp Line 54: right side of operator 
> converted from negative value to unsigned: -1 to 18446744073709551615
> ```
Oh! I missed the use of `0xff` vs `'\xff'`. Sorry if I mislead you. In order to 
avoid such subtle differences in the test, can we use the same check as for C++?
  // UTF-8 character literals are enabled in C23 and later and are always 
unsigned.
  #if __STDC_VERSION__ >= 202000L
  #  if u8'\xff' == '\xff' // expected-warning {{right side of operator 
converted from negative value to unsigned}}
  #error UTF-8 character value matched ordinary character literal; this is 
unexpected
  #  endif
  #endif


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

https://reviews.llvm.org/D124996

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert requested changes to this revision.
jdoerfert added a comment.

In D125378#3506001 , @nikic wrote:

> Please specify the semantics of the new LLVM attribute in LangRef -- though I 
> don't really understand why you need an LLVM-side attribute at all.

+1. I doubt this patch is helpful.

> Shuffle attribute has been added as per suggestions/comments from review: 
> D124158 

I failed to see where this was suggested.

---

My suggestion was and still is summarized in: 
https://reviews.llvm.org/D124158#3486110


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

https://reviews.llvm.org/D125378

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


[PATCH] D124946: [clang] serialize ORIGINAL_PCH_DIR relative to BaseDirectory

2022-05-11 Thread Richard Howell via Phabricator via cfe-commits
rmaz added a comment.

In D124946#3500454 , @urnathan wrote:

> Looks good to me, but perhaps leave it a few days for others to comment (my 
> familiarity with this code is low).  I do know people want relocatable 
> outputs though.

Are we good to go with this one too now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124946

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


[PATCH] D124866: [CUDA][HIP] support __noinline__ as keyword

2022-05-11 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/Basic/IdentifierTable.cpp:111
 KEYSYCL   = 0x100,
+KEYCUDA   = 0x200,
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,

delcypher wrote:
> yaxunl wrote:
> > delcypher wrote:
> > > @yaxunl Is it intentional that you didn't update `KEYALL` here? That 
> > > means `KEYALL` doesn't include the bit for `KEYCUDA`.
> > > 
> > > If that was your intention then this will break if someone adds a new 
> > > key. E.g.
> > > 
> > > ```
> > > KEYCUDA = 0x200,
> > > KEYSOMENEWTHING = 0x400,
> > > // ...
> > > // KEYALL now includes `KEYCUDA`, whereas it didn't before.
> > > // KEYALL includes KEYSOMENEWTHING 
> > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > >   ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to 
> > > exclude.
> > > ...
> > > ```
> > > 
> > > 
> > > 1. Updating the `0x1ff` constant to `0x3ff` so that `KEYALL` 
> > > includes `KEYCUDA`
> > > 2. If your intention **is** to not have `KEYCUDA`  set in `KEYALL` then 
> > > amend `KEYALL` to be.
> > > 
> > > ```
> > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL are 
> > > used to exclude.
> > > // KEYCUDA is not included in KEYALL
> > > ```
> > My intention is not to include KEYCUDA in KEYALL.
> > 
> > Should I change KEYALL to
> > 
> > 
> > ```
> > KEYALL = (0x3ff & ~KEYNOMS18 &
> >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL are 
> > used to exclude.
> > // KEYCUDA is not included in KEYALL
> > ```
> > 
> > instead of 
> > 
> > 
> > ```
> > KEYALL = (0x7ff & ~KEYNOMS18 &
> >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL are 
> > used to exclude.
> > // KEYCUDA is not included in KEYALL
> > ```
> > 
> > since the current maximum mask is 0x3ff instead of 0x7ff
> Oops, you're right it would be `0x3ff`. I wonder though if we should 
> clean this up so we don't need to manually update the bit mask every time... 
> what if it was written like this?
> 
> ```lang=c++
>  enum {
> KEYC99= 0x1,
> KEYCXX= 0x2,
> KEYCXX11  = 0x4,
> 
> KEYSYCL   = 0x100,
> KEYCUDA   = 0x200,
> KEYMAX = KEYCUDA, // Must be set to the largest KEY enum value
> KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
> 
> // KEYNOMS18 and KEYNOOPENCL are used to exclude.
> // KEYCUDA is not included in KEYALL because 
> KEYALL = (((KEYMAX & (KEYMAX-1)) & ~KEYNOMS18 & ~KEYNOOPENCL & ~KEYCUDA)
> };
> ```
On second thought, KEYALL does not need to exclude KEYCUDA.

However, it would be good to set KEYALL in a generic approach. I will open a 
separate review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124866

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


[PATCH] D125379: [analyzer][solver] Do not negate unsigned ranges

2022-05-11 Thread Gabor Marton via Phabricator via cfe-commits
martong abandoned this revision.
martong added inline comments.



Comment at: clang/test/Analysis/constraint_manager_negate_difference.c:125-130
 void negate_unsigned_mid(unsigned m, unsigned n) {
   if (m - n == UINT_MID) {
-clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}}
-clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != UINT_MID); // expected-warning{{FALSE}} 
expected-warning{{TRUE}}
   }
 }

Actually, this test case was correct, because UINT_MID is a special value and 
for that
```
_Static_assert(UINT_MID == -UINT_MID, "");
```
holds.
So, this patch is meaningless.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125379

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 added a comment.

In D125378#3506215 , @jdoerfert wrote:

> In D125378#3506001 , @nikic wrote:
>
>> Please specify the semantics of the new LLVM attribute in LangRef -- though 
>> I don't really understand why you need an LLVM-side attribute at all.
>
> +1. I doubt this patch is helpful.
>
>> Shuffle attribute has been added as per suggestions/comments from review: 
>> D124158 
>
> I failed to see where this was suggested.
>
> ---
>
> My suggestion was and still is summarized in: 
> https://reviews.llvm.org/D124158#3486110

@jdoerfert I meant to convey that, As a solution to review comments from 
D124158 , introduced this shuffle attribute 
to identify __shfl_sync like APIs.


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

https://reviews.llvm.org/D125378

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


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

2022-05-11 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 428674.
khchen added a comment.

address Craig's comments, thanks!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125323

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

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


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

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

Thanks for all the hard work on this, LGTM! Can you please add a release note 
to clang/docs/ReleaseNotes.rst for the new functionality (probably best under 
the `New Pragmas in Clang` heading) when you land it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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


[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:1323-1344
+def ShuffleDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The ``shuffle`` attribute can be placed on a function declaration. It indicates
+that the call instructions of a function with this attribute can take undef
+arguments and is still valid.
+

This sounds highly specific to those language standards and like an expert-only 
feature that's going to be a footgun for everyone else. Is there a way these 
special functions can be identified at codegen time (or within the backend) so 
that we don't have to expose an attribute for this?


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

https://reviews.llvm.org/D125378

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


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

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125395

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/constraint_manager_negate.c
  clang/test/Analysis/constraint_manager_negate_difference.c

Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -1,4 +1,6 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-binary-operation-simplification=true -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -87,6 +89,7 @@
   clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{FALSE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void negate_int_min(int m, int n) {
   if (m - n != INT_MIN)
 return;
@@ -106,11 +109,11 @@
   clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void effective_range_2(int m, int n) {
   assert(m - n <= 0);
   assert(n - m <= 0);
-  clang_analyzer_eval(m - n == 0); // expected-warning{{TRUE}} expected-warning{{FALSE}}
-  clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+  clang_analyzer_eval(m - n == 0 || m - n == INT_MIN); // expected-warning{{TRUE}}
 }
 
 void negate_unsigned_min(unsigned m, unsigned n) {
@@ -122,6 +125,15 @@
   }
 }
 
+_Static_assert(7u - 3u != 3u - 7u, "");
+void negate_unsigned_4(unsigned m, unsigned n) {
+  if (m - n == 4u) {
+clang_analyzer_eval(n - m == 4u); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != 4u); // expected-warning{{TRUE}}
+  }
+}
+
+_Static_assert(UINT_MID == -UINT_MID, "");
 void negate_unsigned_mid(unsigned m, unsigned n) {
   if (m - n == UINT_MID) {
 clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}}
@@ -136,6 +148,8 @@
   }
 }
 
+_Static_assert(1u - 2u == UINT_MAX, "");
+_Static_assert(2u - 1u == 1, "");
 void negate_unsigned_max(unsigned m, unsigned n) {
   if (m - n == UINT_MAX) {
 clang_analyzer_eval(n - m == 1); // expected-warning{{TRUE}}
@@ -152,8 +166,8 @@
 
 // The next code is a repro for the bug PR41588
 void negated_unsigned_range(unsigned x, unsigned y) {
-  clang_analyzer_eval(x - y != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
-  clang_analyzer_eval(y - x != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
+  clang_analyzer_eval(x - y != 0); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(y - x != 0); // expected-warning{{UNKNOWN}}
   // expected no assertion on the next line
-  clang_analyzer_eval(x - y != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
+  clang_analyzer_eval(x - y != 0); // expected-warning{{UNKNOWN}}
 }
Index: clang/test/Analysis/constraint_manager_negate.c
===
--- /dev/null
+++ clang/test/Analysis/constraint_manager_negate.c
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+void exit(int);
+
+#define UINT_MIN (0U)
+#define UINT_MAX (~UINT_MIN)
+#define UINT_MID (UINT_MAX / 2 + 1)
+#define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
+#define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
+
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
+void negate_positive_range(int a) {
+  if (-a <= 0)
+return;
+  // -a: [1, INT_MAX]
+  // a: [INT_MIN, -1]
+  clang_analyzer_eval(a < 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a >= INT_MIN); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a == INT_MIN); // expected-warning{{FALSE}}
+}
+
+void negate_positive_range2(int a) {
+  if (a <= 0)
+return;
+  // a: [1, INT_MAX]
+  // -a: [INT_MIN, -1]
+  clang_analyzer_eval(-a < 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(-a >= INT_MIN); // expected-warning{{TRUE}}
+  clang_analyzer_eval(-a == INT_MIN); // expected-warning{{FALSE}}
+}
+
+_Static_assert(INT_MIN == -INT_MIN, "");

[PATCH] D125378: [Attribute] Introduce shuffle attribute to be used for __shfl_sync like cross-lane APIs

2022-05-11 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D125378#3506383 , @skc7 wrote:

> In D125378#3506215 , @jdoerfert 
> wrote:
>
>> In D125378#3506001 , @nikic wrote:
>>
>>> Please specify the semantics of the new LLVM attribute in LangRef -- though 
>>> I don't really understand why you need an LLVM-side attribute at all.
>>
>> +1. I doubt this patch is helpful.
>>
>>> Shuffle attribute has been added as per suggestions/comments from review: 
>>> D124158 
>>
>> I failed to see where this was suggested.
>>
>> ---
>>
>> My suggestion was and still is summarized in: 
>> https://reviews.llvm.org/D124158#3486110
>
> @jdoerfert I meant to convey that, As a solution to review comments from 
> D124158 , introduced this shuffle attribute 
> to identify __shfl_sync like APIs.

I'm confused. What is the Attribute in IR going to achieve? The problem is 
during clang codegen. I can see how the C++/Clang attribute part is useful but 
I would not call it "shuffle". 
What I would suggest, if you want to use C/C++ attributes (which makes sense to 
me), is an attribute that avoids undef or introduces frozen:

  __attribute__((maybe_undef(0))) int __shfl_sync(int var, int src_lane, int 
width = warpSize);
  __attribute__((maybe_undef(var))) int __shfl_sync(int var, int src_lane, int 
width = warpSize);

*OR*

  int __shfl_sync(int __attribute__((maybe_undef)) var, int src_lane, int width 
= warpSize);

And the attribute will cause clang either not to place `noundef` or place 
`freeze` for the respective argument(s).


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

https://reviews.llvm.org/D125378

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


[PATCH] D125165: [Clang] Introduce clang-offload-packager tool to bundle device files

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

We could add a "clang-offload-bundler and clang-offload-wrapper are deprecated, 
replace them with $whatever" in the release notes and then remove them a 
release later, assuming the replacement is straightforward.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125165

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


[PATCH] D125396: [clang] Fix KEYALL

2022-05-11 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: delcypher, aaron.ballman, tra, rsmith.
Herald added a project: All.
yaxunl requested review of this revision.

Introduce KEYMAX and a generic way to update KEYALL.


https://reviews.llvm.org/D125396

Files:
  clang/lib/Basic/IdentifierTable.cpp


Index: clang/lib/Basic/IdentifierTable.cpp
===
--- clang/lib/Basic/IdentifierTable.cpp
+++ clang/lib/Basic/IdentifierTable.cpp
@@ -109,9 +109,10 @@
 KEYMSCOMPAT   = 0x80,
 KEYSYCL   = 0x100,
 KEYCUDA   = 0x200,
+KEYMAX= KEYCUDA, // The maximum key
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
-KEYALL = (0x1ff & ~KEYNOMS18 &
-  ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
+KEYALL = (KEYMAX | (KEYMAX-1)) & ~KEYNOMS18 &
+ ~KEYNOOPENCL // KEYNOMS18 and KEYNOOPENCL are used to exclude.
   };
 
   /// How a keyword is treated in the selected standard.


Index: clang/lib/Basic/IdentifierTable.cpp
===
--- clang/lib/Basic/IdentifierTable.cpp
+++ clang/lib/Basic/IdentifierTable.cpp
@@ -109,9 +109,10 @@
 KEYMSCOMPAT   = 0x80,
 KEYSYCL   = 0x100,
 KEYCUDA   = 0x200,
+KEYMAX= KEYCUDA, // The maximum key
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
-KEYALL = (0x1ff & ~KEYNOMS18 &
-  ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
+KEYALL = (KEYMAX | (KEYMAX-1)) & ~KEYNOMS18 &
+ ~KEYNOOPENCL // KEYNOMS18 and KEYNOOPENCL are used to exclude.
   };
 
   /// How a keyword is treated in the selected standard.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124866: [CUDA][HIP] support __noinline__ as keyword

2022-05-11 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/lib/Basic/IdentifierTable.cpp:111
 KEYSYCL   = 0x100,
+KEYCUDA   = 0x200,
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,

yaxunl wrote:
> delcypher wrote:
> > yaxunl wrote:
> > > delcypher wrote:
> > > > @yaxunl Is it intentional that you didn't update `KEYALL` here? That 
> > > > means `KEYALL` doesn't include the bit for `KEYCUDA`.
> > > > 
> > > > If that was your intention then this will break if someone adds a new 
> > > > key. E.g.
> > > > 
> > > > ```
> > > > KEYCUDA = 0x200,
> > > > KEYSOMENEWTHING = 0x400,
> > > > // ...
> > > > // KEYALL now includes `KEYCUDA`, whereas it didn't before.
> > > > // KEYALL includes KEYSOMENEWTHING 
> > > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > > >   ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to 
> > > > exclude.
> > > > ...
> > > > ```
> > > > 
> > > > 
> > > > 1. Updating the `0x1ff` constant to `0x3ff` so that `KEYALL` 
> > > > includes `KEYCUDA`
> > > > 2. If your intention **is** to not have `KEYCUDA`  set in `KEYALL` then 
> > > > amend `KEYALL` to be.
> > > > 
> > > > ```
> > > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL 
> > > > are used to exclude.
> > > > // KEYCUDA is not included in KEYALL
> > > > ```
> > > My intention is not to include KEYCUDA in KEYALL.
> > > 
> > > Should I change KEYALL to
> > > 
> > > 
> > > ```
> > > KEYALL = (0x3ff & ~KEYNOMS18 &
> > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL are 
> > > used to exclude.
> > > // KEYCUDA is not included in KEYALL
> > > ```
> > > 
> > > instead of 
> > > 
> > > 
> > > ```
> > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL are 
> > > used to exclude.
> > > // KEYCUDA is not included in KEYALL
> > > ```
> > > 
> > > since the current maximum mask is 0x3ff instead of 0x7ff
> > Oops, you're right it would be `0x3ff`. I wonder though if we should 
> > clean this up so we don't need to manually update the bit mask every 
> > time... what if it was written like this?
> > 
> > ```lang=c++
> >  enum {
> > KEYC99= 0x1,
> > KEYCXX= 0x2,
> > KEYCXX11  = 0x4,
> > 
> > KEYSYCL   = 0x100,
> > KEYCUDA   = 0x200,
> > KEYMAX = KEYCUDA, // Must be set to the largest KEY enum value
> > KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
> > 
> > // KEYNOMS18 and KEYNOOPENCL are used to exclude.
> > // KEYCUDA is not included in KEYALL because 
> > KEYALL = (((KEYMAX & (KEYMAX-1)) & ~KEYNOMS18 & ~KEYNOOPENCL & ~KEYCUDA)
> > };
> > ```
> On second thought, KEYALL does not need to exclude KEYCUDA.
> 
> However, it would be good to set KEYALL in a generic approach. I will open a 
> separate review.
opened https://reviews.llvm.org/D125396 to fix KEYALL


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124866

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


[PATCH] D124866: [CUDA][HIP] support __noinline__ as keyword

2022-05-11 Thread Dan Liew via Phabricator via cfe-commits
delcypher added inline comments.



Comment at: clang/lib/Basic/IdentifierTable.cpp:111
 KEYSYCL   = 0x100,
+KEYCUDA   = 0x200,
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,

yaxunl wrote:
> yaxunl wrote:
> > delcypher wrote:
> > > yaxunl wrote:
> > > > delcypher wrote:
> > > > > @yaxunl Is it intentional that you didn't update `KEYALL` here? That 
> > > > > means `KEYALL` doesn't include the bit for `KEYCUDA`.
> > > > > 
> > > > > If that was your intention then this will break if someone adds a new 
> > > > > key. E.g.
> > > > > 
> > > > > ```
> > > > > KEYCUDA = 0x200,
> > > > > KEYSOMENEWTHING = 0x400,
> > > > > // ...
> > > > > // KEYALL now includes `KEYCUDA`, whereas it didn't before.
> > > > > // KEYALL includes KEYSOMENEWTHING 
> > > > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > > > >   ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to 
> > > > > exclude.
> > > > > ...
> > > > > ```
> > > > > 
> > > > > 
> > > > > 1. Updating the `0x1ff` constant to `0x3ff` so that `KEYALL` 
> > > > > includes `KEYCUDA`
> > > > > 2. If your intention **is** to not have `KEYCUDA`  set in `KEYALL` 
> > > > > then amend `KEYALL` to be.
> > > > > 
> > > > > ```
> > > > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > > > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL 
> > > > > are used to exclude.
> > > > > // KEYCUDA is not included in KEYALL
> > > > > ```
> > > > My intention is not to include KEYCUDA in KEYALL.
> > > > 
> > > > Should I change KEYALL to
> > > > 
> > > > 
> > > > ```
> > > > KEYALL = (0x3ff & ~KEYNOMS18 &
> > > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL 
> > > > are used to exclude.
> > > > // KEYCUDA is not included in KEYALL
> > > > ```
> > > > 
> > > > instead of 
> > > > 
> > > > 
> > > > ```
> > > > KEYALL = (0x7ff & ~KEYNOMS18 &
> > > >   ~KEYNOOPENCL & ~KEYCUDA ) // KEYNOMS18 and KEYNOOPENCL 
> > > > are used to exclude.
> > > > // KEYCUDA is not included in KEYALL
> > > > ```
> > > > 
> > > > since the current maximum mask is 0x3ff instead of 0x7ff
> > > Oops, you're right it would be `0x3ff`. I wonder though if we should 
> > > clean this up so we don't need to manually update the bit mask every 
> > > time... what if it was written like this?
> > > 
> > > ```lang=c++
> > >  enum {
> > > KEYC99= 0x1,
> > > KEYCXX= 0x2,
> > > KEYCXX11  = 0x4,
> > > 
> > > KEYSYCL   = 0x100,
> > > KEYCUDA   = 0x200,
> > > KEYMAX = KEYCUDA, // Must be set to the largest KEY enum value
> > > KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
> > > 
> > > // KEYNOMS18 and KEYNOOPENCL are used to exclude.
> > > // KEYCUDA is not included in KEYALL because 
> > > KEYALL = (((KEYMAX & (KEYMAX-1)) & ~KEYNOMS18 & ~KEYNOOPENCL & 
> > > ~KEYCUDA)
> > > };
> > > ```
> > On second thought, KEYALL does not need to exclude KEYCUDA.
> > 
> > However, it would be good to set KEYALL in a generic approach. I will open 
> > a separate review.
> opened https://reviews.llvm.org/D125396 to fix KEYALL
Oops that should say

```
KEYALL = (((KEYMAX | (KEYMAX-1)) & ~KEYNOMS18 & ~KEYNOOPENCL & ~KEYCUDA)
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124866

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


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

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

- Add false positive test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125395

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

Index: clang/test/Analysis/unary-sym-expr.c
===
--- clang/test/Analysis/unary-sym-expr.c
+++ clang/test/Analysis/unary-sym-expr.c
@@ -28,3 +28,12 @@
 return;
   clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
 }
+
+int test_fp(int flag) {
+  int value;
+  if (flag == 0)
+value = 1;
+  if (-flag == 0)
+return value; // no-warning
+  return 42;
+}
Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -1,4 +1,6 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-binary-operation-simplification=true -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -87,6 +89,7 @@
   clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{FALSE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void negate_int_min(int m, int n) {
   if (m - n != INT_MIN)
 return;
@@ -106,11 +109,11 @@
   clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void effective_range_2(int m, int n) {
   assert(m - n <= 0);
   assert(n - m <= 0);
-  clang_analyzer_eval(m - n == 0); // expected-warning{{TRUE}} expected-warning{{FALSE}}
-  clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+  clang_analyzer_eval(m - n == 0 || m - n == INT_MIN); // expected-warning{{TRUE}}
 }
 
 void negate_unsigned_min(unsigned m, unsigned n) {
@@ -122,6 +125,15 @@
   }
 }
 
+_Static_assert(7u - 3u != 3u - 7u, "");
+void negate_unsigned_4(unsigned m, unsigned n) {
+  if (m - n == 4u) {
+clang_analyzer_eval(n - m == 4u); // expected-warning{{FALSE}}
+clang_analyzer_eval(n - m != 4u); // expected-warning{{TRUE}}
+  }
+}
+
+_Static_assert(UINT_MID == -UINT_MID, "");
 void negate_unsigned_mid(unsigned m, unsigned n) {
   if (m - n == UINT_MID) {
 clang_analyzer_eval(n - m == UINT_MID); // expected-warning{{TRUE}}
@@ -136,6 +148,8 @@
   }
 }
 
+_Static_assert(1u - 2u == UINT_MAX, "");
+_Static_assert(2u - 1u == 1, "");
 void negate_unsigned_max(unsigned m, unsigned n) {
   if (m - n == UINT_MAX) {
 clang_analyzer_eval(n - m == 1); // expected-warning{{TRUE}}
@@ -152,8 +166,8 @@
 
 // The next code is a repro for the bug PR41588
 void negated_unsigned_range(unsigned x, unsigned y) {
-  clang_analyzer_eval(x - y != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
-  clang_analyzer_eval(y - x != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
+  clang_analyzer_eval(x - y != 0); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(y - x != 0); // expected-warning{{UNKNOWN}}
   // expected no assertion on the next line
-  clang_analyzer_eval(x - y != 0); // expected-warning{{FALSE}} expected-warning{{TRUE}}
+  clang_analyzer_eval(x - y != 0); // expected-warning{{UNKNOWN}}
 }
Index: clang/test/Analysis/constraint_manager_negate.c
===
--- /dev/null
+++ clang/test/Analysis/constraint_manager_negate.c
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+void exit(int);
+
+#define UINT_MIN (0U)
+#define UINT_MAX (~UINT_MIN)
+#define UINT_MID (UINT_MAX / 2 + 1)
+#define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
+#define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
+
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
+void negate_positive_range(int a) {
+  if (-a <= 0)
+return;
+  // -a: [1, INT_MAX]
+  // a: [INT_MIN, -1]
+  clang_analyzer_eval(a < 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a >= INT_MIN); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a == INT_MIN); // expected-warning{{FALSE}}
+}
+
+void negate_positive_range2(int a) {
+  if (a <= 0)
+return;
+  // a: [1, INT_MAX]
+  // -a: [INT_MIN, -1]
+  clang_analyz

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

2022-05-11 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125395

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


  1   2   3   >