[PATCH] D138377: add clang_Type_getFullyQualifiedName

2022-11-23 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands updated this revision to Diff 477398.
anderslanglands added a comment.

Remove whitespace changes on unaffected lines


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138377

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang-c/Index.h
  clang/test/Index/print-qualified-type.cpp
  clang/tools/c-index-test/c-index-test.c
  clang/tools/libclang/CXType.cpp
  clang/tools/libclang/libclang.map

Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -413,6 +413,7 @@
 clang_CXXMethod_isDeleted;
 clang_CXXMethod_isCopyAssignmentOperator;
 clang_CXXMethod_isMoveAssignmentOperator;
+clang_Type_getFullyQualifiedName;
 };
 
 # Example of how to add a new symbol version entry.  If you do add a new symbol
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/QualTypeNames.h"
 #include "clang/Basic/AddressSpaces.h"
 #include "clang/Frontend/ASTUnit.h"
 
@@ -309,6 +310,18 @@
   return cxstring::createDup(OS.str());
 }
 
+CXString clang_Type_getFullyQualifiedName(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return cxstring::createEmpty();
+
+  const ASTContext &Ctx = cxtu::getASTUnit(GetTU(CT))->getASTContext();
+  std::string QualName = clang::TypeName::getFullyQualifiedName(
+  T, Ctx, Ctx.getLangOpts());
+
+  return cxstring::createDup(QualName);
+}
+
 CXType clang_getTypedefDeclUnderlyingType(CXCursor C) {
   using namespace cxcursor;
   CXTranslationUnit TU = cxcursor::getCursorTU(C);
Index: clang/tools/c-index-test/c-index-test.c
===
--- clang/tools/c-index-test/c-index-test.c
+++ clang/tools/c-index-test/c-index-test.c
@@ -373,6 +373,19 @@
   return CommentSchemaFile;
 }
 
+static int parse_print_qualified_type_names(int argc, const char **argv) {
+  const char *PrintQualifiedTypeNamesArg = "-print-qualified-type-names";
+  int PrintQualifiedTypeNames = 0;
+
+  if (argc == 0)
+return PrintQualifiedTypeNames;
+
+  if (!strncmp(argv[0], PrintQualifiedTypeNamesArg, strlen(PrintQualifiedTypeNamesArg)))
+PrintQualifiedTypeNames = 1;
+
+  return PrintQualifiedTypeNames;
+}
+
 /**/
 /* Pretty-printing.   */
 /**/
@@ -1300,6 +1313,7 @@
   CXTranslationUnit TU;
   enum CXCursorKind *Filter;
   const char *CommentSchemaFile;
+  int PrintQualifiedTypeNames;
 } VisitorData;
 
 
@@ -1507,10 +1521,15 @@
 /* Typekind testing.  */
 /**/
 
-static void PrintTypeAndTypeKind(CXType T, const char *Format) {
+static void PrintTypeAndTypeKind(CXType T, const char *Format,
+ int PrintQualifiedName) {
   CXString TypeSpelling, TypeKindSpelling;
 
-  TypeSpelling = clang_getTypeSpelling(T);
+  if (PrintQualifiedName != 0) {
+TypeSpelling = clang_Type_getFullyQualifiedName(T);
+  } else {
+TypeSpelling = clang_getTypeSpelling(T);
+  }
   TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
   printf(Format,
  clang_getCString(TypeSpelling),
@@ -1525,7 +1544,8 @@
 return CXVisit_Continue;
 }
 
-static void PrintTypeTemplateArgs(CXType T, const char *Format) {
+static void PrintTypeTemplateArgs(CXType T, const char *Format,
+  int PrintQualifiedName) {
   int NumTArgs = clang_Type_getNumTemplateArguments(T);
   if (NumTArgs != -1 && NumTArgs != 0) {
 int i;
@@ -1534,7 +1554,8 @@
 for (i = 0; i < NumTArgs; ++i) {
   TArg = clang_Type_getTemplateArgumentAsType(T, i);
   if (TArg.kind != CXType_Invalid) {
-PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
+PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]",
+ PrintQualifiedName);
   }
 }
 /* Ensure that the returned type is invalid when indexing off-by-one. */
@@ -1577,7 +1598,9 @@
 CXType PT = clang_getPointeeType(T);
 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
 PrintCursor(cursor, NULL);
-PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
+VisitorData *Data = (VisitorData *)d;
+PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]",
+ Data->PrintQualifiedTypeNames);
 PrintNullabilityKind(T, " [nullability=%s]");
 if (cl

[PATCH] D138377: add clang_Type_getFullyQualifiedName

2022-11-23 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands updated this revision to Diff 477399.
anderslanglands added a comment.

couple of little spaces I missed...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138377

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang-c/Index.h
  clang/test/Index/print-qualified-type.cpp
  clang/tools/c-index-test/c-index-test.c
  clang/tools/libclang/CXType.cpp
  clang/tools/libclang/libclang.map

Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -413,6 +413,7 @@
 clang_CXXMethod_isDeleted;
 clang_CXXMethod_isCopyAssignmentOperator;
 clang_CXXMethod_isMoveAssignmentOperator;
+clang_Type_getFullyQualifiedName;
 };
 
 # Example of how to add a new symbol version entry.  If you do add a new symbol
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/QualTypeNames.h"
 #include "clang/Basic/AddressSpaces.h"
 #include "clang/Frontend/ASTUnit.h"
 
@@ -309,6 +310,18 @@
   return cxstring::createDup(OS.str());
 }
 
+CXString clang_Type_getFullyQualifiedName(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return cxstring::createEmpty();
+
+  const ASTContext &Ctx = cxtu::getASTUnit(GetTU(CT))->getASTContext();
+  std::string QualName = clang::TypeName::getFullyQualifiedName(
+  T, Ctx, Ctx.getLangOpts());
+
+  return cxstring::createDup(QualName);
+}
+
 CXType clang_getTypedefDeclUnderlyingType(CXCursor C) {
   using namespace cxcursor;
   CXTranslationUnit TU = cxcursor::getCursorTU(C);
Index: clang/tools/c-index-test/c-index-test.c
===
--- clang/tools/c-index-test/c-index-test.c
+++ clang/tools/c-index-test/c-index-test.c
@@ -373,6 +373,19 @@
   return CommentSchemaFile;
 }
 
+static int parse_print_qualified_type_names(int argc, const char **argv) {
+  const char *PrintQualifiedTypeNamesArg = "-print-qualified-type-names";
+  int PrintQualifiedTypeNames = 0;
+
+  if (argc == 0)
+return PrintQualifiedTypeNames;
+
+  if (!strncmp(argv[0], PrintQualifiedTypeNamesArg, strlen(PrintQualifiedTypeNamesArg)))
+PrintQualifiedTypeNames = 1;
+
+  return PrintQualifiedTypeNames;
+}
+
 /**/
 /* Pretty-printing.   */
 /**/
@@ -1300,6 +1313,7 @@
   CXTranslationUnit TU;
   enum CXCursorKind *Filter;
   const char *CommentSchemaFile;
+  int PrintQualifiedTypeNames;
 } VisitorData;
 
 
@@ -1507,10 +1521,15 @@
 /* Typekind testing.  */
 /**/
 
-static void PrintTypeAndTypeKind(CXType T, const char *Format) {
+static void PrintTypeAndTypeKind(CXType T, const char *Format,
+ int PrintQualifiedName) {
   CXString TypeSpelling, TypeKindSpelling;
 
-  TypeSpelling = clang_getTypeSpelling(T);
+  if (PrintQualifiedName != 0) {
+TypeSpelling = clang_Type_getFullyQualifiedName(T);
+  } else {
+TypeSpelling = clang_getTypeSpelling(T);
+  }
   TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
   printf(Format,
  clang_getCString(TypeSpelling),
@@ -1525,7 +1544,8 @@
 return CXVisit_Continue;
 }
 
-static void PrintTypeTemplateArgs(CXType T, const char *Format) {
+static void PrintTypeTemplateArgs(CXType T, const char *Format,
+  int PrintQualifiedName) {
   int NumTArgs = clang_Type_getNumTemplateArguments(T);
   if (NumTArgs != -1 && NumTArgs != 0) {
 int i;
@@ -1534,7 +1554,8 @@
 for (i = 0; i < NumTArgs; ++i) {
   TArg = clang_Type_getTemplateArgumentAsType(T, i);
   if (TArg.kind != CXType_Invalid) {
-PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
+PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]",
+ PrintQualifiedName);
   }
 }
 /* Ensure that the returned type is invalid when indexing off-by-one. */
@@ -1577,7 +1598,9 @@
 CXType PT = clang_getPointeeType(T);
 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
 PrintCursor(cursor, NULL);
-PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
+VisitorData *Data = (VisitorData *)d;
+PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]",
+ Data->PrintQualifiedTypeNames);
 PrintNullabilityKind(T, " [nullability=%s]");
 if (clang_isCons

[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Christopher Sauer via Phabricator via cfe-commits
cpsauer created this revision.
cpsauer added reviewers: nridge, sammccall, kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
cpsauer requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This preserves --target and -target flags in the system includes extractor, 
which is needed for cross-compiling to, e.g. Android, since the target flags 
can influence the default include paths.

Note that, like isysroot (which is handled incorrectly above and elsewhere), 
the target flag doesn't fit cleanly into the ArgsToPreserve abstraction and 
does indeed have a different number of - in its = and non = forms. (ref 
)
 There are plenty of bugs in this file, but this is an incremental improvement.

For more context, please see https://github.com/clangd/clangd/issues/1378

Thanks for all you do, wonderful LLVM folks :)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138546

Files:
  clang-tools-extra/clangd/SystemIncludeExtractor.cpp


Index: clang-tools-extra/clangd/SystemIncludeExtractor.cpp
===
--- clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -184,13 +184,18 @@
   const llvm::StringRef FlagsToPreserve[] = {
   "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"};
   // Preserves these flags and their values, either as separate args or with an
-  // equalsbetween them
+  // equals between them
   const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"};
 
   for (size_t I = 0, E = CommandLine.size(); I < E; ++I) {
 llvm::StringRef Arg = CommandLine[I];
 if (llvm::is_contained(FlagsToPreserve, Arg)) {
   Args.push_back(Arg);
+} else if (Arg.startswith("--target=")) {
+  Args.push_back(Arg);
+} else if (I + 1 < E && Arg.equals("-target")) {
+  Args.push_back(CommandLine[I]);
+  Args.push_back(CommandLine[++I]);
 } else {
   const auto *Found =
   llvm::find_if(ArgsToPreserve, [&Arg](llvm::StringRef S) {


Index: clang-tools-extra/clangd/SystemIncludeExtractor.cpp
===
--- clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -184,13 +184,18 @@
   const llvm::StringRef FlagsToPreserve[] = {
   "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"};
   // Preserves these flags and their values, either as separate args or with an
-  // equalsbetween them
+  // equals between them
   const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"};
 
   for (size_t I = 0, E = CommandLine.size(); I < E; ++I) {
 llvm::StringRef Arg = CommandLine[I];
 if (llvm::is_contained(FlagsToPreserve, Arg)) {
   Args.push_back(Arg);
+} else if (Arg.startswith("--target=")) {
+  Args.push_back(Arg);
+} else if (I + 1 < E && Arg.equals("-target")) {
+  Args.push_back(CommandLine[I]);
+  Args.push_back(CommandLine[++I]);
 } else {
   const auto *Found =
   llvm::find_if(ArgsToPreserve, [&Arg](llvm::StringRef S) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

In D134859#3945709 , @sepavloff wrote:

> In D134859#3943926 , @tbaeder wrote:
>
>> FYI, I noticed the way the floating values are serialized doesn't work if 
>> the `APFloat` heap-allocated anything; those values aren't preserved through 
>> (de)serialization of course.
>>
>> Reproducer:
>>
>>   constexpr double foo() {
>> return __LDBL_MIN__;
>>   }
>
> The return statement returns a value of type `long double` while the function 
> returns `double`. If `long double` is wider than `double`, truncation occurs, 
> may be this is the reason?

It also happens when the function returns a `long double`.

I tracked the problem down to the way we emit byte code into a `std::vector`. 
It's simply `reintepret_cast'`ed to `const char *`, so that won't work for 
`APFloat`.

This change seems to fix the problem:

  diff --git a/clang/lib/AST/Interp/ByteCodeEmitter.cpp 
b/clang/lib/AST/Interp/ByteCodeEmitter.cpp
  index ff2136d34872..61e9662013c3 100644
  --- a/clang/lib/AST/Interp/ByteCodeEmitter.cpp
  +++ b/clang/lib/AST/Interp/ByteCodeEmitter.cpp
  @@ -163,8 +163,15 @@ static void emit(Program &P, std::vector &Code, 
const T &Val,
 }
  
 if constexpr (!std::is_pointer_v) {
  -const char *Data = reinterpret_cast(&Val);
  -Code.insert(Code.end(), Data, Data + Size);
  + if constexpr (std::is_trivially_copyable_v) {
  +  const char *Data = reinterpret_cast(&Val);
  +  Code.insert(Code.end(), Data, Data + Size);
  + } else {
  +   // Construct the value directly into our storage vector.
  +   size_t ValPos = Code.size();
  +   Code.resize(Code.size() + Size);
  +   new (Code.data() + ValPos) T(Val);
  + }
 } else {
   uint32_t ID = P.getOrCreateNativePointer(Val);
   const char *Data = reinterpret_cast(&ID);




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

https://reviews.llvm.org/D134859

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


[PATCH] D138547: [X86][AMX] Fix typo of the headerfile.

2022-11-23 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke created this revision.
Herald added a project: All.
LuoYuanke 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/D138547

Files:
  clang/lib/Headers/amxfp16intrin.h


Index: clang/lib/Headers/amxfp16intrin.h
===
--- clang/lib/Headers/amxfp16intrin.h
+++ clang/lib/Headers/amxfp16intrin.h
@@ -20,7 +20,7 @@
 ///floating-point elements with elements in \a dst, and store the 32-bit
 ///result back to tile \a dst.
 ///
-/// \headerfile 
+/// \headerfile 
 ///
 /// \code
 /// void _tile_dpfp16ps (__tile dst, __tile a, __tile b)


Index: clang/lib/Headers/amxfp16intrin.h
===
--- clang/lib/Headers/amxfp16intrin.h
+++ clang/lib/Headers/amxfp16intrin.h
@@ -20,7 +20,7 @@
 ///floating-point elements with elements in \a dst, and store the 32-bit
 ///result back to tile \a dst.
 ///
-/// \headerfile 
+/// \headerfile 
 ///
 /// \code
 /// void _tile_dpfp16ps (__tile dst, __tile a, __tile b)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137770: [docs] Introduce clangd part in StandardCPlusPlusModules

2022-11-23 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D137770#3945095 , @spartacoos 
wrote:

> I realised this is an active issue that's not being worked on. So, I want to 
> put myself forward to help implement this new module system for clangd once 
> you have settled on a design/approach.

Well, an issue here is that a design isn't actively being worked on either :) 
So it's probably best to start there.

I think a good starting point would be Sam's list of "issues that need to be 
addressed" in this comment 
.

A concrete way to make progress here might be:

- Identify scenarios that we explicitly do not want to support. An example 
might be "consuming binary module artifacts produced by a non-clang compiler".
- Of the scenarios that we do want to support, identify a subset to focus on 
implementing support for in an initial implementation ("support now" vs. 
"support later"). For example, we could start by limiting support to cases 
where clangd builds all modules from source itself and does not try to consume 
binary module artifacts built by anything other than itself. (Alternatively, we 
could start by limiting support only to cases where we assume the build 
compiler is version-locked to clangd and _only_ consume binary module artifacts 
built by the build compiler.) Since you're looking to work on this, the choice 
of subset can of course be informed by what scenarios you care about.
- Go through the "list of issues", and propose answers that are suitable for 
the "support now" scenarios, while still leaving open a path to bring the 
"support later" scenarios onboard.

We can then discuss the proposed approach in the issue and iterate on it.

> Are there any other resources where I can learn more about clangd development?

The clangd website and particularly the design section 
 are probably helpful reading, especially to 
understand some of the concepts like "preamble" discussed in the above list.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137770

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


[PATCH] D137488: [clang][Interp] Array initialization via string literal

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1098-1099
+
+unsigned N = SL->getLength();
+for (size_t I = 0; I != NumElems; ++I) {
+  uint32_t CodePoint = I < N ? SL->getCodeUnit(I) : 0;

tbaeder wrote:
> tahonermann wrote:
> > tahonermann wrote:
> > > Aren't `N` and `NumElems` guaranteed to have the same value here? Both 
> > > are derived from `SL`. The code seems to be written with the expectation 
> > > that `NumElems` corresponds to the number of elements to be iniitialized 
> > > in the target array.
> > I see the change to now use the minimum of `SL->getLength()` and 
> > `CAT->getSize().getZExtValue()`. Based on https://godbolt.org/z/5sTWExTac 
> > this looks to be unnecessary. When a string literal is used as an array 
> > initializer, it appears that the type of the string literal is adjusted to 
> > match the size of the array being initialized. I suggest using only 
> > `CAT->getSize().getZExtValue()` and adding a comment that this code depends 
> > on that adjustment.
> That is good to know and  makes sense, thanks!
That actually doesn't work. They type might be adjusted, but `getCodeUnit()` 
still asserts that the index is `< getLength()`. :(


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

https://reviews.llvm.org/D137488

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


[PATCH] D138429: [clang][RISCV][NFC] Prevent data race in RVVType::computeType

2022-11-23 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 477406.
kito-cheng added a comment.

Changes:

- Add comment for RVVTypeCache
- computeRVVTypeHashValue become a local function rather than static function 
of RVVTypeCache.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138429

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

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -95,6 +95,7 @@
 class RVVEmitter {
 private:
   RecordKeeper &Records;
+  RVVTypeCache TypeCache;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -349,8 +350,8 @@
   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
   // Print RVV boolean types.
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Int8, Log2LMUL,
-  PrototypeDescriptor::Mask);
+auto T = TypeCache.computeType(BasicType::Int8, Log2LMUL,
+   PrototypeDescriptor::Mask);
 if (T)
   printType(T.value());
   }
@@ -358,10 +359,10 @@
   for (char I : StringRef("csil")) {
 BasicType BT = ParseBasicType(I);
 for (int Log2LMUL : Log2LMULs) {
-  auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
+  auto T = TypeCache.computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
   if (T) {
 printType(T.value());
-auto UT = RVVType::computeType(
+auto UT = TypeCache.computeType(
 BT, Log2LMUL,
 PrototypeDescriptor(BaseTypeModifier::Vector,
 VectorTypeModifier::NoModifier,
@@ -372,8 +373,8 @@
   }
   OS << "#if defined(__riscv_zvfh)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float16, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float16, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -381,8 +382,8 @@
 
   OS << "#if (__riscv_v_elen_fp >= 32)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float32, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float32, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -390,8 +391,8 @@
 
   OS << "#if (__riscv_v_elen_fp >= 64)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float64, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float64, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -553,14 +554,15 @@
   for (int Log2LMUL : Log2LMULList) {
 BasicType BT = ParseBasicType(I);
 Optional Types =
-RVVType::computeTypes(BT, Log2LMUL, NF, Prototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, Prototype);
 // Ignored to create new intrinsic if there are any illegal types.
 if (!Types)
   continue;
 
-auto SuffixStr = RVVIntrinsic::getSuffixStr(BT, Log2LMUL, SuffixDesc);
-auto OverloadedSuffixStr =
-RVVIntrinsic::getSuffixStr(BT, Log2LMUL, OverloadedSuffixDesc);
+auto SuffixStr =
+RVVIntrinsic::getSuffixStr(TypeCache, BT, Log2LMUL, SuffixDesc);
+auto OverloadedSuffixStr = RVVIntrinsic::getSuffixStr(
+TypeCache, BT, Log2LMUL, OverloadedSuffixDesc);
 // Create a unmasked intrinsic
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffixStr, IRName,
@@ -576,7 +578,7 @@
 /*HasMaskedOffOperand=*/false, HasVL, NF,
 IsPrototypeDefaultTU, UnMaskedPolicyScheme, P);
 Optional PolicyTypes =
-RVVType::computeTypes(BT, Log2LMUL, NF, PolicyPrototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, PolicyPrototype);
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffixStr, IRName,
 /*IsMask=*/false, /*HasMaskedOffOperand=*/false, HasVL,
@@ -588,7 +590,7 @@
   continue;
 // Create a masked intrinsic
 Optional MaskTypes =
-RVVType::computeTypes(BT, Log2LMUL, NF, Prototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, Prototype);
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffi

[PATCH] D138429: [clang][RISCV][NFC] Prevent data race in RVVType::computeType

2022-11-23 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng marked 3 inline comments as done.
kito-cheng added inline comments.



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:284
+
+class RVVTypeCache {
+private:

khchen wrote:
> nit: maybe we could add some comments to said the motivation for 
> `RVVTypeCache`. 
good suggestion, thanks :)



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:289
+
+  static uint64_t computeRVVTypeHashValue(BasicType BT, int Log2LMUL,
+  PrototypeDescriptor Proto);

kadircet wrote:
> khchen wrote:
> > `static` could be eliminated now.
> nit: i'd actually drop it from the header completely
I just move that to a local static function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138429

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


[clang] 3fe89be - [clang][RISCV][NFC] Prevent data race in RVVType::computeType

2022-11-23 Thread Kito Cheng via cfe-commits

Author: Kito Cheng
Date: 2022-11-23T16:59:19+08:00
New Revision: 3fe89be8015955f2e8403f8b7d7580db13cedb2c

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

LOG: [clang][RISCV][NFC] Prevent data race in RVVType::computeType

Introduce a RVVTypeCache to hold the cache instead of using a local
static variable to maintain a cache.

Also made construct of RVVType to private, make sure that could be only
created by a cache manager.

Reviewed By: sammccall

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

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h 
b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
index 4a8bbc78cdee3..8b9f994a4e31a 100644
--- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -15,7 +15,9 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include 
+#include 
 #include 
+#include 
 #include 
 
 namespace llvm {
@@ -182,9 +184,12 @@ struct LMULType {
 class RVVType;
 using RVVTypePtr = RVVType *;
 using RVVTypes = std::vector;
+class RVVTypeCache;
 
 // This class is compact representation of a valid and invalid RVVType.
 class RVVType {
+  friend class RVVTypeCache;
+
   BasicType BT;
   ScalarTypeKind ScalarType = Invalid;
   LMULType LMUL;
@@ -204,10 +209,9 @@ class RVVType {
 
   enum class FixedLMULType { LargerThan, SmallerThan };
 
-public:
-  RVVType() : BT(BasicType::Unknown), LMUL(0), Valid(false) {}
   RVVType(BasicType BT, int Log2LMUL, const PrototypeDescriptor &Profile);
 
+public:
   // Return the string representation of a type, which is an encoded string for
   // passing to the BUILTIN() macro in Builtins.def.
   const std::string &getBuiltinStr() const { return BuiltinStr; }
@@ -275,17 +279,25 @@ class RVVType {
   void initTypeStr();
   // Compute and record a short name of a type for C/C++ name suffix.
   void initShortStr();
+};
+
+// This class is used to manage RVVType, RVVType should only created by this
+// class, also provided thread-safe cache capability.
+class RVVTypeCache {
+private:
+  std::unordered_map LegalTypes;
+  std::set IllegalTypes;
 
 public:
   /// Compute output and input types by applying 
diff erent config (basic type
   /// and LMUL with type transformers). It also record result of type in legal
   /// or illegal set to avoid compute the same config again. The result maybe
   /// have illegal RVVType.
-  static llvm::Optional
+  llvm::Optional
   computeTypes(BasicType BT, int Log2LMUL, unsigned NF,
llvm::ArrayRef Prototype);
-  static llvm::Optional computeType(BasicType BT, int Log2LMUL,
-PrototypeDescriptor Proto);
+  llvm::Optional computeType(BasicType BT, int Log2LMUL,
+ PrototypeDescriptor Proto);
 };
 
 enum PolicyScheme : uint8_t {
@@ -373,7 +385,7 @@ class RVVIntrinsic {
   std::string getBuiltinTypeStr() const;
 
   static std::string
-  getSuffixStr(BasicType Type, int Log2LMUL,
+  getSuffixStr(RVVTypeCache &TypeCache, BasicType Type, int Log2LMUL,
llvm::ArrayRef PrototypeDescriptors);
 
   static llvm::SmallVector

diff  --git a/clang/lib/Sema/SemaRISCVVectorLookup.cpp 
b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
index 4ab393b89d1b9..85bf11e942b96 100644
--- a/clang/lib/Sema/SemaRISCVVectorLookup.cpp
+++ b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
@@ -132,6 +132,7 @@ class RISCVIntrinsicManagerImpl : public 
sema::RISCVIntrinsicManager {
 private:
   Sema &S;
   ASTContext &Context;
+  RVVTypeCache TypeCache;
 
   // List of all RVV intrinsic.
   std::vector IntrinsicList;
@@ -247,16 +248,16 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() {
   continue;
 
 Optional Types =
-RVVType::computeTypes(BaseType, Log2LMUL, Record.NF, ProtoSeq);
+TypeCache.computeTypes(BaseType, Log2LMUL, Record.NF, ProtoSeq);
 
 // Ignored to create new intrinsic if there are any illegal types.
 if (!Types.has_value())
   continue;
 
-std::string SuffixStr =
-RVVIntrinsic::getSuffixStr(BaseType, Log2LMUL, SuffixProto);
+std::string SuffixStr = RVVIntrinsic::getSuffixStr(
+TypeCache, BaseType, Log2LMUL, SuffixProto);
 std::string OverloadedSuffixStr = RVVIntrinsic::getSuffixStr(
-BaseType, Log2LMUL, OverloadedSuffixProto);
+TypeCache, BaseType, Log2LMUL, OverloadedSuffixProto);
 
 // Create non-masked intrinsic.
 InitRVVIntrinsic(Rec

[PATCH] D138429: [clang][RISCV][NFC] Prevent data race in RVVType::computeType

2022-11-23 Thread Kito Cheng via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
kito-cheng marked 2 inline comments as done.
Closed by commit rG3fe89be80159: [clang][RISCV][NFC] Prevent data race in 
RVVType::computeType (authored by kito-cheng).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138429

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

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -95,6 +95,7 @@
 class RVVEmitter {
 private:
   RecordKeeper &Records;
+  RVVTypeCache TypeCache;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -349,8 +350,8 @@
   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
   // Print RVV boolean types.
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Int8, Log2LMUL,
-  PrototypeDescriptor::Mask);
+auto T = TypeCache.computeType(BasicType::Int8, Log2LMUL,
+   PrototypeDescriptor::Mask);
 if (T)
   printType(T.value());
   }
@@ -358,10 +359,10 @@
   for (char I : StringRef("csil")) {
 BasicType BT = ParseBasicType(I);
 for (int Log2LMUL : Log2LMULs) {
-  auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
+  auto T = TypeCache.computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
   if (T) {
 printType(T.value());
-auto UT = RVVType::computeType(
+auto UT = TypeCache.computeType(
 BT, Log2LMUL,
 PrototypeDescriptor(BaseTypeModifier::Vector,
 VectorTypeModifier::NoModifier,
@@ -372,8 +373,8 @@
   }
   OS << "#if defined(__riscv_zvfh)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float16, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float16, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -381,8 +382,8 @@
 
   OS << "#if (__riscv_v_elen_fp >= 32)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float32, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float32, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -390,8 +391,8 @@
 
   OS << "#if (__riscv_v_elen_fp >= 64)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = RVVType::computeType(BasicType::Float64, Log2LMUL,
-  PrototypeDescriptor::Vector);
+auto T = TypeCache.computeType(BasicType::Float64, Log2LMUL,
+   PrototypeDescriptor::Vector);
 if (T)
   printType(T.value());
   }
@@ -553,14 +554,15 @@
   for (int Log2LMUL : Log2LMULList) {
 BasicType BT = ParseBasicType(I);
 Optional Types =
-RVVType::computeTypes(BT, Log2LMUL, NF, Prototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, Prototype);
 // Ignored to create new intrinsic if there are any illegal types.
 if (!Types)
   continue;
 
-auto SuffixStr = RVVIntrinsic::getSuffixStr(BT, Log2LMUL, SuffixDesc);
-auto OverloadedSuffixStr =
-RVVIntrinsic::getSuffixStr(BT, Log2LMUL, OverloadedSuffixDesc);
+auto SuffixStr =
+RVVIntrinsic::getSuffixStr(TypeCache, BT, Log2LMUL, SuffixDesc);
+auto OverloadedSuffixStr = RVVIntrinsic::getSuffixStr(
+TypeCache, BT, Log2LMUL, OverloadedSuffixDesc);
 // Create a unmasked intrinsic
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffixStr, IRName,
@@ -576,7 +578,7 @@
 /*HasMaskedOffOperand=*/false, HasVL, NF,
 IsPrototypeDefaultTU, UnMaskedPolicyScheme, P);
 Optional PolicyTypes =
-RVVType::computeTypes(BT, Log2LMUL, NF, PolicyPrototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, PolicyPrototype);
 Out.push_back(std::make_unique(
 Name, SuffixStr, OverloadedName, OverloadedSuffixStr, IRName,
 /*IsMask=*/false, /*HasMaskedOffOperand=*/false, HasVL,
@@ -588,7 +590,7 @@
   continue;
 // Create a masked intrinsic
 Optional MaskTypes =
-RVVType::computeTypes(BT, Log2LMUL, NF, Prototype);
+TypeCache.computeTypes(BT, Log2LMUL, NF, Prototype);
 Out.push_bac

[PATCH] D137488: [clang][Interp] Array initialization via string literal

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 477409.

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

https://reviews.llvm.org/D137488

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -350,6 +350,46 @@
 #endif
 
 #pragma clang diagnostic pop
+
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");
+
+  constexpr char foo2[] = "abc\0def";
+  static_assert(foo2[0] == 'a', "");
+  static_assert(foo2[3] == '\0', "");
+  static_assert(foo2[6] == 'f', "");
+  static_assert(foo2[7] == '\0', "");
+  static_assert(foo2[8] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+  constexpr char foo3[4] = "abc";
+  static_assert(foo3[3] == '\0', "");
+  static_assert(foo3[4] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+  constexpr char foo4[2] = "abcd"; // expected-error {{initializer-string for 
char array is too long}} \
+   // ref-error {{initializer-string for char 
array is too long}}
+  static_assert(foo4[0] == 'a', "");
+  static_assert(foo4[1] == 'b', "");
+  static_assert(foo4[2] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+constexpr char foo5[12] = "abc\xff";
+#if defined(__CHAR_UNSIGNED__) || __CHAR_BIT__ > 8
+static_assert(foo5[3] == 255, "");
+#else
+static_assert(foo5[3] == -1, "");
+#endif
 };
 
 #if __cplusplus > 201402L
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1073,6 +1073,33 @@
 return false;
 }
 return true;
+  } else if (const auto *SL = dyn_cast(Initializer)) {
+const ConstantArrayType *CAT =
+Ctx.getASTContext().getAsConstantArrayType(SL->getType());
+assert(CAT && "a string literal that's not a constant array?");
+
+// If the initializer string is too long, a diagnostic has already been
+// emitted. Read only the array length from the string literal.
+unsigned N = std::min(unsigned(CAT->getSize().getZExtValue()), 
SL->getLength());
+size_t CharWidth = SL->getCharByteWidth();
+
+for (unsigned I = 0; I != N; ++I) {
+  uint32_t CodeUnit = SL->getCodeUnit(I);
+
+  if (CharWidth == 1) {
+this->emitConstSint8(CodeUnit, SL);
+this->emitInitElemSint8(I, SL);
+  } else if (CharWidth == 2) {
+this->emitConstUint16(CodeUnit, SL);
+this->emitInitElemUint16(I, SL);
+  } else if (CharWidth == 4) {
+this->emitConstUint32(CodeUnit, SL);
+this->emitInitElemUint32(I, SL);
+  } else {
+llvm_unreachable("unsupported character width");
+  }
+}
+return true;
   }
 
   assert(false && "Unknown expression for array initialization");


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -350,6 +350,46 @@
 #endif
 
 #pragma clang diagnostic pop
+
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");
+
+  constexpr char foo2[] = "abc\0def";
+  static_assert(foo2[0] == 'a', "");
+  static_assert(foo2[3] == '\0', "");
+  static_assert(foo2[6] == 'f', "");
+  static_assert(foo2[7] == '\0', "");
+  static_assert(foo2[8] == '\0', ""); // expected-error {{not an integral constant expression}} \
+  // expected-note {{read of dereferenced one-past-the-end pointer}} \
+  

[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report. Demo: https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/ra

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

>> we are missing refs in some using declarations (line 31, line32), but line 
>> 33 does have a link which seems weird
>
> They are different types of symbol (template vs function), may make a 
> difference?

You're right, the template is the reason here. Taking a closing look, the logic 
of in WalkAST.cpp 

 doesn't seem to handle well on this case.

E.g. for the following case, the `UsingShadowDecl` refers to the *primary* 
template decl, which is not marked as used or referenced. The used/referenced 
bit is only set for specialized `FunctionDecl`, so WalkAST doesn't report this 
UsingDecl location. (`EnumDecl` also has this problem).

  namespace ns {
  template
  int func();
  }
  
  using ns::func; 
  
  int k = func();


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

My biggest concern here is propagating more information here without including 
it in the cache key.
Originally the computation was strictly using the cache key as input, but 
started using the command-line flags in D73453 
. @kadircet any extra context on when/why this 
is safe?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138546

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


[clang] 64f5fed - [ASTContext][NFC] Remove getTargetAddressSpace(Qualifiers Q)

2022-11-23 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-23T09:04:42Z
New Revision: 64f5fedb59e82a79c0c669c3d6591ca9eadb82fb

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

LOG: [ASTContext][NFC] Remove getTargetAddressSpace(Qualifiers Q)

This simply calls getTargetAddressSpace(Q.getAddressSpace()) and there
are only two callers, so adjust those caller instead.

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp
clang/lib/CodeGen/CodeGenTypes.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 2a21f2d1f37ee..6f695f096857f 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2812,8 +2812,6 @@ class ASTContext : public RefCountedBase {
 
   unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const;
-
   unsigned getTargetAddressSpace(LangAS AS) const;
 
   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index b9f9bec39317a..e887f44b3ca0b 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12234,11 +12234,7 @@ unsigned ASTContext::getTargetAddressSpace(QualType T) 
const {
   // the best address space based on the type information
   return T->isFunctionType() && !T.hasAddressSpace()
  ? getTargetInfo().getProgramAddressSpace()
- : getTargetAddressSpace(T.getQualifiers());
-}
-
-unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
-  return getTargetAddressSpace(Q.getAddressSpace());
+ : getTargetAddressSpace(T.getAddressSpace());
 }
 
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {

diff  --git a/clang/lib/CodeGen/CodeGenTypes.cpp 
b/clang/lib/CodeGen/CodeGenTypes.cpp
index 05956c2c1ec69..3869285e0b2cb 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -772,10 +772,10 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
 // Block pointers lower to function type. For function type,
 // getTargetAddressSpace() returns default address space for
 // function pointer i.e. program address space. Therefore, for block
-// pointers, it is important to pass qualifiers when calling
-// getTargetAddressSpace(), to ensure that we get the address space
-// for data pointers and not function pointers.
-unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
+// pointers, it is important to pass the pointee AST address space when
+// calling getTargetAddressSpace(), to ensure that we get the LLVM IR
+// address space for data pointers and not function pointers.
+unsigned AS = Context.getTargetAddressSpace(FTy.getAddressSpace());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }



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


[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:31
+default='clang-tools-extra/clangd/TidyFastChecks.inc')
+parser.add_argument('--file', help='clangd binary to invoke',
+default='clang/lib/Sema/Sema.cpp')

`file to use for benchmark`?



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:41
+def read_old_fast(path):
+text = subprocess.check_output(["cpp", "-P", "-FAST(C,T)=C", path])
+for line in text.splitlines():

what does `-P` do? shouldn't the latter be `-DFAST`?



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:70
+print("""// This file is generated, do not edit it directly!
+// This describes 
+#ifndef FAST

comment seems to be incomplete here



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:70
+print("""// This file is generated, do not edit it directly!
+// This describes 
+#ifndef FAST

kadircet wrote:
> comment seems to be incomplete here
it might be useful to include name of the file benchmarks were performed on in 
the output.



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:83
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})")
+

i don't see the point in including delta in the output if we're also making the 
decision here. is it mostly for debugging purposes? e.g. when updating the list 
we get to see the difference?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138491

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


[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report. Demo: https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/ra

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(I do think the outstanding issues are not related to this patch, so this is 
ready for review)

In D138219#3945954 , @hokein wrote:

> E.g. for the following case, the `UsingShadowDecl` refers to the *primary* 
> template decl, which is not marked as used or referenced. The used/referenced 
> bit is only set for specialized `FunctionDecl`, so WalkAST doesn't report 
> this UsingDecl location. (`EnumDecl` also has this problem).

That makes sense, I can imagine a few ways to fix this (change the bits in the 
AST, walk over specializations, drop the used||referenced approach).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138552: [docs] Document that the modules can improve the linking time

2022-11-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: dblaikie, iains, aaronmondal, MaskRay.
Herald added a subscriber: StephenFan.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We found that the linking time decreases significantly after using modules. It 
is a big surprise and I feel like it is good to document it. So that other 
people whose project is pretty slow at linking time now may have stronger 
motivation to use modules.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138552

Files:
  clang/docs/StandardCPlusPlusModules.rst


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -910,6 +910,70 @@
 this means the build speedup at higher optimization levels may be lower than 
expected given ``O0`` experience, 
 but does provide by more optimization opportunities.
 
+Can modules speedup linking?
+
+
+It is possible. Since the use of modules can reduce the symbols in the object 
files.
+
+Here is an example,
+
+.. code-block:: c++
+
+  // A.h
+  inline void notDirectlyUsed() {}
+  inline void DirectlyUsed() { notDirectlyUsed(); }
+
+  // A.cc
+  #include "A.h"
+  void foo() { DirectlyUsed(); }
+
+then compile it and look the generated symbol with the following commands
+
+.. code-block:: console
+
+  $ clang++ -std=c++20 A.cc -c -o A.o
+  $ nm -C A.o
+   W DirectlyUsed()
+   W notDirectlyUsed()
+   T foo()
+
+now let's check the result after using modules with the following example:
+
+.. code-block:: c++
+
+  // A.cppm
+  export module A;
+  void notDirectlyUsed() {}
+  export void DirectlyUsed() { notDirectlyUsed(); }
+  
+  // A.cc
+  #include "A.h"
+  void foo() { DirectlyUsed(); }
+
+compile it with the following commands:
+
+.. code-block:: console
+
+  $ clang++ -std=c++20 A.cppm --precompile -o A.pcm
+  $ clang++ -std=c++20 A.cc -fprebuilt-module-path=. -c -o A.o
+  $ nm -C A.o
+   t _GLOBAL__sub_I_Use.cc
+   T foo()
+   U _ZGIW1A
+   U _ZW1A12DirectlyUsedv
+
+First we can find that there are 2 additional symbols ``_GLOBAL__sub_I_Use`` 
and
+``_ZGIW1A``. These 2 symbols are used to initialize the current object file and
+the module A.
+
+The interesting part here is that there is not the symbol for 
``notDirectlyUsed``.
+In a real world project, the number of ``notDirectlyUsed`` symbols should
+usually be much more than the ``DirectlyUsed`` ones.
+
+So that we can reduce many symbols in the object files and so we can speedup 
linking
+by using modules. Note that things may be better with optimizations, since the
+``DirectlyUsed`` ones may be optimized out.
+
 Interoperability with Clang Modules
 ---
 


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -910,6 +910,70 @@
 this means the build speedup at higher optimization levels may be lower than expected given ``O0`` experience, 
 but does provide by more optimization opportunities.
 
+Can modules speedup linking?
+
+
+It is possible. Since the use of modules can reduce the symbols in the object files.
+
+Here is an example,
+
+.. code-block:: c++
+
+  // A.h
+  inline void notDirectlyUsed() {}
+  inline void DirectlyUsed() { notDirectlyUsed(); }
+
+  // A.cc
+  #include "A.h"
+  void foo() { DirectlyUsed(); }
+
+then compile it and look the generated symbol with the following commands
+
+.. code-block:: console
+
+  $ clang++ -std=c++20 A.cc -c -o A.o
+  $ nm -C A.o
+   W DirectlyUsed()
+   W notDirectlyUsed()
+   T foo()
+
+now let's check the result after using modules with the following example:
+
+.. code-block:: c++
+
+  // A.cppm
+  export module A;
+  void notDirectlyUsed() {}
+  export void DirectlyUsed() { notDirectlyUsed(); }
+  
+  // A.cc
+  #include "A.h"
+  void foo() { DirectlyUsed(); }
+
+compile it with the following commands:
+
+.. code-block:: console
+
+  $ clang++ -std=c++20 A.cppm --precompile -o A.pcm
+  $ clang++ -std=c++20 A.cc -fprebuilt-module-path=. -c -o A.o
+  $ nm -C A.o
+   t _GLOBAL__sub_I_Use.cc
+   T foo()
+   U _ZGIW1A
+   U _ZW1A12DirectlyUsedv
+
+First we can find that there are 2 additional symbols ``_GLOBAL__sub_I_Use`` and
+``_ZGIW1A``. These 2 symbols are used to initialize the current object file and
+the module A.
+
+The interesting part here is that there is not the symbol for ``notDirectlyUsed``.
+In a real world project, the number of ``notDirectlyUsed`` symbols 

[PATCH] D136920: [clang][Interp] Array initialization via CXXConstructExpr

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 477418.

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

https://reviews.llvm.org/D136920

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/arrays.cpp


Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -185,6 +185,40 @@
   }
 };
 
+class A {
+public:
+  int a;
+  constexpr A(int m = 2) : a(10 + m) {}
+};
+class AU {
+public:
+  int a;
+  constexpr AU() : a(5 / 0) {} // expected-warning {{division by zero is 
undefined}} \
+   // expected-note {{division by zero}} \
+   // ref-error {{never produces a constant 
expression}} \
+   // ref-note 2{{division by zero}} \
+   // ref-warning {{division by zero is undefined}}
+};
+class B {
+public:
+  A a[2];
+  constexpr B() {}
+};
+constexpr B b;
+static_assert(b.a[0].a == 12, "");
+static_assert(b.a[1].a == 12, "");
+
+class BU {
+public:
+  AU a[2];
+  constexpr BU() {} // expected-note {{in call to 'AU()'}} \
+// ref-note {{in call to 'AU()'}}
+};
+constexpr BU bu; // expected-error {{must be initialized by a constant 
expression}} \
+ // expected-note {{in call to 'BU()'}} \
+ // ref-error {{must be initialized by a constant expression}} 
\
+ // ref-note {{in call to 'BU()'}}
+
 namespace IncDec {
   // FIXME: Pointer arithmethic needs to be supported in inc/dec
   //   unary operators
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1012,6 +1012,37 @@
   assert(false && "default initializer for non-primitive type");
 }
 
+return true;
+  } else if (const auto *Ctor = dyn_cast(Initializer)) {
+const ConstantArrayType *CAT =
+Ctx.getASTContext().getAsConstantArrayType(Ctor->getType());
+assert(CAT);
+size_t NumElems = CAT->getSize().getZExtValue();
+const Function *Func = getFunction(Ctor->getConstructor());
+if (!Func || !Func->isConstexpr())
+  return false;
+
+// FIXME(perf): We're calling the constructor once per array element here,
+//   in the old intepreter we had a special-case for trivial constructors.
+for (size_t I = 0; I != NumElems; ++I) {
+  if (!this->emitDupPtr(Initializer))
+return false;
+  if (!this->emitConstUint64(I, Initializer))
+return false;
+  if (!this->emitAddOffsetUint64(Initializer))
+return false;
+  if (!this->emitNarrowPtr(Initializer))
+return false;
+
+  // Constructor arguments.
+  for (const auto *Arg : Ctor->arguments()) {
+if (!this->visit(Arg))
+  return false;
+  }
+
+  if (!this->emitCall(Func, Initializer))
+return false;
+}
 return true;
   }
 


Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -185,6 +185,40 @@
   }
 };
 
+class A {
+public:
+  int a;
+  constexpr A(int m = 2) : a(10 + m) {}
+};
+class AU {
+public:
+  int a;
+  constexpr AU() : a(5 / 0) {} // expected-warning {{division by zero is undefined}} \
+   // expected-note {{division by zero}} \
+   // ref-error {{never produces a constant expression}} \
+   // ref-note 2{{division by zero}} \
+   // ref-warning {{division by zero is undefined}}
+};
+class B {
+public:
+  A a[2];
+  constexpr B() {}
+};
+constexpr B b;
+static_assert(b.a[0].a == 12, "");
+static_assert(b.a[1].a == 12, "");
+
+class BU {
+public:
+  AU a[2];
+  constexpr BU() {} // expected-note {{in call to 'AU()'}} \
+// ref-note {{in call to 'AU()'}}
+};
+constexpr BU bu; // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{in call to 'BU()'}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{in call to 'BU()'}}
+
 namespace IncDec {
   // FIXME: Pointer arithmethic needs to be supported in inc/dec
   //   unary operators
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1012,6 +1012,37 @@
   assert(false && "default initializer for non-primitive type");
 }
 
+return true;
+  } else if (const auto *Ctor = dyn_cast(Initializer)) {
+const ConstantArrayType *CAT =
+Ctx.getASTContext().getAsConstantArrayType(Ctor->getType());
+ass

[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Christopher Sauer via Phabricator via cfe-commits
cpsauer added a comment.

Sam, my read, too, is that the memoizing design isn't safe--also that the key 
bug is preexisting.

I had the same reaction reading through this file after spotting problems in 
the log. That's what spawned https://github.com/clangd/clangd/issues/1378.

Any chance I could get you to quickly read through that issue if you haven't 
already? (The relevant section to this part: "If we think sysroots, targets, 
and the other flags enumerated effect the system includes, we'd better include 
them as part of the memoization key.")

There are sadly *lots* of problems in this file that leap out on a quick read. 
Nathan and I were thinking, though, that we'd should post this incremental fix 
for review rather than getting bogged down in trying to fix multiple things 
atomically.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138546

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


[PATCH] D136920: [clang][Interp] Array initialization via CXXConstructExpr

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:962-963
+  } else if (const auto *Ctor = dyn_cast(Initializer)) {
+const ArrayType *AT = Ctor->getType()->getAsArrayTypeUnsafe();
+const auto *CAT = cast(AT);
+size_t NumElems = CAT->getSize().getZExtValue();

aaron.ballman wrote:
> This should go through `ASTContext::getConstantArrayType()`. It may also be 
> worth a comment mentioning that VLAs can't have initializers and an unbounded 
> array has known bounds if it has an initializer, as I suspect that's the 
> reason you're not handling either of those here?
I'm not handling them because they are untested everywhere. :/



Comment at: clang/test/AST/Interp/arrays.cpp:188-200
+class A {
+public:
+  int a;
+  constexpr A(int m = 2) : a(10 + m) {}
+};
+class B {
+public:

aaron.ballman wrote:
> I'd like to see a test for when the class ends with a flexible array member 
> (ctor shouldn't be called for that case because we don't know how many 
> trailing objects there will be). That could show up as an unbounded member.
> 
> Also, a test case where the ctor will execute UB, to demonstrate we properly 
> diagnose arrays of default-constructed objects.
I added a test for a UB constructor, but a flexible array member shows up as a 
non-`ConstantArrayType` member, so the code runs into one or the other 
assertion.


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

https://reviews.llvm.org/D136920

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


[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 3 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:41
+def read_old_fast(path):
+text = subprocess.check_output(["cpp", "-P", "-FAST(C,T)=C", path])
+for line in text.splitlines():

kadircet wrote:
> what does `-P` do? shouldn't the latter be `-DFAST`?
-P avoids emitting `# 0 /path/to/Sema.cpp` lines. Added comments

Fixed `-DFAST`, I must have somehow mangled this after running it!



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:83
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})")
+

kadircet wrote:
> i don't see the point in including delta in the output if we're also making 
> the decision here. is it mostly for debugging purposes? e.g. when updating 
> the list we get to see the difference?
Yes, that's exactly the reason. Can make it a comment instead if you like, but 
that makes ad-hoc analysis slightly harder.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138491

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


[PATCH] D138554: [clang][Interp] Use placement new to construct opcode arguments into bytecode vector

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik, 
sepavloff.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is split-out from https://reviews.llvm.org/D134859 as it showed up there.

When the opcode argument is not trivially copyable, we can't just memcpy it 
into our code vector. Use placement new to copy it instead.

This is currently dead code without https://reviews.llvm.org/D134859.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138554

Files:
  clang/lib/AST/Interp/ByteCodeEmitter.cpp


Index: clang/lib/AST/Interp/ByteCodeEmitter.cpp
===
--- clang/lib/AST/Interp/ByteCodeEmitter.cpp
+++ clang/lib/AST/Interp/ByteCodeEmitter.cpp
@@ -163,8 +163,15 @@
   }
 
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+if constexpr (std::is_trivially_copyable_v) {
+  const char *Data = reinterpret_cast(&Val);
+  Code.insert(Code.end(), Data, Data + Size);
+} else {
+  // Construct the value directly into our storage vector.
+  size_t ValPos = Code.size();
+  Code.resize(Code.size() + Size);
+  new (Code.data() + ValPos) T(Val);
+}
   } else {
 uint32_t ID = P.getOrCreateNativePointer(Val);
 const char *Data = reinterpret_cast(&ID);


Index: clang/lib/AST/Interp/ByteCodeEmitter.cpp
===
--- clang/lib/AST/Interp/ByteCodeEmitter.cpp
+++ clang/lib/AST/Interp/ByteCodeEmitter.cpp
@@ -163,8 +163,15 @@
   }
 
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+if constexpr (std::is_trivially_copyable_v) {
+  const char *Data = reinterpret_cast(&Val);
+  Code.insert(Code.end(), Data, Data + Size);
+} else {
+  // Construct the value directly into our storage vector.
+  size_t ValPos = Code.size();
+  Code.resize(Code.size() + Size);
+  new (Code.data() + ValPos) T(Val);
+}
   } else {
 uint32_t ID = P.getOrCreateNativePointer(Val);
 const char *Data = reinterpret_cast(&ID);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137415: [clang][Interp] Implement switch statements

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


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

https://reviews.llvm.org/D137415

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


[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report. Demo: https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/ra

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D138219#3946020 , @sammccall wrote:

> In D138219#3945954 , @hokein wrote:
>
>> E.g. for the following case, the `UsingShadowDecl` refers to the *primary* 
>> template decl, which is not marked as used or referenced. The 
>> used/referenced bit is only set for specialized `FunctionDecl`, so WalkAST 
>> doesn't report this UsingDecl location. (`EnumDecl` also has this problem).
>
> That makes sense, I can imagine a few ways to fix this (change the bits in 
> the AST, walk over specializations, drop the used||referenced approach).

Filed https://github.com/llvm/llvm-project/issues/59147


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138216: [AMDGPU] Intrinsic to expose s_wait_event for export ready

2022-11-23 Thread David Stuttard via Phabricator via cfe-commits
dstuttard updated this revision to Diff 477423.
dstuttard added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Updated - adding test for builtin


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138216

Files:
  clang/include/clang/Basic/BuiltinsAMDGPU.def
  clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
  llvm/include/llvm/IR/IntrinsicsAMDGPU.td
  llvm/lib/Target/AMDGPU/SOPInstructions.td
  llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll


Index: llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
@@ -0,0 +1,15 @@
+; RUN: llc -global-isel=0 -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < 
%s | FileCheck -check-prefix=GCN %s
+; RUN: llc -global-isel -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s 
| FileCheck -check-prefix=GCN %s
+
+; GCN-LABEL: {{^}}test_wait_event:
+; GCN: s_wait_event 0x0
+
+define amdgpu_ps void @test_wait_event() #0 {
+entry:
+  call void @llvm.amdgcn.s.wait.event.export.ready() #0
+  ret void
+}
+
+declare void @llvm.amdgcn.s.wait.event.export.ready() #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Target/AMDGPU/SOPInstructions.td
===
--- llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1388,7 +1388,9 @@
 
 let SubtargetPredicate = isGFX11Plus in {
   def S_WAIT_EVENT : SOPP_Pseudo<"s_wait_event", (ins s16imm:$simm16),
- "$simm16">;
+ "$simm16"> {
+   let hasSideEffects = 1;
+ }
   def S_DELAY_ALU : SOPP_Pseudo<"s_delay_alu", (ins DELAY_FLAG:$simm16),
 "$simm16">;
 } // End SubtargetPredicate = isGFX11Plus
@@ -1430,6 +1432,10 @@
   (S_SEXT_I32_I16 $src)
 >;
 
+def : GCNPat <
+  (int_amdgcn_s_wait_event_export_ready),
+(S_WAIT_EVENT (i16 0))
+>;
 
 
//===--===//
 // SOP2 Patterns
Index: llvm/include/llvm/IR/IntrinsicsAMDGPU.td
===
--- llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -2067,6 +2067,10 @@
 def int_amdgcn_wmma_i32_16x16x16_iu8   : AMDGPUWmmaIntrinsicIU;
 def int_amdgcn_wmma_i32_16x16x16_iu4   : AMDGPUWmmaIntrinsicIU;
 
+def int_amdgcn_s_wait_event_export_ready :
+  ClangBuiltin<"__builtin_amdgcn_s_wait_event_export_ready">,
+  Intrinsic<[], [], [IntrNoMem, IntrHasSideEffects, IntrWillReturn]
+>;
 
 
//===--===//
 // Deep learning intrinsics.
Index: clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
===
--- clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
+++ clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
@@ -37,3 +37,9 @@
 void test_permlane64(global uint* out, uint a) {
   *out = __builtin_amdgcn_permlane64(a);
 }
+
+// CHECK-LABEL: @test_s_wait_event_export_ready
+// CHECK: call void @llvm.amdgcn.s.wait.event.export.ready
+void test_s_wait_event_export_ready() {
+  __builtin_amdgcn_s_wait_event_export_ready();
+}
Index: clang/include/clang/Basic/BuiltinsAMDGPU.def
===
--- clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -261,6 +261,7 @@
 
 // TODO: This is a no-op in wave32. Should the builtin require wavefrontsize64?
 TARGET_BUILTIN(__builtin_amdgcn_permlane64, "UiUi", "nc", "gfx11-insts")
+TARGET_BUILTIN(__builtin_amdgcn_s_wait_event_export_ready, "v", "n", 
"gfx11-insts")
 
 
//===--===//
 // WMMA builtins.


Index: llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
@@ -0,0 +1,15 @@
+; RUN: llc -global-isel=0 -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s | FileCheck -check-prefix=GCN %s
+; RUN: llc -global-isel -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s | FileCheck -check-prefix=GCN %s
+
+; GCN-LABEL: {{^}}test_wait_event:
+; GCN: s_wait_event 0x0
+
+define amdgpu_ps void @test_wait_event() #0 {
+entry:
+  call void @llvm.amdgcn.s.wait.event.export.ready() #0
+  ret void
+}
+
+declare void @llvm.amdgcn.s.wait.event.export.ready() #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Target/AMDGPU/SOPInstructions.td
===
--- llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1388,7 +1388,9 

[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report. Demo: https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/ra

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

In D138219#3946020 , @sammccall wrote:

> (I do think the outstanding issues are not related to this patch, so this is 
> ready for review)

Agree (sorry, I didn't mean we should address in this patch). We have found a 
few issues, I think we should record them in the issue tracker so that we don't 
lose them.




Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:116
   FileID File;
+  const FileEntry *FE;
 

nit: the `FE` can be removed -- we have the FileID, we can retrieve it by 
`SM.getFileEntryByID(File)`



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:126
+SmallVector Includes;
+bool Satisfied = false;
   };

Worth to add a comment on the meaning of `Satisfied`.





Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:160
+
+for (const auto &H : T.Headers) {
+  T.Includes.append(Includes.match(H));

The current behaivor looks fine to me, but this is not the final state, right? 
We will revisit it when we have all the ranking/included-header bits in the 
library, if so, probably add a FIXME?



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:162
+  T.Includes.append(Includes.match(H));
+  if (H.kind() == Header::Physical && H.physical() == FE)
+T.Satisfied = true;

a comment -- this is for the target symbol defined in the main file?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D138546#3946046 , @cpsauer wrote:

> Sam, my read, too, is that the memoizing design isn't safe--also that the key 
> bug is preexisting. 
> Nathan and I were thinking, though, that we'd should post this incremental 
> fix for review rather than getting bogged down in trying to fix multiple 
> things atomically.

Sure. At first glance the design looks like it's been changed in a way that's 
broken, but maybe there's some deeper reason that it's safe. That reason may or 
may not also apply to `-target` (e.g. if `-target` could plausibly differ 
across a project but other flags couldn't). I wanted to understand whether/why 
it's broken today before concluding it's safe to break it further. Probably 
@kadircet is the best person to make a call here.

> I had the same reaction reading through this file after spotting problems in 
> the log. That's what spawned https://github.com/clangd/clangd/issues/1378.
>
> Any chance I could get you (and others) to quickly read through that issue if 
> you haven't already? (The relevant section to this part: "If we think 
> sysroots, targets, and the other flags enumerated effect the system includes, 
> we'd better include them as part of the memoization key.") )

The discussion in this bug makes sense to me. I agree with the need for 
memoization, and the handling of `-isysroot` indeed looks dodgy and could 
probably be fixed.
Framework support sounds important for Mac, and we'd be happy to take a 
contribution from a Mac person who can explain the issues there.
Reusing clang's arg parser is tricky: it's a large change, it's often more 
complex than naive string-bashing, and it's also significantly slower.

Unfortunately at the moment I'm not really able to spend work time on improving 
these things, beyond reviewing patches.
(The system include extractor is mostly useful for things that don't build with 
stock clang, which at $employer is a minority).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138546

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


[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

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

review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138491

Files:
  clang-tools-extra/clangd/TidyFastChecks.inc
  clang-tools-extra/clangd/TidyFastChecks.py
  clang-tools-extra/clangd/tool/Check.cpp

Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -241,6 +241,9 @@
 elog("-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
 return false;
   }
+  #ifndef NDEBUG
+  elog("Timing clang-tidy checks in asserts-mode is not representative!");
+  #endif
   checkTidyTimes();
 }
 
Index: clang-tools-extra/clangd/TidyFastChecks.py
===
--- /dev/null
+++ clang-tools-extra/clangd/TidyFastChecks.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+#
+# Determines which clang-tidy checks are "fast enough" to run in clangd.
+# This runs clangd --check --check-tidy-time and parses the output.
+# This program outputs a header fragment specifying which checks are fast:
+#   FAST(bugprone-argument-comment, 5)
+#   SLOW(misc-const-correctness, 200)
+# If given the old header fragment as input, we lean to preserve its choices.
+#
+# This is not deterministic or hermetic, but should be run occasionally to
+# update the list of allowed checks. From llvm-project:
+#   clang-tools-extra/clangd/TidyFastChecks.py \
+# --clangd=build-opt/bin/clangd \
+# > clang-tools-extra/clangd/TidyFastChecks.inc
+# Be sure to use an optimized, no-asserts, tidy-enabled build of clangd!
+
+import argparse
+import re
+import subprocess
+import sys
+
+# Checks faster than FAST_THRESHOLD are fast, slower than SLOW_THRESHOLD slow.
+# If a check is in between, we stick with our previous decision. This avoids
+# enabling/disabling checks between releases due to random measurement jitter.
+FAST_THRESHOLD = 8 # percent
+SLOW_THRESHOLD = 15
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--old', help='Existing TidyFastChecks.inc, for hysteresis',
+default='clang-tools-extra/clangd/TidyFastChecks.inc')
+parser.add_argument('--file', help='Source file to benchmark tidy checks',
+default='clang/lib/Sema/Sema.cpp')
+parser.add_argument('--clangd', help='clangd binary to invoke',
+default='build/bin/clangd')
+parser.add_argument('--checks', help='check glob to run', default='*')
+parser.add_argument('--verbose', help='log clangd output', action='store_true')
+args = parser.parse_args()
+
+# Use the preprocessor to extract the list of previously-fast checks.
+def read_old_fast(path):
+text = subprocess.check_output(["cpp",
+"-P",# Omit GNU line markers
+"-nostdinc", # Don't include stdc-predef.h
+"-DFAST(C,T)=C", # Print fast checks only
+path])
+for line in text.splitlines():
+if line.strip():
+yield line.strip().decode('utf-8')
+old_fast = list(read_old_fast(args.old)) if args.old else []
+print(f"Old fast checks: {old_fast}", file=sys.stderr)
+
+# Runs clangd --check --check-tidy-time.
+# Yields (check, percent-overhead) pairs.
+def measure():
+process = subprocess.Popen([args.clangd,
+"--check=" + args.file,
+"--check-locations=0", # Skip useless slow steps.
+"--check-tidy-time=" + args.checks],
+stderr=subprocess.PIPE)
+recording = False
+for line in iter(process.stderr.readline, b""):
+if args.verbose:
+print("clangd> ", line, file=sys.stderr)
+if not recording:
+if b'Timing AST build with individual clang-tidy checks' in line:  
+   recording = True
+continue
+if b'Finished individual clang-tidy checks' in line:
+return
+match = re.search(rb'(\S+) = (\S+)%', line)
+if match:
+yield (match.group(1).decode('utf-8'), float(match.group(2)))
+
+# Produce an includable X-macros fragment with our decisions.
+print(f"""// This file is generated, do not edit it directly!
+// Deltas are perncentage regression in parsing {args.file}
+#ifndef FAST
+#define FAST(CHECK, DELTA)
+#endif
+#ifndef SLOW
+#define SLOW(CHECK, DELTA)
+#endif
+""")
+
+for check, time in measure():
+threshold = SLOW_THRESHOLD if check in old_fast else FAST_THRESHOLD
+decision = "FAST" if time <= threshold else "SLOW"
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})")
+
+print("""
+#undef FAST
+#undef SLOW
+""")
Index: clang-tools-extra/clangd/TidyFastChecks.inc
===
--- /dev/null
+++ clang-tools-extra/clangd/TidyFastChecks.inc
@@ -0,0

[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/TidyFastChecks.inc:2
+// This file is generated, do not edit it directly!
+// This describes 
+#ifndef FAST

can you also re-run the script before checking in (or update here, since 
re-running all might take a while, but would be a good way to test history 
preserving logic)



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:76
+print(f"""// This file is generated, do not edit it directly!
+// Deltas are perncentage regression in parsing {args.file}
+#ifndef FAST

s/perncentage/percentage



Comment at: clang-tools-extra/clangd/TidyFastChecks.py:83
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})")
+

sammccall wrote:
> kadircet wrote:
> > i don't see the point in including delta in the output if we're also making 
> > the decision here. is it mostly for debugging purposes? e.g. when updating 
> > the list we get to see the difference?
> Yes, that's exactly the reason. Can make it a comment instead if you like, 
> but that makes ad-hoc analysis slightly harder.
if that's the case no need. just wanted to make sure about it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138491

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


[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Christopher Sauer via Phabricator via cfe-commits
cpsauer added a comment.

Makes sense! Thanks for your time, Sam, and for being great, as always.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138546

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


[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2022-11-23 Thread Christopher Sauer via Phabricator via cfe-commits
cpsauer added a comment.

I suppose, if it ever might help make the case with said employer (Google, 
right?) the broken, non-stock-clang use case that's motivating this is Android 
(and also usage from Bazel/Blaze).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138546

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


[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report. Demo: https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/ra

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:116
   FileID File;
+  const FileEntry *FE;
 

hokein wrote:
> nit: the `FE` can be removed -- we have the FileID, we can retrieve it by 
> `SM.getFileEntryByID(File)`
Sure, I'd just rather do that in the constructor than in the inner loop



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:160
+
+for (const auto &H : T.Headers) {
+  T.Includes.append(Includes.match(H));

hokein wrote:
> The current behaivor looks fine to me, but this is not the final state, 
> right? We will revisit it when we have all the ranking/included-header bits 
> in the library, if so, probably add a FIXME?
Ranking isn't relevant whether a ref is satisfied or not.

If we add the concept of one provider dominating another, this logic might 
change. (e.g. for `std::vector` accept `` but not if `` is 
included). But this is up in the air and also would probably be encapsulated in 
a signature change to `Includes.match`.

Added a FIXME to avoid the brittle main-file check.



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:162
+  T.Includes.append(Includes.match(H));
+  if (H.kind() == Header::Physical && H.physical() == FE)
+T.Satisfied = true;

hokein wrote:
> a comment -- this is for the target symbol defined in the main file?
Defined or declared or otherwise provided by the main file.
Renamed FE => MainFE. Beyond that I think such a comment just echoes the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report.

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 477429.
sammccall retitled this revision from "[include-cleaner] Show includes matched 
by refs in HTML report.

Demo: 
https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/raw/8736e64c45af411e2c2d72adaed2dfc4410a5b36/ASTTests.html%25202";
 to "[include-cleaner] Show includes matched by refs in HTML report.".
sammccall edited the summary of this revision.
sammccall added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

Files:
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Index: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
===
--- clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -71,8 +71,8 @@
<< ": " << EC.message() << "\n";
   exit(1);
 }
-writeHTMLReport(AST.Ctx->getSourceManager().getMainFileID(), AST.Roots,
-PP.MacroReferences, *AST.Ctx, &PI, OS);
+writeHTMLReport(AST.Ctx->getSourceManager().getMainFileID(), PP.Includes,
+AST.Roots, PP.MacroReferences, *AST.Ctx, &PI, OS);
   }
 };
 
Index: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
===
--- clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
+++ clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
@@ -51,6 +51,7 @@
   #hover p, #hover pre { margin: 0; }
   #hover .target.implicit { background-color: #bbb; }
   #hover .target.ambiguous { background-color: #caf; }
+  .missing, .unused { background-color: #faa !important; }
   #hover th { color: #008; text-align: right; padding-right: 0.5em; }
   #hover .target:not(:first-child) {
 margin-top: 1em;
@@ -110,8 +111,10 @@
   llvm::raw_ostream &OS;
   const ASTContext &Ctx;
   const SourceManager &SM;
+  const RecordedPP::RecordedIncludes &Includes;
   const PragmaIncludes *PI;
   FileID File;
+  const FileEntry *MainFE;
 
   // References to symbols from the main file.
   // FIXME: should we deduplicate these?
@@ -120,6 +123,8 @@
 RefType Type;
 SmallVector Locations;
 SmallVector Headers;
+SmallVector Includes;
+bool Satisfied = false; // Is the include present?
   };
   std::vector Targets;
   // Points within the main file that reference a Target.
@@ -136,7 +141,7 @@
   std::vector Refs;
 
   Target makeTarget(const SymbolReference &SR) {
-Target T{SR.Target, SR.RT, {}, {}};
+Target T{SR.Target, SR.RT, {}, {}, {}};
 
 // Duplicates logic from walkUsed(), which doesn't expose SymbolLocations.
 // FIXME: use locateDecl and friends once implemented.
@@ -151,15 +156,31 @@
 }
 
 for (const auto &Loc : T.Locations)
-  T.Headers = findHeaders(Loc, SM, PI);
+  T.Headers.append(findHeaders(Loc, SM, PI));
+
+for (const auto &H : T.Headers) {
+  T.Includes.append(Includes.match(H));
+  // FIXME: library should signal main-file refs somehow.
+  // Non-physical refs to the main-file should be possible.
+  if (H.kind() == Header::Physical && H.physical() == MainFE)
+T.Satisfied = true;
+}
+if (!T.Includes.empty())
+  T.Satisfied = true;
+// Include pointers are meaningfully ordered as they are backed by a vector.
+llvm::sort(T.Includes);
+T.Includes.erase(std::unique(T.Includes.begin(), T.Includes.end()),
+ T.Includes.end());
 
 return T;
   }
 
 public:
-  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx, const PragmaIncludes *PI,
-   FileID File)
-  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), PI(PI), File(File) {}
+  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx,
+   const RecordedPP::RecordedIncludes &Includes,
+   const PragmaIncludes *PI, FileID File)
+  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), Includes(Includes),
+PI(PI), File(File), MainFE(SM.getFileEntryForID(File)) {}
 
   void addRef(const SymbolReference &SR) {
 auto [File, Offset] = SM.getDecomposedLoc(SM.getFileLoc(SR.RefLocation));
@@ -289,6 +310,13 @@
   OS << "\n";
 }
 
+for (const auto *I : T.Includes) {
+  OS << "Included";
+  escapeString(I->Spelled);
+  OS << ", line " << I->Line << "";
+  OS << "";
+}
+
 OS << "";
   }
 
@@ -297,7 +325,8 @@
 llvm::StringRef Code = SM.getBufferData(File);
 
 OS << "";
-OS << "";
+OS << "";
+unsigned LineNum = 1;
 auto Rest = llvm::makeArrayRef(Refs);
 unsigned End = 0;
 for (unsigned I = 0; I < Code.size(); ++I) {
@@ -310,12 +339,14 @@
   while (!Rest.empty() && Rest.front().Offset == I &&
  Rest.front().Implicit

[PATCH] D138505: [clangd] Don't run slow clang-tidy checks

2022-11-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D138505#3944285 , @sammccall wrote:

> Ideas on testing welcome. Does it make sense to rely on the fact that 
> `misc-const-correctness` is always slow? :-D

I'd say it doesn't, if the check is ever updated in a way to be more performant 
it'd be nice if we don't need to change anything hard coded in clangd to enable 
it to run again.




Comment at: clang-tools-extra/clangd/ParsedAST.cpp:487
+  }
+  CTFactories = std::move(FastFactories);
+}

Not exactly related but surely both check factories could be made into static 
variables and then just choose the factory based on the config.



Comment at: clang-tools-extra/clangd/tool/Check.cpp:468
+  // is counterproductive! 
+  if (CheckTidyTime.getNumOccurrences())
+F.Diagnostics.ClangTidy.SlowChecks = true;

How about changing this provide to always enable slow checks, but only use the 
provider if the flag is passed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138505

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


[clang] 63d65d3 - Reland "[CGObjC] Add run line for release mode in test arc-exceptions-seh.mm (NFC)"

2022-11-23 Thread Stefan Gränitz via cfe-commits

Author: Stefan Gränitz
Date: 2022-11-23T11:35:22+01:00
New Revision: 63d65d3764ea2fc27e0e1a6054ec42cff6d84158

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

LOG: Reland "[CGObjC] Add run line for release mode in test 
arc-exceptions-seh.mm (NFC)"

This reverts commit a37807ac8a3e9d2880a483940dcd33194f354bf8.

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

Added: 


Modified: 
clang/test/CodeGenObjCXX/arc-exceptions-seh.mm

Removed: 




diff  --git a/clang/test/CodeGenObjCXX/arc-exceptions-seh.mm 
b/clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
index b432abcda97d6..d5daf55db 100644
--- a/clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
+++ b/clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -emit-llvm -fobjc-arc 
-fexceptions -fobjc-exceptions -fobjc-arc-exceptions -fobjc-runtime=gnustep-2.0 
-o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -emit-llvm -fobjc-arc 
-fexceptions -fobjc-exceptions -fobjc-arc-exceptions -fobjc-runtime=gnustep-2.0 
-o - %s | FileCheck %s --check-prefixes=CHECK,CHECK-O0
+// RUN: %clang_cc1 -O2 -triple x86_64-pc-windows-msvc -emit-llvm -fobjc-arc 
-fexceptions -fobjc-exceptions -fobjc-arc-exceptions -fobjc-runtime=gnustep-2.0 
-mllvm -enable-objc-arc-opts=false -o - %s | FileCheck %s 
--check-prefixes=CHECK,CHECK-O2
 
 // WinEH requires funclet tokens on nounwind intrinsics if they can lower to
 // regular function calls in the course of IR transformations.
@@ -40,18 +41,21 @@ void try_catch_with_objc_intrinsic() {
 // CHECK: [ "funclet"(token [[CATCHPAD]]) ]
 // CHECK: unwind label %[[CLEANUP2]]
 // CHECK:   call
-// CHECK: @llvm.objc.storeStrong
+// CHECK-O0:  @llvm.objc.storeStrong
+// CHECK-O2:  @llvm.objc.release
 // CHECK: [ "funclet"(token [[CATCHPAD]]) ]
-// CHECK:   catchret from [[CATCHPAD]] to label %catchret.dest
+// CHECK-O0:catchret from [[CATCHPAD]] to label %catchret.dest
+// CHECK-O2:catchret from [[CATCHPAD]] to label %eh.cont
 //
-// This block exists and it's empty:
-// CHECK: catchret.dest:
-// CHECK-NEXT:  br label %eh.cont
+// In debug mode, this block exists and it's empty:
+// CHECK-O0:  catchret.dest:
+// CHECK-O0-NEXT:   br label %eh.cont
 //
 // CHECK: [[CLEANUP2]]:
 // CHECK-NEXT:  [[CLEANUPPAD2:%[0-9]+]] = cleanuppad within [[CATCHPAD]]
 // CHECK:   call
-// CHECK: @llvm.objc.storeStrong
+// CHECK-O0:  @llvm.objc.storeStrong
+// CHECK-O2:  @llvm.objc.release
 // CHECK: [ "funclet"(token [[CLEANUPPAD2]]) ]
 // CHECK:   cleanupret from [[CLEANUPPAD2]]
 // CHECK: unwind label %[[CLEANUP1]]
@@ -59,6 +63,7 @@ void try_catch_with_objc_intrinsic() {
 // CHECK: [[CLEANUP1]]:
 // CHECK-NEXT:  [[CLEANUPPAD1:%[0-9]+]] = cleanuppad within none
 // CHECK:   call
-// CHECK: @llvm.objc.storeStrong
+// CHECK-O0:  @llvm.objc.storeStrong
+// CHECK-O2:  @llvm.objc.release
 // CHECK: [ "funclet"(token [[CLEANUPPAD1]]) ]
 // CHECK:   cleanupret from [[CLEANUPPAD1]] unwind to caller



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


[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report.

2022-11-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp:116
   const PragmaIncludes *PI;
   FileID File;
+  const FileEntry *MainFE;

nit: maybe rename to MainFile to correspond to the `MainFE`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

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


[PATCH] D138426: Fix #58958 on github

2022-11-23 Thread Alexey Kreshchuk via Phabricator via cfe-commits
krsch added a comment.

Should I change the title myself or you can change it during commit? If it's on 
me, how do I change it? `git commit --amend; arc diff`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138426

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


[PATCH] D138122: Lift EHPersonalities from Analysis to IR (NFC)

2022-11-23 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz updated this revision to Diff 477433.
sgraenitz added a comment.

clang-format includes and sort clang-formatted-files.txt


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138122

Files:
  clang/docs/tools/clang-formatted-files.txt
  llvm/include/llvm/Analysis/EHPersonalities.h
  llvm/include/llvm/Analysis/MustExecute.h
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/include/llvm/IR/EHPersonalities.h
  llvm/lib/Analysis/CMakeLists.txt
  llvm/lib/Analysis/EHPersonalities.cpp
  llvm/lib/Analysis/ValueTracking.cpp
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/DwarfEHPrepare.cpp
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/MachineVerifier.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
  llvm/lib/CodeGen/StackProtector.cpp
  llvm/lib/CodeGen/WinEHPrepare.cpp
  llvm/lib/IR/CMakeLists.txt
  llvm/lib/IR/EHPersonalities.cpp
  llvm/lib/Target/M68k/M68kCollapseMOVEMPass.cpp
  llvm/lib/Target/M68k/M68kExpandPseudo.cpp
  llvm/lib/Target/X86/X86ExpandPseudo.cpp
  llvm/lib/Target/X86/X86FrameLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86WinEHState.cpp
  llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
  llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
  llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/ObjCARC/ObjCARC.h
  llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp
  llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
  llvm/lib/Transforms/Utils/EscapeEnumerator.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/lib/Transforms/Utils/Local.cpp
  llvm/utils/gn/secondary/llvm/lib/Analysis/BUILD.gn
  llvm/utils/gn/secondary/llvm/lib/IR/BUILD.gn

Index: llvm/utils/gn/secondary/llvm/lib/IR/BUILD.gn
===
--- llvm/utils/gn/secondary/llvm/lib/IR/BUILD.gn
+++ llvm/utils/gn/secondary/llvm/lib/IR/BUILD.gn
@@ -33,6 +33,7 @@
 "DiagnosticInfo.cpp",
 "DiagnosticPrinter.cpp",
 "Dominators.cpp",
+"EHPersonalities.cpp",
 "FPEnv.cpp",
 "Function.cpp",
 "GCStrategy.cpp",
Index: llvm/utils/gn/secondary/llvm/lib/Analysis/BUILD.gn
===
--- llvm/utils/gn/secondary/llvm/lib/Analysis/BUILD.gn
+++ llvm/utils/gn/secondary/llvm/lib/Analysis/BUILD.gn
@@ -50,7 +50,6 @@
 "DomPrinter.cpp",
 "DomTreeUpdater.cpp",
 "DominanceFrontier.cpp",
-"EHPersonalities.cpp",
 "FunctionPropertiesAnalysis.cpp",
 "GlobalsModRef.cpp",
 "GuardUtils.cpp",
Index: llvm/lib/Transforms/Utils/Local.cpp
===
--- llvm/lib/Transforms/Utils/Local.cpp
+++ llvm/lib/Transforms/Utils/Local.cpp
@@ -27,7 +27,6 @@
 #include "llvm/Analysis/AssumeBundleQueries.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/DomTreeUpdater.h"
-#include "llvm/Analysis/EHPersonalities.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Analysis/MemorySSAUpdater.h"
@@ -49,6 +48,7 @@
 #include "llvm/IR/DebugLoc.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Dominators.h"
+#include "llvm/IR/EHPersonalities.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GetElementPtrTypeIterator.h"
 #include "llvm/IR/GlobalObject.h"
Index: llvm/lib/Transforms/Utils/InlineFunction.cpp
===
--- llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -25,7 +25,6 @@
 #include "llvm/Analysis/BlockFrequencyInfo.h"
 #include "llvm/Analysis/CallGraph.h"
 #include "llvm/Analysis/CaptureTracking.h"
-#include "llvm/Analysis/EHPersonalities.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/MemoryProfileInfo.h"
 #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
@@ -44,6 +43,7 @@
 #include "llvm/IR/DebugLoc.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Dominators.h"
+#include "llvm/IR/EHPersonalities.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
Index: llvm/lib/Transforms/Utils/EscapeEnumerator.cpp
===
--- llvm/lib/Transforms/Utils/EscapeEnumerator.cpp
+++ llvm/lib/Transforms/Utils/EscapeEnumerator.cpp
@@ -13,7 +13,7 @@
 
 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/Analysis/EHPersonalities.h"
+#include "llvm/IR/EHPersonalities.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Transforms/Utils/Local.h"
 
Index: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
===
--- llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ llvm

[PATCH] D138539: Use std::nullopt_t instead of NoneType (NFC)

2022-11-23 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a reviewer: DavidSpickett.
DavidSpickett added a comment.

lldb parts LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138539

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


[PATCH] D138505: [clangd] Don't run slow clang-tidy checks

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:487
+  }
+  CTFactories = std::move(FastFactories);
+}

njames93 wrote:
> Not exactly related but surely both check factories could be made into static 
> variables and then just choose the factory based on the config.
`createChecks` is nonconst, so this requires some fast-and-loose assumptions 
about nonconst operations being threadsafe.

(In principle you're right, but I think this is mostly an argument that 
ClangTidyCheckFactories and its adjacent APIs could be improved, which isn't 
something I can get sidetracked by at the moment)



Comment at: clang-tools-extra/clangd/tool/Check.cpp:468
+  // is counterproductive! 
+  if (CheckTidyTime.getNumOccurrences())
+F.Diagnostics.ClangTidy.SlowChecks = true;

njames93 wrote:
> How about changing this provide to always enable slow checks, but only use 
> the provider if the flag is passed?
This doesn't seem like it would simplify the code, but it does mean that if 
--check wants to override other config options then we'd need to add a second 
provider.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138505

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


[PATCH] D138505: [clangd] Don't run slow clang-tidy checks

2022-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

i can't think of a proper way to test this out either. unless we somehow let 
slow-tidy-check list to be configurable, so probably fine to make sure it works 
locally and hope that new people introducing tidy checks do complain.




Comment at: clang-tools-extra/clangd/ConfigCompile.cpp:518
+
+if (F.SlowChecks.has_value())
+  Out.Apply.push_back([V = **F.SlowChecks](const Params &, Config &C) {

nit: drop `has_value`?



Comment at: clang-tools-extra/clangd/TidyProvider.cpp:286
 
 bool isRegisteredTidyCheck(llvm::StringRef Check) {
   assert(!Check.empty());

should we update callers here to also emit a warning when they're turning on a 
slow check (and possibly mention SlowChecks override?) this might as well be 
our way of testing this to some extent. we'd still rely on a certain check-name 
always being part of the list (and pick a new element whenever we're updating 
the list), but at least we wouldn't rely on semantics of the check (i.e. also 
have a test case that'd trigger the warning).



Comment at: clang-tools-extra/clangd/tool/Check.cpp:468
+  // is counterproductive! 
+  if (CheckTidyTime.getNumOccurrences())
+F.Diagnostics.ClangTidy.SlowChecks = true;

sammccall wrote:
> njames93 wrote:
> > How about changing this provide to always enable slow checks, but only use 
> > the provider if the flag is passed?
> This doesn't seem like it would simplify the code, but it does mean that if 
> --check wants to override other config options then we'd need to add a second 
> provider.
i think it's better to always have the provider, in case we decide to override 
more options later on (it'd be nice if we didn't come up with a new provider 
for every option we override). but seems fine either way for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138505

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


[PATCH] D135750: [clang][Interp] Track initialization state of local variables

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked 10 inline comments as done.
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Descriptor.h:141-145
   unsigned getAllocSize() const { return AllocSize; }
   /// returns the size of an element when the structure is viewed as an array.
   unsigned getElemSize()  const { return ElemSize; }
+  /// Returns the size of the metadata.
+  unsigned getMetadataSize() const { return MDSize; }

aaron.ballman wrote:
> There's some interface awkwardness here where these values are of type 
> `InterpSize` but the interface returns `unsigned`
Yes. `InterpSize` is also only really used in `Descriptor.h`. No idea why.



Comment at: clang/lib/AST/Interp/Descriptor.h:74
+  };
+  static constexpr MetadataSize NoMetadata = MetadataSize{0};
+

aaron.ballman wrote:
> aaron.ballman wrote:
> > tbaeder wrote:
> > > tbaeder wrote:
> > > > shafik wrote:
> > > > > erichkeane wrote:
> > > > > > add a line: 
> > > > > > `static constexpr MetadataSize InlineDescriptor = 
> > > > > > MetadataSize{sizeof(InlineDescriptor)};` 
> > > > > > and you can use this instead of depending on 'sizeof' all over the 
> > > > > > place.
> > > > > It feels weird to call this `NoMetadata` but we will pass this as an 
> > > > > argument to a function with a parameter of `MetaDataSize`. So I am 
> > > > > expecting a size but I am getting no meta data instead and it looks 
> > > > > like a mistake. 
> > > > > 
> > > > > Maybe a better name would be `ZeroMetaDataSize`?
> > > > I kinda get what your point is, but I don't think this is confusing.
> > > I'm a bit concerned about the naming here; `InlineDescriptor` is already 
> > > a type name, but calling it `MetadataSizeInlineDesc` is pretty long and 
> > > callers already have to prepend a `Descriptor::` to that. :/
> > Rather than using a sentinel value, should we be using `Optional`?
> I'm still wondering if `Optional` is cleaner than `NoMetadata`...
New version uses `Optional`.


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

https://reviews.llvm.org/D135750

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


[PATCH] D135750: [clang][Interp] Track initialization state of local variables

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 477437.

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

https://reviews.llvm.org/D135750

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Descriptor.h
  clang/lib/AST/Interp/EvalEmitter.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpBlock.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/lib/AST/Interp/InterpFrame.h
  clang/lib/AST/Interp/Pointer.cpp
  clang/lib/AST/Interp/Pointer.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h
  clang/test/AST/Interp/cxx20.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/AST/Interp/loops.cpp

Index: clang/test/AST/Interp/loops.cpp
===
--- clang/test/AST/Interp/loops.cpp
+++ clang/test/AST/Interp/loops.cpp
@@ -5,6 +5,7 @@
 
 // ref-no-diagnostics
 // expected-no-diagnostics
+// expected-cpp20-no-diagnostics
 
 namespace WhileLoop {
   constexpr int f() {
@@ -165,8 +166,6 @@
   static_assert(f5(true) == 8, "");
   static_assert(f5(false) == 5, "");
 
-  /// FIXME: This should be accepted in C++20 but is currently being rejected
-  ///   because the variable declaration doesn't have an initializier.
 #if __cplusplus >= 202002L
   constexpr int f6() {
 int i;
@@ -176,7 +175,7 @@
 } while (true);
 return i;
   }
-  static_assert(f6() == 5, ""); // expected-cpp20-error {{not an integral constant}}
+  static_assert(f6() == 5, "");
 #endif
 
 #if 0
Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -407,8 +407,7 @@
 return 1;
   }
   static_assert(uninit(), ""); // ref-error {{not an integral constant expression}} \
-   // ref-note {{in call to 'uninit()'}} \
-   // expected-error {{not an integral constant expression}}
+   // ref-note {{in call to 'uninit()'}}
 
   constexpr int OverFlow() { // ref-error {{never produces a constant expression}}
 int a = INT_MAX;
Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -56,33 +56,27 @@
 }
 static_assert(pointerAssign2() == 12, "");
 
-
 constexpr int unInitLocal() {
   int a;
-  return a; // ref-note{{read of uninitialized object}}
+  return a; // ref-note {{read of uninitialized object}} \
+// expected-note {{read of object outside its lifetime}}
+// FIXME: ^^^ Wrong diagnostic.
 }
-static_assert(unInitLocal() == 0, ""); // expected-error {{not an integral constant expression}} \
-   // ref-error {{not an integral constant expression}} \
-   // ref-note {{in call to 'unInitLocal()'}}
-
-/// TODO: The example above is correctly rejected by the new constexpr
-///   interpreter, but for the wrong reasons. We don't reject it because
-///   it is an uninitialized read, we reject it simply because
-///   the local variable does not have an initializer.
-///
-///   The code below should be accepted but is also being rejected
-///   right now.
-#if 0
+static_assert(unInitLocal() == 0, ""); // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to 'unInitLocal()'}} \
+   // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to 'unInitLocal()'}} \
+
 constexpr int initializedLocal() {
   int a;
-  int b;
-
   a = 20;
   return a;
 }
 static_assert(initializedLocal() == 20);
 
-/// Similar here, but the uninitialized local is passed as a function parameter.
+#if 0
+// FIXME: This code should be rejected because we pass an uninitialized value
+//   as a function parameter.
 constexpr int inc(int a) { return a + 1; }
 constexpr int f() {
 int i;
Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -113,14 +113,15 @@
 
   /// Creates a descriptor for a primitive type.
   Descriptor *createDescriptor(const DeclTy &D, PrimType Type,
-   bool IsConst = false,
-   bool IsTemporary = false,
+   Descriptor::MetadataSize MDSize = {0},
+   bool IsConst = false, bool IsTemporary = false,
bool IsMutable = false) {
-return allocateDescriptor(D, Type, IsConst, IsTemporary, IsMutable);
+return allocateDescriptor(D, Type, MDSize, IsConst, IsTemporary, IsM

[PATCH] D138505: [clangd] Don't run slow clang-tidy checks

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall planned changes to this revision.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/ConfigCompile.cpp:518
+
+if (F.SlowChecks.has_value())
+  Out.Apply.push_back([V = **F.SlowChecks](const Params &, Config &C) {

kadircet wrote:
> nit: drop `has_value`?
This is a boolean, so there's an obvious+wrong interpretation of that version.
I think `has_value`, uh, has value here.



Comment at: clang-tools-extra/clangd/TidyProvider.cpp:286
 
 bool isRegisteredTidyCheck(llvm::StringRef Check) {
   assert(!Check.empty());

kadircet wrote:
> should we update callers here to also emit a warning when they're turning on 
> a slow check (and possibly mention SlowChecks override?) this might as well 
> be our way of testing this to some extent. we'd still rely on a certain 
> check-name always being part of the list (and pick a new element whenever 
> we're updating the list), but at least we wouldn't rely on semantics of the 
> check (i.e. also have a test case that'd trigger the warning).
Callers here == diagnostics for config files that name unknown checks.
I can add a warning for naming a slow check too, that makes sense.

> this might as well be our way of testing this to some extent

Yeah, `ASSERT_FALSE(isFastCheck("misc-const-completeness"))` and a 
corresponding positive case has some value even if we have to trivially update 
it sometimes.

I'm less sure about setting up a complicated end-to-end case that we'll have to 
rewrite/delete if the list changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138505

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


[PATCH] D138559: Record macro references in #ifdef clause.

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Records macro references in #ifdef clauses as ambiguous.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138559

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 
//===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,27 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesIfDefMacroRefs) {
+  llvm::Annotations MainFile(R"cpp(
+#define X 1
+#ifdef $def^X
+ #define Y 2
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  auto AST = build();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  SourceManager &SM = AST.sourceManager();
+  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), 
MainFile.point("def"));
+
+  SymbolReference XRef = Recorded.MacroReferences.front();
+  EXPECT_EQ(XRef.RT, RefType::Ambiguous);
+  EXPECT_EQ("X", XRef.Target.macro().Name->getName());
+  EXPECT_EQ(XRef.RefLocation, Def);
+}
+
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -53,7 +53,7 @@
 SourceRange Range, const MacroArgs *Args) override {
 if (!Active)
   return;
-recordMacroRef(MacroName, *MD.getMacroInfo());
+recordMacroRef(MacroName, *MD.getMacroInfo(), RefType::Explicit);
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override 
{
@@ -71,7 +71,7 @@
   llvm::is_contained(MI->params(), II))
 continue;
   if (const MacroInfo *MI = PP.getMacroInfo(II))
-recordMacroRef(Tok, *MI);
+recordMacroRef(Tok, *MI, RefType::Explicit);
 }
   }
 
@@ -80,17 +80,25 @@
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
-  recordMacroRef(MacroName, *MI);
+  recordMacroRef(MacroName, *MI, RefType::Explicit);
+  }
+
+  void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
+ const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
   }
 
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
 Recorded.MacroReferences.push_back(
 SymbolReference{Tok.getLocation(),
 Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RefType::Explicit});
+RT});
   }
 
   bool Active = false;


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 //===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,27 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesIfDefMacroRefs) {
+  llvm::Annotations MainFile(R"cpp(
+#define X 1
+#ifdef $def^X
+ #define Y 2

[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 477443.
sammccall added a comment.

Script reads/writes from file rather than redirecting output.
Update .inc file to show "no-op" changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138491

Files:
  clang-tools-extra/clangd/TidyFastChecks.inc
  clang-tools-extra/clangd/TidyFastChecks.py
  clang-tools-extra/clangd/tool/Check.cpp

Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -241,6 +241,9 @@
 elog("-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
 return false;
   }
+  #ifndef NDEBUG
+  elog("Timing clang-tidy checks in asserts-mode is not representative!");
+  #endif
   checkTidyTimes();
 }
 
Index: clang-tools-extra/clangd/TidyFastChecks.py
===
--- /dev/null
+++ clang-tools-extra/clangd/TidyFastChecks.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+#
+# Determines which clang-tidy checks are "fast enough" to run in clangd.
+# This runs clangd --check --check-tidy-time and parses the output.
+# This program outputs a header fragment specifying which checks are fast:
+#   FAST(bugprone-argument-comment, 5)
+#   SLOW(misc-const-correctness, 200)
+# If given the old header fragment as input, we lean to preserve its choices.
+#
+# This is not deterministic or hermetic, but should be run occasionally to
+# update the list of allowed checks. From llvm-project:
+#   clang-tools-extra/clangd/TidyFastChecks.py --clangd=build-opt/bin/clangd
+# Be sure to use an optimized, no-asserts, tidy-enabled build of clangd!
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+
+# Checks faster than FAST_THRESHOLD are fast, slower than SLOW_THRESHOLD slow.
+# If a check is in between, we stick with our previous decision. This avoids
+# enabling/disabling checks between releases due to random measurement jitter.
+FAST_THRESHOLD = 8 # percent
+SLOW_THRESHOLD = 15
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--target', help='X-macro output file. '
+'If it exists, existing contents will be used for hysteresis',
+default='clang-tools-extra/clangd/TidyFastChecks.inc')
+parser.add_argument('--source', help='Source file to benchmark tidy checks',
+default='clang/lib/Sema/Sema.cpp')
+parser.add_argument('--clangd', help='clangd binary to invoke',
+default='build/bin/clangd')
+parser.add_argument('--checks', help='check glob to run', default='*')
+parser.add_argument('--verbose', help='log clangd output', action='store_true')
+args = parser.parse_args()
+
+# Use the preprocessor to extract the list of previously-fast checks.
+def read_old_fast(path):
+text = subprocess.check_output(["cpp",
+"-P",# Omit GNU line markers
+"-nostdinc", # Don't include stdc-predef.h
+"-DFAST(C,T)=C", # Print fast checks only
+path])
+for line in text.splitlines():
+if line.strip():
+yield line.strip().decode('utf-8')
+old_fast = list(read_old_fast(args.target)) if os.path.exists(args.target) else []
+print(f"Old fast checks: {old_fast}", file=sys.stderr)
+
+# Runs clangd --check --check-tidy-time.
+# Yields (check, percent-overhead) pairs.
+def measure():
+process = subprocess.Popen([args.clangd,
+"--check=" + args.source,
+"--check-locations=0", # Skip useless slow steps.
+"--check-tidy-time=" + args.checks],
+stderr=subprocess.PIPE)
+recording = False
+for line in iter(process.stderr.readline, b""):
+if args.verbose:
+print("clangd> ", line, file=sys.stderr)
+if not recording:
+if b'Timing AST build with individual clang-tidy checks' in line:  
+   recording = True
+continue
+if b'Finished individual clang-tidy checks' in line:
+return
+match = re.search(rb'(\S+) = (\S+)%', line)
+if match:
+yield (match.group(1).decode('utf-8'), float(match.group(2)))
+
+with open(args.target, 'w', buffering=1) as target:
+# Produce an includable X-macros fragment with our decisions.
+print(f"""// This file is generated, do not edit it directly!
+// Deltas are percentage regression in parsing {args.source}
+#ifndef FAST
+#define FAST(CHECK, DELTA)
+#endif
+#ifndef SLOW
+#define SLOW(CHECK, DELTA)
+#endif
+""", file=target)
+
+for check, time in measure():
+threshold = SLOW_THRESHOLD if check in old_fast else FAST_THRESHOLD
+decision = "FAST" if time <= threshold else "SLOW"
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})", file=target)
+
+print("""
+#undef FAST
+#undef SLOW
+""", file=target

[PATCH] D137149: Use PassGate from LLVMContext if any otherwise global one

2022-11-23 Thread Evgeniy via Phabricator via cfe-commits
ebrevnov updated this revision to Diff 477446.
ebrevnov marked an inline comment as done.
ebrevnov added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Updated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137149

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  llvm/include/llvm/IR/OptBisect.h
  llvm/include/llvm/Passes/StandardInstrumentations.h
  llvm/lib/Analysis/CallGraphSCCPass.cpp
  llvm/lib/Analysis/LoopPass.cpp
  llvm/lib/Analysis/RegionPass.cpp
  llvm/lib/IR/LLVMContextImpl.cpp
  llvm/lib/IR/OptBisect.cpp
  llvm/lib/IR/Pass.cpp
  llvm/lib/LTO/LTOBackend.cpp
  llvm/lib/LTO/ThinLTOCodeGenerator.cpp
  llvm/lib/Passes/PassBuilderBindings.cpp
  llvm/lib/Passes/StandardInstrumentations.cpp
  llvm/tools/opt/NewPMDriver.cpp
  llvm/unittests/IR/LegacyPassManagerTest.cpp
  llvm/unittests/IR/PassManagerTest.cpp

Index: llvm/unittests/IR/PassManagerTest.cpp
===
--- llvm/unittests/IR/PassManagerTest.cpp
+++ llvm/unittests/IR/PassManagerTest.cpp
@@ -826,7 +826,7 @@
   FunctionAnalysisManager FAM;
   FunctionPassManager FPM;
   PassInstrumentationCallbacks PIC;
-  StandardInstrumentations SI(/*DebugLogging*/ true);
+  StandardInstrumentations SI(M->getContext(), /*DebugLogging*/ true);
   SI.registerCallbacks(PIC, &FAM);
   FAM.registerPass([&] { return PassInstrumentationAnalysis(&PIC); });
   FAM.registerPass([&] { return DominatorTreeAnalysis(); });
@@ -872,7 +872,7 @@
   FunctionAnalysisManager FAM;
   FunctionPassManager FPM;
   PassInstrumentationCallbacks PIC;
-  StandardInstrumentations SI(/*DebugLogging*/ true);
+  StandardInstrumentations SI(M->getContext(), /*DebugLogging*/ true);
   SI.registerCallbacks(PIC, &FAM);
   FAM.registerPass([&] { return PassInstrumentationAnalysis(&PIC); });
   FAM.registerPass([&] { return DominatorTreeAnalysis(); });
@@ -937,7 +937,7 @@
   FunctionAnalysisManager FAM;
   FunctionPassManager FPM;
   PassInstrumentationCallbacks PIC;
-  StandardInstrumentations SI(/*DebugLogging*/ true);
+  StandardInstrumentations SI(M->getContext(), /*DebugLogging*/ true);
   SI.registerCallbacks(PIC, &FAM);
   FAM.registerPass([&] { return PassInstrumentationAnalysis(&PIC); });
   FAM.registerPass([&] { return DominatorTreeAnalysis(); });
Index: llvm/unittests/IR/LegacyPassManagerTest.cpp
===
--- llvm/unittests/IR/LegacyPassManagerTest.cpp
+++ llvm/unittests/IR/LegacyPassManagerTest.cpp
@@ -359,10 +359,8 @@
 struct CustomOptPassGate : public OptPassGate {
   bool Skip;
   CustomOptPassGate(bool Skip) : Skip(Skip) { }
-  bool shouldRunPass(const Pass *P, StringRef IRDescription) override {
-if (P->getPassKind() == PT_Module)
-  return !Skip;
-return OptPassGate::shouldRunPass(P, IRDescription);
+  bool shouldRunPass(const StringRef PassName, StringRef IRDescription) override {
+return !Skip;
   }
   bool isEnabled() const override { return true; }
 };
Index: llvm/tools/opt/NewPMDriver.cpp
===
--- llvm/tools/opt/NewPMDriver.cpp
+++ llvm/tools/opt/NewPMDriver.cpp
@@ -354,8 +354,8 @@
   PrintPassOptions PrintPassOpts;
   PrintPassOpts.Verbose = DebugPM == DebugLogging::Verbose;
   PrintPassOpts.SkipAnalyses = DebugPM == DebugLogging::Quiet;
-  StandardInstrumentations SI(DebugPM != DebugLogging::None, VerifyEachPass,
-  PrintPassOpts);
+  StandardInstrumentations SI(M.getContext(), DebugPM != DebugLogging::None,
+  VerifyEachPass, PrintPassOpts);
   SI.registerCallbacks(PIC, &FAM);
   DebugifyEachInstrumentation Debugify;
   DebugifyStatsMap DIStatsMap;
Index: llvm/lib/Passes/StandardInstrumentations.cpp
===
--- llvm/lib/Passes/StandardInstrumentations.cpp
+++ llvm/lib/Passes/StandardInstrumentations.cpp
@@ -766,27 +766,35 @@
   return ShouldRun;
 }
 
-void OptBisectInstrumentation::registerCallbacks(
+bool OptPassGateInstrumentation::shouldRun(StringRef PassName, Any IR) {
+  if (isIgnored(PassName))
+return true;
+
+  bool ShouldRun =
+  Context.getOptPassGate().shouldRunPass(PassName, getIRName(IR));
+  if (!ShouldRun && !this->HasWrittenIR && !OptBisectPrintIRPath.empty()) {
+// FIXME: print IR if limit is higher than number of opt-bisect
+// invocations
+this->HasWrittenIR = true;
+const Module *M = unwrapModule(IR, /*Force=*/true);
+assert((M && &M->getContext() == &Context) && "Missing/Mismatching Module");
+std::error_code EC;
+raw_fd_ostream OS(OptBisectPrintIRPath, EC);
+if (EC)
+  report_fatal_error(errorCodeToError(EC));
+M->print(OS, nullptr);
+  }
+  return ShouldRun;
+}
+
+void OptPassGateInstrumentation::registerCallbacks(
 PassInstrume

[PATCH] D138157: Make -fsanitize=scudo use scudo_standalone. Delete check-scudo.

2022-11-23 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

We (Linaro) also have an issue with a bot that uses 
`-DCOMPILER_RT_BUILD_SANITIZERS=OFF`.

https://lab.llvm.org/buildbot/#/builders/178/builds/3318

  CMake Error at cmake/modules/AddLLVM.cmake:1915 (add_dependencies):
The dependency target "ScudoUnitTests" of target "check-all" does not
exist.
  Call Stack (most recent call first):
cmake/modules/AddLLVM.cmake:1955 (add_lit_target)
CMakeLists.txt:1249 (umbrella_lit_testsuite_end)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138157

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


[clang] 5cfc22c - Revert "[SROA] `isVectorPromotionViable()`: memory intrinsics operate on vectors of bytes"

2022-11-23 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2022-11-23T13:11:16+01:00
New Revision: 5cfc22cafe3f2465e0bb324f8daba82ffcabd0df

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

LOG: Revert "[SROA] `isVectorPromotionViable()`: memory intrinsics operate on 
vectors of bytes"

This reverts commit cf624b23bc5d5a6161706d1663def49380ff816a. It
triggers crashes in clang, see the comments on github on the original
change.

Added: 


Modified: 
clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
llvm/lib/Transforms/Scalar/SROA.cpp
llvm/test/CodeGen/AMDGPU/v1024.ll
llvm/test/DebugInfo/X86/sroasplit-1.ll
llvm/test/DebugInfo/X86/sroasplit-4.ll
llvm/test/Transforms/PhaseOrdering/instcombine-sroa-inttoptr.ll
llvm/test/Transforms/SROA/address-spaces.ll
llvm/test/Transforms/SROA/alignment.ll
llvm/test/Transforms/SROA/alloca-address-space.ll
llvm/test/Transforms/SROA/basictest.ll
llvm/test/Transforms/SROA/pointer-offset-size.ll
llvm/test/Transforms/SROA/scalable-vectors.ll
llvm/test/Transforms/SROA/slice-width.ll
llvm/test/Transforms/SROA/sroa-common-type-fail-promotion.ll
llvm/test/Transforms/SROA/tbaa-struct.ll
llvm/test/Transforms/SROA/tbaa-struct2.ll
llvm/test/Transforms/SROA/vector-promotion.ll

Removed: 




diff  --git a/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl 
b/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
index 859e81f08d6bd..65f6f2e7d8c24 100644
--- a/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
+++ b/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
@@ -515,17 +515,13 @@ typedef struct {
   private char *p;
 } StructTy3;
 
-// CHECK-LABEL: @test_memset_private(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = bitcast [[STRUCT_STRUCTTY3:%.*]] 
addrspace(5)* [[PTR:%.*]] to i8 addrspace(5)*
-// CHECK-NEXT:[[S3_SROA_0_SROA_0_0_S3_SROA_0_0__SROA_CAST2_SROA_CAST:%.*]] 
= bitcast [[STRUCT_STRUCTTY3]] addrspace(5)* [[PTR]] to <32 x i8> addrspace(5)*
-// CHECK-NEXT:store <32 x i8> zeroinitializer, <32 x i8> addrspace(5)* 
[[S3_SROA_0_SROA_0_0_S3_SROA_0_0__SROA_CAST2_SROA_CAST]], align 8, !tbaa.struct 
!9
-// CHECK-NEXT:[[S3_SROA_4_0__SROA_IDX6:%.*]] = getelementptr inbounds 
[[STRUCT_STRUCTTY3]], [[STRUCT_STRUCTTY3]] addrspace(5)* [[PTR]], i32 0, i32 4
-// CHECK-NEXT:store i8 addrspace(5)* addrspacecast (i8* null to i8 
addrspace(5)*), i8 addrspace(5)* addrspace(5)* [[S3_SROA_4_0__SROA_IDX6]], 
align 8, !tbaa.struct !12
-// CHECK-NEXT:[[S3_SROA_5_0__SROA_IDX:%.*]] = getelementptr inbounds i8, 
i8 addrspace(5)* [[TMP0]], i32 36
-// CHECK-NEXT:[[S3_SROA_5_0__SROA_CAST8:%.*]] = bitcast i8 addrspace(5)* 
[[S3_SROA_5_0__SROA_IDX]] to i32 addrspace(5)*
-// CHECK-NEXT:store i32 0, i32 addrspace(5)* [[S3_SROA_5_0__SROA_CAST8]], 
align 4, !tbaa.struct !13
-// CHECK-NEXT:ret void
+// CHECK-LABEL: test_memset_private
+// CHECK: call void @llvm.memset.p5i8.i64(i8 addrspace(5)* noundef align 8 
{{.*}}, i8 0, i64 32, i1 false)
+// CHECK: [[GEP:%.*]] = getelementptr inbounds %struct.StructTy3, 
%struct.StructTy3 addrspace(5)* %ptr, i32 0, i32 4
+// CHECK: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), 
i8 addrspace(5)* addrspace(5)* [[GEP]]
+// CHECK: [[GEP1:%.*]] = getelementptr inbounds i8, i8 addrspace(5)* {{.*}}, 
i32 36
+// CHECK: [[GEP1_CAST:%.*]] = bitcast i8 addrspace(5)* [[GEP1]] to i32 
addrspace(5)*
+// CHECK: store i32 0, i32 addrspace(5)* [[GEP1_CAST]], align 4
 void test_memset_private(private StructTy3 *ptr) {
   StructTy3 S3 = {0, 0, 0, 0, 0};
   *ptr = S3;

diff  --git a/llvm/lib/Transforms/Scalar/SROA.cpp 
b/llvm/lib/Transforms/Scalar/SROA.cpp
index 09a445c236fa7..6dcdd630b6bae 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -1806,10 +1806,8 @@ static bool isVectorPromotionViableForSlice(Partition 
&P, const Slice &S,
   ? Ty->getElementType()
   : FixedVectorType::get(Ty->getElementType(), 
NumElements);
 
-  Type *SplitIntTy = nullptr;
-  if (uint64_t Bitwidth = NumElements * ElementSize * 8;
-  Bitwidth <= IntegerType::MAX_INT_BITS)
-SplitIntTy = Type::getIntNTy(Ty->getContext(), Bitwidth);
+  Type *SplitIntTy =
+  Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
 
   Use *U = S.getUse();
 
@@ -1828,8 +1826,7 @@ static bool isVectorPromotionViableForSlice(Partition &P, 
const Slice &S,
 // Disable vector promotion when there are loads or stores of an FCA.
 if (LTy->isStructTy())
   return false;
-if (SplitIntTy &&
-(P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset())) {
+if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
   assert(LTy->isIntegerTy());
   LTy = SplitIntTy;
 }
@@ -1842,8 +1839,7 @@ static 

[PATCH] D137386: [clang][Interp] Reject invalid declarations and expressions

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


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

https://reviews.llvm.org/D137386

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


[PATCH] D137399: [clang][Interp] Emit negated integers directly as constants

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder abandoned this revision.
tbaeder added a comment.

This was just to make the byte code a little more readable, but given the 
amount of pending patches I already have, I'll abandon this and maybe revisit 
at a later point, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137399

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


[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2022-11-23 Thread Tao Liang via Phabricator via cfe-commits
Origami404 updated this revision to Diff 477453.
Origami404 added a comment.

Change implements according reviews.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137043

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/Inputs/stdc-predef/usr/include/stdc-predef.h
  clang/test/Driver/stdc-predef.c
  clang/test/Driver/stdc-predef.i

Index: clang/test/Driver/stdc-predef.i
===
--- /dev/null
+++ clang/test/Driver/stdc-predef.i
@@ -0,0 +1,9 @@
+// The automatic preinclude of stdc-predef.h should not occur if
+// the source filename indicates a preprocessed file.
+//
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: | FileCheck --implicit-check-not "stdc-predef.h" %s
+
+int i;
Index: clang/test/Driver/stdc-predef.c
===
--- /dev/null
+++ clang/test/Driver/stdc-predef.c
@@ -0,0 +1,61 @@
+// Test that clang preincludes stdc-predef.h, if we are using libc that does not
+// pre-include it, e.g. Musl
+
+// Musl-based system need this addition include.
+//
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: | FileCheck -check-prefix CHECK-CPP-FLAG %s
+
+// Gnu-based system does not need this addition include.
+//
+// RUN: %clang %s -### -c -ffreestanding 2>&1 \
+// RUN: -target x86_64-unknown-linux-gnu \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: | FileCheck --implicit-check-not "stdc-predef.h" %s
+
+// Standalone system does not need this addition include.
+//
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: -target x86_64-unknown-linux-musl -ffreestanding \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: | FileCheck --implicit-check-not "stdc-predef.h" %s
+
+// Because this behavior is implemented by adding preprocessor flags in the 
+// driver, so if we disabled preprocess, the include flag should not appear.
+//
+// RUN: %clang -x cpp-output %s -### -c 2>&1 \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: | FileCheck --implicit-check-not "stdc-predef.h" %s
+
+// This behavior should appear in all languages that use the c preprocessor,
+// including C, C++ and Objective-C, as long as the system uses musl.
+//
+// RUN: %clang -x objective-c %s -### -c 2>&1 \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: --sysroot=%S/Inputs/stdc-predef \
+// RUN: | FileCheck -check-prefix CHECK-CPP-FLAG %s
+
+// If a musl-based system does not have this header, give an error at line 1.
+//
+// RUN: %clang %s -c -Xclang -verify=expected 2>&1 \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree 
+// expected-error@1 {{'stdc-predef.h' file not found}}
+
+// Check if the file is really included by macro.
+//
+// RUN: %clang %s -c -Xclang -verify=ok -DCHECK_DUMMY=1 \
+// RUN: -target x86_64-unknown-linux-musl \
+// RUN: --sysroot=%S/Inputs/stdc-predef 
+// ok-no-diagnostics
+
+// CHECK-CPP-FLAG: "-include" "stdc-predef.h"
+int i;
+#if CHECK_DUMMY
+#if !DUMMY_STDC_PREDEF 
+  #error "Expected macro symbol DUMMY_STDC_PREDEF is not defined."
+#endif
+#endif
Index: clang/test/Driver/Inputs/stdc-predef/usr/include/stdc-predef.h
===
--- /dev/null
+++ clang/test/Driver/Inputs/stdc-predef/usr/include/stdc-predef.h
@@ -0,0 +1,4 @@
+#ifndef	_STDC_PREDEF_H
+#define	_STDC_PREDEF_H	1
+#define DUMMY_STDC_PREDEF 1
+#endif
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -636,6 +636,12 @@
 
   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
 addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
+
+  // add implict include for musl-based non-free-standing system
+  if (!DriverArgs.hasArg(options::OPT_ffreestanding) && getTriple().isMusl()) {
+CC1Args.push_back("-include");
+CC1Args.push_back("stdc-predef.h");
+  }
 }
 
 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -398,6 +398,8 @@
   PCH or modules. When Clang hits this limit, it now produces notes mentioning
   which header and source files are consuming large amounts of this space.
   ``#pragma clang __debug sloc_usage`` can also be used to request this report.
+- Clang will implicitly add ``#include "stdc-predef.h"`` on musl-based system 
+  likes GCC.
 
 Non-comprehensive list of changes in this release
 

[PATCH] D138564: Format changes with clang-format

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138564

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -232,7 +232,8 @@
   ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
 
   SourceManager &SM = AST.sourceManager();
-  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), 
MainFile.point("def"));
+  SourceLocation Def =
+  SM.getComposedLoc(SM.getMainFileID(), MainFile.point("def"));
 
   SymbolReference XRef = Recorded.MacroReferences.front();
   EXPECT_EQ(XRef.RT, RefType::Ambiguous);
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -84,7 +84,7 @@
   }
 
   void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
- const MacroDefinition &MD) override {
+ const MacroDefinition &MD) override {
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
@@ -95,10 +95,9 @@
   void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
-Recorded.MacroReferences.push_back(
-SymbolReference{Tok.getLocation(),
-Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RT});
+Recorded.MacroReferences.push_back(SymbolReference{
+Tok.getLocation(),
+Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()}, RT});
   }
 
   bool Active = false;


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -232,7 +232,8 @@
   ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
 
   SourceManager &SM = AST.sourceManager();
-  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), MainFile.point("def"));
+  SourceLocation Def =
+  SM.getComposedLoc(SM.getMainFileID(), MainFile.point("def"));
 
   SymbolReference XRef = Recorded.MacroReferences.front();
   EXPECT_EQ(XRef.RT, RefType::Ambiguous);
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -84,7 +84,7 @@
   }
 
   void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
- const MacroDefinition &MD) override {
+ const MacroDefinition &MD) override {
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
@@ -95,10 +95,9 @@
   void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
-Recorded.MacroReferences.push_back(
-SymbolReference{Tok.getLocation(),
-Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RT});
+Recorded.MacroReferences.push_back(SymbolReference{
+Tok.getLocation(),
+Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()}, RT});
   }
 
   bool Active = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138566: [clang-tidy][NFC] Make CheckFactories::CreateChecks* const

2022-11-23 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2, JonasToth.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
njames93 requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

There's no reason for these methods to be non-const.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138566

Files:
  clang-tools-extra/clang-tidy/ClangTidyModule.cpp
  clang-tools-extra/clang-tidy/ClangTidyModule.h


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -65,11 +65,11 @@
 
   /// Create instances of checks that are enabled.
   std::vector>
-  createChecks(ClangTidyContext *Context);
+  createChecks(ClangTidyContext *Context) const;
 
   /// Create instances of checks that are enabled for the current Language.
   std::vector>
-  createChecksForLanguage(ClangTidyContext *Context);
+  createChecksForLanguage(ClangTidyContext *Context) const;
 
   typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -22,7 +22,7 @@
 }
 
 std::vector>
-ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
+ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) const {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
 if (Context->isCheckEnabled(Factory.getKey()))
@@ -32,7 +32,8 @@
 }
 
 std::vector>
-ClangTidyCheckFactories::createChecksForLanguage(ClangTidyContext *Context) {
+ClangTidyCheckFactories::createChecksForLanguage(
+ClangTidyContext *Context) const {
   std::vector> Checks;
   const LangOptions &LO = Context->getLangOpts();
   for (const auto &Factory : Factories) {


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -65,11 +65,11 @@
 
   /// Create instances of checks that are enabled.
   std::vector>
-  createChecks(ClangTidyContext *Context);
+  createChecks(ClangTidyContext *Context) const;
 
   /// Create instances of checks that are enabled for the current Language.
   std::vector>
-  createChecksForLanguage(ClangTidyContext *Context);
+  createChecksForLanguage(ClangTidyContext *Context) const;
 
   typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -22,7 +22,7 @@
 }
 
 std::vector>
-ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
+ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) const {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
 if (Context->isCheckEnabled(Factory.getKey()))
@@ -32,7 +32,8 @@
 }
 
 std::vector>
-ClangTidyCheckFactories::createChecksForLanguage(ClangTidyContext *Context) {
+ClangTidyCheckFactories::createChecksForLanguage(
+ClangTidyContext *Context) const {
   std::vector> Checks;
   const LangOptions &LO = Context->getLangOpts();
   for (const auto &Factory : Factories) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 19ab2a6 - [include-cleaner] Show includes matched by refs in HTML report.

2022-11-23 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-11-23T13:41:24+01:00
New Revision: 19ab2a671eb32bede5a0bf686aebf3c6838848e3

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

LOG: [include-cleaner] Show includes matched by refs in HTML report.

Demo: 
https://htmlpreview.github.io/?https://gist.githubusercontent.com/sam-mccall/ecee6869e37af3db28089b64d8dce806/raw/8736e64c45af411e2c2d72adaed2dfc4410a5b36/ASTTests.html%25202

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h 
b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
index ec378dca6ec70..1b85c679f6a7d 100644
--- a/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
+++ b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
@@ -84,7 +84,8 @@ llvm::SmallVector findHeaders(const SymbolLocation 
&Loc,
   const PragmaIncludes *PI);
 
 /// Write an HTML summary of the analysis to the given stream.
-void writeHTMLReport(FileID File, llvm::ArrayRef Roots,
+void writeHTMLReport(FileID File, const RecordedPP::RecordedIncludes &Includes,
+ llvm::ArrayRef Roots,
  llvm::ArrayRef MacroRefs, ASTContext 
&Ctx,
  PragmaIncludes *PI, llvm::raw_ostream &OS);
 

diff  --git a/clang-tools-extra/include-cleaner/lib/HTMLReport.cpp 
b/clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
index 2b5d67c299550..477fea6e3fc0e 100644
--- a/clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
+++ b/clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
@@ -51,6 +51,7 @@ constexpr llvm::StringLiteral CSS = R"css(
   #hover p, #hover pre { margin: 0; }
   #hover .target.implicit { background-color: #bbb; }
   #hover .target.ambiguous { background-color: #caf; }
+  .missing, .unused { background-color: #faa !important; }
   #hover th { color: #008; text-align: right; padding-right: 0.5em; }
   #hover .target:not(:first-child) {
 margin-top: 1em;
@@ -110,8 +111,10 @@ class Reporter {
   llvm::raw_ostream &OS;
   const ASTContext &Ctx;
   const SourceManager &SM;
+  const RecordedPP::RecordedIncludes &Includes;
   const PragmaIncludes *PI;
-  FileID File;
+  FileID MainFile;
+  const FileEntry *MainFE;
 
   // References to symbols from the main file.
   // FIXME: should we deduplicate these?
@@ -120,6 +123,8 @@ class Reporter {
 RefType Type;
 SmallVector Locations;
 SmallVector Headers;
+SmallVector Includes;
+bool Satisfied = false; // Is the include present?
   };
   std::vector Targets;
   // Points within the main file that reference a Target.
@@ -136,7 +141,7 @@ class Reporter {
   std::vector Refs;
 
   Target makeTarget(const SymbolReference &SR) {
-Target T{SR.Target, SR.RT, {}, {}};
+Target T{SR.Target, SR.RT, {}, {}, {}};
 
 // Duplicates logic from walkUsed(), which doesn't expose SymbolLocations.
 // FIXME: use locateDecl and friends once implemented.
@@ -151,19 +156,35 @@ class Reporter {
 }
 
 for (const auto &Loc : T.Locations)
-  T.Headers = findHeaders(Loc, SM, PI);
+  T.Headers.append(findHeaders(Loc, SM, PI));
+
+for (const auto &H : T.Headers) {
+  T.Includes.append(Includes.match(H));
+  // FIXME: library should signal main-file refs somehow.
+  // Non-physical refs to the main-file should be possible.
+  if (H.kind() == Header::Physical && H.physical() == MainFE)
+T.Satisfied = true;
+}
+if (!T.Includes.empty())
+  T.Satisfied = true;
+// Include pointers are meaningfully ordered as they are backed by a 
vector.
+llvm::sort(T.Includes);
+T.Includes.erase(std::unique(T.Includes.begin(), T.Includes.end()),
+ T.Includes.end());
 
 return T;
   }
 
 public:
-  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx, const PragmaIncludes *PI,
-   FileID File)
-  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), PI(PI), File(File) {}
+  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx,
+   const RecordedPP::RecordedIncludes &Includes,
+   const PragmaIncludes *PI, FileID MainFile)
+  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), Includes(Includes),
+PI(PI), MainFile(MainFile), MainFE(SM.getFileEntryForID(MainFile)) {}
 
   void addRef(const SymbolReference &SR) {
 auto [File, Offset] = SM.getDecomposedLoc(SM.getFileLoc(SR.RefLocation));
-if (File != this->File) {
+if (File != this->MainFile) {
   // Can get here e.g. if there's an #include inside a root Decl.
   // FIXME: do somethin

[PATCH] D138219: [include-cleaner] Show includes matched by refs in HTML report.

2022-11-23 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG19ab2a671eb3: [include-cleaner] Show includes matched by 
refs in HTML report. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D138219?vs=477429&id=477459#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138219

Files:
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Index: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
===
--- clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -71,8 +71,8 @@
<< ": " << EC.message() << "\n";
   exit(1);
 }
-writeHTMLReport(AST.Ctx->getSourceManager().getMainFileID(), AST.Roots,
-PP.MacroReferences, *AST.Ctx, &PI, OS);
+writeHTMLReport(AST.Ctx->getSourceManager().getMainFileID(), PP.Includes,
+AST.Roots, PP.MacroReferences, *AST.Ctx, &PI, OS);
   }
 };
 
Index: clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
===
--- clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
+++ clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
@@ -51,6 +51,7 @@
   #hover p, #hover pre { margin: 0; }
   #hover .target.implicit { background-color: #bbb; }
   #hover .target.ambiguous { background-color: #caf; }
+  .missing, .unused { background-color: #faa !important; }
   #hover th { color: #008; text-align: right; padding-right: 0.5em; }
   #hover .target:not(:first-child) {
 margin-top: 1em;
@@ -110,8 +111,10 @@
   llvm::raw_ostream &OS;
   const ASTContext &Ctx;
   const SourceManager &SM;
+  const RecordedPP::RecordedIncludes &Includes;
   const PragmaIncludes *PI;
-  FileID File;
+  FileID MainFile;
+  const FileEntry *MainFE;
 
   // References to symbols from the main file.
   // FIXME: should we deduplicate these?
@@ -120,6 +123,8 @@
 RefType Type;
 SmallVector Locations;
 SmallVector Headers;
+SmallVector Includes;
+bool Satisfied = false; // Is the include present?
   };
   std::vector Targets;
   // Points within the main file that reference a Target.
@@ -136,7 +141,7 @@
   std::vector Refs;
 
   Target makeTarget(const SymbolReference &SR) {
-Target T{SR.Target, SR.RT, {}, {}};
+Target T{SR.Target, SR.RT, {}, {}, {}};
 
 // Duplicates logic from walkUsed(), which doesn't expose SymbolLocations.
 // FIXME: use locateDecl and friends once implemented.
@@ -151,19 +156,35 @@
 }
 
 for (const auto &Loc : T.Locations)
-  T.Headers = findHeaders(Loc, SM, PI);
+  T.Headers.append(findHeaders(Loc, SM, PI));
+
+for (const auto &H : T.Headers) {
+  T.Includes.append(Includes.match(H));
+  // FIXME: library should signal main-file refs somehow.
+  // Non-physical refs to the main-file should be possible.
+  if (H.kind() == Header::Physical && H.physical() == MainFE)
+T.Satisfied = true;
+}
+if (!T.Includes.empty())
+  T.Satisfied = true;
+// Include pointers are meaningfully ordered as they are backed by a vector.
+llvm::sort(T.Includes);
+T.Includes.erase(std::unique(T.Includes.begin(), T.Includes.end()),
+ T.Includes.end());
 
 return T;
   }
 
 public:
-  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx, const PragmaIncludes *PI,
-   FileID File)
-  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), PI(PI), File(File) {}
+  Reporter(llvm::raw_ostream &OS, ASTContext &Ctx,
+   const RecordedPP::RecordedIncludes &Includes,
+   const PragmaIncludes *PI, FileID MainFile)
+  : OS(OS), Ctx(Ctx), SM(Ctx.getSourceManager()), Includes(Includes),
+PI(PI), MainFile(MainFile), MainFE(SM.getFileEntryForID(MainFile)) {}
 
   void addRef(const SymbolReference &SR) {
 auto [File, Offset] = SM.getDecomposedLoc(SM.getFileLoc(SR.RefLocation));
-if (File != this->File) {
+if (File != this->MainFile) {
   // Can get here e.g. if there's an #include inside a root Decl.
   // FIXME: do something more useful than this.
   llvm::errs() << "Ref location outside file! " << SR.Target << " at "
@@ -289,15 +310,23 @@
   OS << "\n";
 }
 
+for (const auto *I : T.Includes) {
+  OS << "Included";
+  escapeString(I->Spelled);
+  OS << ", line " << I->Line << "";
+  OS << "";
+}
+
 OS << "";
   }
 
   void writeCode() {
 llvm::sort(Refs);
-llvm::StringRef Code = SM.getBufferData(File);
+llvm::StringRef Code = SM.getBufferData(MainFile);
 
 OS << "";
-OS << "";
+OS << "";
+unsigned LineNum = 1;
 auto Rest = llvm::

[PATCH] D138559: Record macro references in #ifdef clause.

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 477461.
VitaNuo added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138559

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 
//===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,27 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesIfDefMacroRefs) {
+  llvm::Annotations MainFile(R"cpp(
+#define X 1
+#ifdef $def^X
+ #define Y 2
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  auto AST = build();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  SourceManager &SM = AST.sourceManager();
+  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), 
MainFile.point("def"));
+
+  SymbolReference XRef = Recorded.MacroReferences.front();
+  EXPECT_EQ(XRef.RT, RefType::Ambiguous);
+  EXPECT_EQ("X", XRef.Target.macro().Name->getName());
+  EXPECT_EQ(XRef.RefLocation, Def);
+}
+
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -53,7 +53,7 @@
 SourceRange Range, const MacroArgs *Args) override {
 if (!Active)
   return;
-recordMacroRef(MacroName, *MD.getMacroInfo());
+recordMacroRef(MacroName, *MD.getMacroInfo(), RefType::Explicit);
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override 
{
@@ -71,7 +71,7 @@
   llvm::is_contained(MI->params(), II))
 continue;
   if (const MacroInfo *MI = PP.getMacroInfo(II))
-recordMacroRef(Tok, *MI);
+recordMacroRef(Tok, *MI, RefType::Explicit);
 }
   }
 
@@ -80,17 +80,25 @@
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
-  recordMacroRef(MacroName, *MI);
+  recordMacroRef(MacroName, *MI, RefType::Explicit);
+  }
+
+  void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
+ const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
   }
 
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
 Recorded.MacroReferences.push_back(
 SymbolReference{Tok.getLocation(),
 Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RefType::Explicit});
+RT});
   }
 
   bool Active = false;


Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 //===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,27 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesIfDefMacroRefs) {
+  llvm::Annotations MainFile(R"cpp(
+#define X 1
+#ifdef $def^X
+ #define Y 2
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  auto AST = build();
+  ASSERT_THAT(

[PATCH] D138157: Make -fsanitize=scudo use scudo_standalone. Delete check-scudo.

2022-11-23 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Chromium is broken too

  CMake Error at 
/b/s/w/ir/cache/builder/src/third_party/llvm/llvm/cmake/modules/AddLLVM.cmake:1915
 (add_dependencies):
The dependency target "ScudoUnitTests" of target "check-runtimes" does not
exist.
  Call Stack (most recent call first):

/b/s/w/ir/cache/builder/src/third_party/llvm/llvm/cmake/modules/AddLLVM.cmake:1955
 (add_lit_target)
CMakeLists.txt:238 (umbrella_lit_testsuite_end)
  
  
  CMake Error at 
/b/s/w/ir/cache/builder/src/third_party/llvm/llvm/cmake/modules/AddLLVM.cmake:1915
 (add_dependencies):
The dependency target "ScudoUnitTests" of target "check-scudo_standalone"
does not exist.
  Call Stack (most recent call first):

/b/s/w/ir/cache/builder/src/third_party/llvm/llvm/cmake/modules/AddLLVM.cmake:1981
 (add_lit_target)

/b/s/w/ir/cache/builder/src/third_party/llvm/compiler-rt/test/scudo/standalone/CMakeLists.txt:15
 (add_lit_testsuite)

from 
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket/8796726895518599345/+/u/package_clang/stdout


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138157

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


[PATCH] D90568: [clang] Add [is|set]Nested methods to NamespaceDecl

2022-11-23 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 477467.
njames93 added a comment.

Hopefully fixed line endings


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90568

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/HLSLExternalSemaSource.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/AST/ast-dump-decl.cpp
  clang/test/AST/ast-dump-namespace-json.cpp
  clang/unittests/Sema/ExternalSemaSourceTest.cpp

Index: clang/unittests/Sema/ExternalSemaSourceTest.cpp
===
--- clang/unittests/Sema/ExternalSemaSourceTest.cpp
+++ clang/unittests/Sema/ExternalSemaSourceTest.cpp
@@ -121,7 +121,7 @@
   CurrentSema->getPreprocessor().getIdentifierInfo(CorrectTo);
   NamespaceDecl *NewNamespace =
   NamespaceDecl::Create(Context, DestContext, false, Typo.getBeginLoc(),
-Typo.getLoc(), ToIdent, nullptr);
+Typo.getLoc(), ToIdent, nullptr, false);
   DestContext->addDecl(NewNamespace);
   TypoCorrection Correction(ToIdent);
   Correction.addCorrectionDecl(NewNamespace);
Index: clang/test/AST/ast-dump-namespace-json.cpp
===
--- clang/test/AST/ast-dump-namespace-json.cpp
+++ clang/test/AST/ast-dump-namespace-json.cpp
@@ -170,6 +170,7 @@
 // CHECK-NEXT: }
 // CHECK-NEXT:},
 // CHECK-NEXT:"name": "quux"
+// CHECK-NEXT:"isNested": true
 // CHECK-NEXT:   }
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
@@ -195,7 +196,7 @@
 // CHECK-NEXT:"tokLen": 1
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
-// CHECK-NEXT:  "name": "quux",
+// CHECK-NEXT:  "name": "quux"
 // CHECK-NEXT:  "inner": [
 // CHECK-NEXT:   {
 // CHECK-NEXT:"id": "0x{{.*}}",
@@ -220,7 +221,8 @@
 // CHECK-NEXT: }
 // CHECK-NEXT:},
 // CHECK-NEXT:"name": "frobble",
-// CHECK-NEXT:"isInline": true
+// CHECK-NEXT:"isInline": true,
+// CHECK-NEXT:"isNested": true
 // CHECK-NEXT:   }
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
Index: clang/test/AST/ast-dump-decl.cpp
===
--- clang/test/AST/ast-dump-decl.cpp
+++ clang/test/AST/ast-dump-decl.cpp
@@ -53,6 +53,23 @@
 }
 // CHECK:  NamespaceDecl{{.*}} TestNamespaceDeclInline inline
 
+namespace TestNestedNameSpace::Nested {
+}
+// CHECK:  NamespaceDecl{{.*}} TestNestedNameSpace
+// CHECK:  NamespaceDecl{{.*}} Nested nested{{\s*$}}
+
+namespace TestMultipleNested::SecondLevelNested::Nested {
+}
+// CHECK:  NamespaceDecl{{.*}} TestMultipleNested
+// CHECK:  NamespaceDecl{{.*}} SecondLevelNested nested
+// CHECK:  NamespaceDecl{{.*}} Nested nested{{\s*$}}
+
+namespace TestInlineNested::inline SecondLevel::inline Nested {
+}
+// CHECK:  NamespaceDecl{{.*}} TestInlineNested
+// CHECK:  NamespaceDecl{{.*}} SecondLevel inline nested
+// CHECK:  NamespaceDecl{{.*}} Nested inline nested{{\s*$}}
+
 namespace testUsingDirectiveDecl {
   namespace A {
   }
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -1252,6 +1252,7 @@
   VisitRedeclarable(D);
   VisitNamedDecl(D);
   Record.push_back(D->isInline());
+  Record.push_back(D->isNested());
   Record.AddSourceLocation(D->getBeginLoc());
   Record.AddSourceLocation(D->getRBraceLoc());
 
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -1745,6 +1745,7 @@
   RedeclarableResult Redecl = VisitRedeclarable(D);
   VisitNamedDecl(D);
   D->setInline(Record.readInt());
+  D->setNested(Record.readInt());
   D->LocStart = readSourceLocation();
   D->RBraceLoc = readSourceLocation();
 
@@ -1758,7 +1759,7 @@
   } else {
 // Link this namespace back to the first declaration, which has already
 // been deserialized.
-D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
+D->AnonOrFirstNamespaceAndFlags.setPointer(D->getFirstDecl());
   }
 
   mergeRedeclarable(D, Redecl);
@@ -2784,8 +2785,8 @@
 // We cannot have loaded any redeclarations of this declaration yet, so
 // there's nothing else that needs to be updated.
 if (auto *Namespace = dyn_cast(D))
-  Namespace->AnonOrFirstNamespaceAndInline.setPointer(
-  assert_cast(ExistingCanon));
+  Namespace->AnonOrFirstNamespa

[PATCH] D137944: [ObjC][ARC] Teach the OptimizeSequences step of ObjCARCOpts about WinEH funclet tokens

2022-11-23 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz updated this revision to Diff 477470.
sgraenitz marked an inline comment as done.
sgraenitz added a comment.

Rebase and update check-lines after D137939 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137944

Files:
  clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
  llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
  llvm/test/Transforms/ObjCARC/funclet-catchpad.ll

Index: llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
===
--- /dev/null
+++ llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
@@ -0,0 +1,40 @@
+; RUN: opt -mtriple=x86_64-windows-msvc -passes=objc-arc -S < %s | FileCheck %s
+
+; Check that funclet tokens are preserved
+;
+; CHECK-LABEL:  catch:
+; CHECK:  %1 = catchpad within %0
+; CHECK:  %2 = tail call ptr @llvm.objc.retain(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  call void @llvm.objc.release(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  catchret from %1 to label %eh.cont
+
+define void @try_catch_with_objc_intrinsic() personality ptr @__CxxFrameHandler3 {
+entry:
+  %exn.slot = alloca ptr, align 8
+  invoke void @may_throw(ptr null) to label %eh.cont unwind label %catch.dispatch
+
+catch.dispatch:   ; preds = %entry
+  %0 = catchswitch within none [label %catch] unwind to caller
+
+eh.cont:  ; preds = %catch, %entry
+  ret void
+
+catch:; preds = %catch.dispatch
+  %1 = catchpad within %0 [ptr null, i32 0, ptr %exn.slot]
+  br label %if.then
+
+if.then:  ; preds = %catch
+  %exn = load ptr, ptr null, align 8
+  %2 = call ptr @llvm.objc.retain(ptr %exn) [ "funclet"(token %1) ]
+  call void @may_throw(ptr %exn)
+  call void @llvm.objc.release(ptr %exn) [ "funclet"(token %1) ]
+  catchret from %1 to label %eh.cont
+}
+
+declare void @may_throw(ptr)
+declare i32 @__CxxFrameHandler3(...)
+
+declare ptr @llvm.objc.retain(ptr) #0
+declare void @llvm.objc.release(ptr) #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
===
--- llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -546,7 +546,9 @@
   void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
  BlotMapVector &Retains,
  DenseMap &Releases,
- SmallVectorImpl &DeadInsts, Module *M);
+ SmallVectorImpl &DeadInsts,
+ const DenseMap &BlockColors,
+ Module *M);
 
   bool PairUpRetainsAndReleases(DenseMap &BBStates,
 BlotMapVector &Retains,
@@ -559,7 +561,7 @@
 
   bool PerformCodePlacement(DenseMap &BBStates,
 BlotMapVector &Retains,
-DenseMap &Releases, Module *M);
+DenseMap &Releases, Function &F);
 
   void OptimizeWeakCalls(Function &F);
 
@@ -756,6 +758,18 @@
 
   return CallInst::Create(&CI, OpBundles);
 }
+
+void addOpBundleForFunclet(BasicBlock *BB,
+   const DenseMap &BlockColors,
+   SmallVectorImpl &OpBundles) {
+  if (!BlockColors.empty()) {
+const ColorVector &CV = BlockColors.find(BB)->second;
+assert(CV.size() == 1 && "non-unique color for block!");
+BasicBlock *EHPadBB = CV.front();
+if (auto *EHPad = dyn_cast(EHPadBB->getFirstNonPHI()))
+  OpBundles.emplace_back("funclet", EHPad);
+  }
+}
 }
 
 /// Visit each call, one at a time, and make simplifications without doing any
@@ -1757,12 +1771,12 @@
 }
 
 /// Move the calls in RetainsToMove and ReleasesToMove.
-void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
-   RRInfo &ReleasesToMove,
-   BlotMapVector &Retains,
-   DenseMap &Releases,
-   SmallVectorImpl &DeadInsts,
-   Module *M) {
+void ObjCARCOpt::MoveCalls(
+Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
+BlotMapVector &Retains,
+DenseMap &Releases,
+SmallVectorImpl &DeadInsts,
+const DenseMap &BlockColors, Module *M) {
   Type *ArgTy = Arg->getType();
   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
 
@@ -1773,7 +1787,9 @@
 Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
-CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
+SmallVector BundleList;
+addOpBundleForFunclet(InsertPt->getParent(), BlockColors, BundleList);
+CallInst *Call = CallInst::Create(Decl, MyArg, BundleLi

[PATCH] D137944: [ObjC][ARC] Teach the OptimizeSequences step of ObjCARCOpts about WinEH funclet tokens

2022-11-23 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz updated this revision to Diff 477471.
sgraenitz added a comment.

Handle potential multi-color basic blocks in addOpBundleForFunclet()


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137944

Files:
  clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
  llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
  llvm/test/Transforms/ObjCARC/funclet-catchpad.ll

Index: llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
===
--- /dev/null
+++ llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
@@ -0,0 +1,40 @@
+; RUN: opt -mtriple=x86_64-windows-msvc -passes=objc-arc -S < %s | FileCheck %s
+
+; Check that funclet tokens are preserved
+;
+; CHECK-LABEL:  catch:
+; CHECK:  %1 = catchpad within %0
+; CHECK:  %2 = tail call ptr @llvm.objc.retain(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  call void @llvm.objc.release(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  catchret from %1 to label %eh.cont
+
+define void @try_catch_with_objc_intrinsic() personality ptr @__CxxFrameHandler3 {
+entry:
+  %exn.slot = alloca ptr, align 8
+  invoke void @may_throw(ptr null) to label %eh.cont unwind label %catch.dispatch
+
+catch.dispatch:   ; preds = %entry
+  %0 = catchswitch within none [label %catch] unwind to caller
+
+eh.cont:  ; preds = %catch, %entry
+  ret void
+
+catch:; preds = %catch.dispatch
+  %1 = catchpad within %0 [ptr null, i32 0, ptr %exn.slot]
+  br label %if.then
+
+if.then:  ; preds = %catch
+  %exn = load ptr, ptr null, align 8
+  %2 = call ptr @llvm.objc.retain(ptr %exn) [ "funclet"(token %1) ]
+  call void @may_throw(ptr %exn)
+  call void @llvm.objc.release(ptr %exn) [ "funclet"(token %1) ]
+  catchret from %1 to label %eh.cont
+}
+
+declare void @may_throw(ptr)
+declare i32 @__CxxFrameHandler3(...)
+
+declare ptr @llvm.objc.retain(ptr) #0
+declare void @llvm.objc.release(ptr) #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
===
--- llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -546,7 +546,9 @@
   void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
  BlotMapVector &Retains,
  DenseMap &Releases,
- SmallVectorImpl &DeadInsts, Module *M);
+ SmallVectorImpl &DeadInsts,
+ const DenseMap &BlockColors,
+ Module *M);
 
   bool PairUpRetainsAndReleases(DenseMap &BBStates,
 BlotMapVector &Retains,
@@ -559,7 +561,7 @@
 
   bool PerformCodePlacement(DenseMap &BBStates,
 BlotMapVector &Retains,
-DenseMap &Releases, Module *M);
+DenseMap &Releases, Function &F);
 
   void OptimizeWeakCalls(Function &F);
 
@@ -756,6 +758,20 @@
 
   return CallInst::Create(&CI, OpBundles);
 }
+
+void addOpBundleForFunclet(BasicBlock *BB,
+   const DenseMap &BlockColors,
+   SmallVectorImpl &OpBundles) {
+  if (!BlockColors.empty()) {
+const ColorVector &CV = BlockColors.find(BB)->second;
+assert(CV.size() > 0 && "Uncolored block");
+for (BasicBlock *EHPadBB : CV)
+  if (auto *EHPad = dyn_cast(EHPadBB->getFirstNonPHI())) {
+OpBundles.emplace_back("funclet", EHPad);
+return;
+  }
+  }
+}
 }
 
 /// Visit each call, one at a time, and make simplifications without doing any
@@ -1757,12 +1773,12 @@
 }
 
 /// Move the calls in RetainsToMove and ReleasesToMove.
-void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
-   RRInfo &ReleasesToMove,
-   BlotMapVector &Retains,
-   DenseMap &Releases,
-   SmallVectorImpl &DeadInsts,
-   Module *M) {
+void ObjCARCOpt::MoveCalls(
+Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
+BlotMapVector &Retains,
+DenseMap &Releases,
+SmallVectorImpl &DeadInsts,
+const DenseMap &BlockColors, Module *M) {
   Type *ArgTy = Arg->getType();
   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
 
@@ -1773,7 +1789,9 @@
 Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
-CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
+SmallVector BundleList;
+addOpBundleForFunclet(InsertPt->getParent(), BlockColors, BundleList);
+CallInst *Call = CallInst::Create(Decl, MyArg, BundleList, "", InsertPt);
 Call->setDoesN

[PATCH] D134177: Add MC support of RISCV Zcd Extension

2022-11-23 Thread Xinlong Wu via Phabricator via cfe-commits
VincentWu updated this revision to Diff 477475.
VincentWu added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134177

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoC.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/MC/RISCV/compress-rv32d.s
  llvm/test/MC/RISCV/rv32dc-valid.s
  llvm/test/MC/RISCV/rv64dc-valid.s

Index: llvm/test/MC/RISCV/rv64dc-valid.s
===
--- llvm/test/MC/RISCV/rv64dc-valid.s
+++ llvm/test/MC/RISCV/rv64dc-valid.s
@@ -3,31 +3,39 @@
 # RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+c,+d < %s \
 # RUN: | llvm-objdump --mattr=+c,+d -M no-aliases -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zcd,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zcd,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zcd,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
 #
 # RUN: not llvm-mc -triple riscv64 -mattr=+c \
 # RUN: -riscv-no-aliases -show-encoding < %s 2>&1 \
 # RUN: | FileCheck -check-prefixes=CHECK-NO-EXT-D %s
+# RUN: not llvm-mc -triple riscv64 -mattr=+experimental-zcd \
+# RUN: -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT-D %s
 # RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
 # RUN: | FileCheck -check-prefixes=CHECK-NO-EXT-DC %s
 
 # CHECK-ASM-AND-OBJ: c.fldsp  fs0, 504(sp)
 # CHECK-ASM: encoding: [0x7e,0x34]
 # CHECK-NO-EXT-D:  error: instruction requires the following: 'D' (Double-Precision Floating-Point){{$}}
-# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions), 'D' (Double-Precision Floating-Point){{$}}
+# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions) or 'Zcd' (Compressed Double-Precision Floating-Point Instructions), 'D' (Double-Precision Floating-Point){{$}}
 c.fldsp  fs0, 504(sp)
 # CHECK-ASM-AND-OBJ: c.fsdsp  fa7, 504(sp)
 # CHECK-ASM: encoding: [0xc6,0xbf]
 # CHECK-NO-EXT-D:  error: instruction requires the following: 'D' (Double-Precision Floating-Point){{$}}
-# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions), 'D' (Double-Precision Floating-Point){{$}}
+# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions) or 'Zcd' (Compressed Double-Precision Floating-Point Instructions), 'D' (Double-Precision Floating-Point){{$}}
 c.fsdsp  fa7, 504(sp)
 
 # CHECK-ASM-AND-OBJ: c.fld  fa3, 248(a5)
 # CHECK-ASM: encoding: [0xf4,0x3f]
 # CHECK-NO-EXT-D:  error: instruction requires the following: 'D' (Double-Precision Floating-Point){{$}}
-# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions), 'D' (Double-Precision Floating-Point){{$}}
+# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions) or 'Zcd' (Compressed Double-Precision Floating-Point Instructions), 'D' (Double-Precision Floating-Point){{$}}
 c.fld  fa3, 248(a5)
 # CHECK-ASM-AND-OBJ: c.fsd  fa2, 248(a1)
 # CHECK-ASM: encoding: [0xf0,0xbd]
 # CHECK-NO-EXT-D:  error: instruction requires the following: 'D' (Double-Precision Floating-Point){{$}}
-# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions), 'D' (Double-Precision Floating-Point){{$}}
+# CHECK-NO-EXT-DC:  error: instruction requires the following: 'C' (Compressed Instructions) or 'Zcd' (Compressed Double-Precision Floating-Point Instructions), 'D' (Double-Precision Floating-Point){{$}}
 c.fsd  fa2, 248(a1)
Index: llvm/test/MC/RISCV/rv32dc-valid.s
===
--- llvm/test/MC/RISCV/rv32dc-valid.s
+++ llvm/test/MC/RISCV/rv32dc-valid.s
@@ -3,31 +3,39 @@
 # RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+c,+d < %s \
 # RUN: | llvm-objdump --mattr=+c,+d -M no-aliases -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zcd,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zcd,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zcd,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
 #
 # RUN: not llvm-mc -triple riscv32 -mattr=+c \
 # RUN: -riscv-no-aliases -show-encoding < %s 2>&1 \
 # RUN: | FileCheck -check-prefixes=CHECK-NO-EXT-D %s
+# RUN: not llvm-mc -triple ris

[PATCH] D137343: [clang] add -Wvla-stack-allocation

2022-11-23 Thread Tao Liang via Phabricator via cfe-commits
Origami404 updated this revision to Diff 477482.
Origami404 added a comment.

Update release notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137343

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaType.cpp
  clang/test/Sema/warn-vla.c

Index: clang/test/Sema/warn-vla.c
===
--- clang/test/Sema/warn-vla.c
+++ clang/test/Sema/warn-vla.c
@@ -1,12 +1,39 @@
-// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify -Wvla %s
-// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify -Wvla %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=expected,no-fallback-c99 -Wvla -Wvla-stack-allocation %s
+// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify=expected,no-fallback-c89 -Wvla -Wvla-stack-allocation %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=expected,fallback -Wvla %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=expected,only-stack-allocation -Wvla-stack-allocation -Wno-vla %s
 
 void test1(int n) {
-  int v[n]; // expected-warning {{variable length array}}
+  int v[n]; /* no-fallback-c89-warning {{variable length arrays are a C99 feature}}
+   no-fallback-c99-warning {{variable length array that may require stack allocation used}}
+   fallback-warning {{variable length array used}}
+   only-stack-allocation-warning {{variable length array that may require stack allocation used}}
+*/
 }
 
-void test2(int n, int v[n]) { // expected-warning {{variable length array}}
+void test2(int n, int v[n]) { /* no-fallback-c89-warning {{variable length arrays are a C99 feature}}
+ no-fallback-c99-warning {{variable length array used}}
+ fallback-warning {{variable length array used}}
+  */
 }
 
-void test3(int n, int v[n]); // expected-warning {{variable length array}}
+void test3(int n, int v[n]); /* no-fallback-c89-warning {{variable length arrays are a C99 feature}}
+no-fallback-c99-warning {{variable length array used}}
+fallback-warning {{variable length array used}}
+  */
 
+int test4_num;
+typedef int Test4[test4_num]; /* no-fallback-c89-warning {{variable length arrays are a C99 feature}} 
+ no-fallback-c99-warning {{variable length array used}}
+ fallback-warning {{variable length array used}}
+ expected-error {{variable length array declaration not allowed at file scope}}
+  */
+
+void test5() {
+  typedef int type[test4_num]; /* no-fallback-c89-warning {{variable length arrays are a C99 feature}} 
+  no-fallback-c99-warning {{variable length array that may require stack allocation used}}
+  fallback-warning {{variable length array used}}
+  only-stack-allocation-warning {{variable length array that may require stack allocation used}}
+*/
+
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
@@ -2530,7 +2531,8 @@
 return QualType();
   }
 
-  // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
+  // VLAs always produce at least a -Wvla-portability or -Wvla-stack-allocation
+  // diagnostic, sometimes an error.
   unsigned VLADiag;
   bool VLAIsError;
   if (getLangOpts().OpenCL) {
@@ -2538,7 +2540,26 @@
 VLADiag = diag::err_opencl_vla;
 VLAIsError = true;
   } else if (getLangOpts().C99) {
-VLADiag = diag::warn_vla_used;
+// after C99, VLA is no longer an extension.
+if (getCurScope()->getFlags() == Scope::ScopeFlags::DeclScope) {
+  // VLA in file scope typedef will have an error, and should not have a
+  // warning of portability. But for backward compatibility, we preform the
+  // exact same action like before (which will give an warning of "vla
+  // used").
+  VLADiag = diag::warn_vla_portability;
+} else if (getCurScope()->isFunctionPrototypeScope()) {
+  // VLA in function prototype is acceptable by C2x standard
+  // so just give a protability warning
+  VLADiag = diag::warn_vla_portability;
+} else {
+  // in other case, a VLA will cause stack allocation
+  // if -Wvla-stack-allocation is

[PATCH] D138571: Update ninja and cmake installation commands on LibASTMatchersTutorial

2022-11-23 Thread Ismael via Phabricator via cfe-commits
ismaelJimenez created this revision.
Herald added a project: All.
ismaelJimenez 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/D138571

Files:
  clang/docs/LibASTMatchersTutorial.rst


Index: clang/docs/LibASTMatchersTutorial.rst
===
--- clang/docs/LibASTMatchersTutorial.rst
+++ clang/docs/LibASTMatchersTutorial.rst
@@ -30,14 +30,14 @@
 .. code-block:: console
 
   cd ~/clang-llvm
-  git clone https://github.com/martine/ninja.git
+  git clone https://github.com/ninja-build/ninja
   cd ninja
   git checkout release
-  ./bootstrap.py
+  ./configure.py --bootstrap
   sudo cp ninja /usr/bin/
 
   cd ~/clang-llvm
-  git clone git://cmake.org/stage/cmake.git
+  git clone https://github.com/Kitware/CMake.git
   cd cmake
   git checkout next
   ./bootstrap


Index: clang/docs/LibASTMatchersTutorial.rst
===
--- clang/docs/LibASTMatchersTutorial.rst
+++ clang/docs/LibASTMatchersTutorial.rst
@@ -30,14 +30,14 @@
 .. code-block:: console
 
   cd ~/clang-llvm
-  git clone https://github.com/martine/ninja.git
+  git clone https://github.com/ninja-build/ninja
   cd ninja
   git checkout release
-  ./bootstrap.py
+  ./configure.py --bootstrap
   sudo cp ninja /usr/bin/
 
   cd ~/clang-llvm
-  git clone git://cmake.org/stage/cmake.git
+  git clone https://github.com/Kitware/CMake.git
   cd cmake
   git checkout next
   ./bootstrap
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138571: Update ninja and cmake installation commands on LibASTMatchersTutorial

2022-11-23 Thread Ismael via Phabricator via cfe-commits
ismaelJimenez updated this revision to Diff 477488.
ismaelJimenez added a comment.

Fix


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138571

Files:
  clang/docs/LibASTMatchersTutorial.rst


Index: clang/docs/LibASTMatchersTutorial.rst
===
--- clang/docs/LibASTMatchersTutorial.rst
+++ clang/docs/LibASTMatchersTutorial.rst
@@ -30,14 +30,14 @@
 .. code-block:: console
 
   cd ~/clang-llvm
-  git clone https://github.com/martine/ninja.git
+  git clone https://github.com/ninja-build/ninja.git
   cd ninja
   git checkout release
-  ./bootstrap.py
+  ./configure.py --bootstrap
   sudo cp ninja /usr/bin/
 
   cd ~/clang-llvm
-  git clone git://cmake.org/stage/cmake.git
+  git clone https://github.com/Kitware/CMake.git
   cd cmake
   git checkout next
   ./bootstrap


Index: clang/docs/LibASTMatchersTutorial.rst
===
--- clang/docs/LibASTMatchersTutorial.rst
+++ clang/docs/LibASTMatchersTutorial.rst
@@ -30,14 +30,14 @@
 .. code-block:: console
 
   cd ~/clang-llvm
-  git clone https://github.com/martine/ninja.git
+  git clone https://github.com/ninja-build/ninja.git
   cd ninja
   git checkout release
-  ./bootstrap.py
+  ./configure.py --bootstrap
   sudo cp ninja /usr/bin/
 
   cd ~/clang-llvm
-  git clone git://cmake.org/stage/cmake.git
+  git clone https://github.com/Kitware/CMake.git
   cd cmake
   git checkout next
   ./bootstrap
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138559: Record macro references in #ifdef clause.

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

Thanks, this code looks good to me overall. I think we can extend it to handle 
the `Defined`, `Elifdef`, `Elifndef` cases.

And please add a `[include-cleaner]` prefix in the commit title.




Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:95
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())

nit: we can set a default value (`RefType::Explicit`) for the RT parameter, 
then we don't need to pass the `RefType::Explicit` in all callsites.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138559

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


Re: [clang] 5cfc22c - Revert "[SROA] `isVectorPromotionViable()`: memory intrinsics operate on vectors of bytes"

2022-11-23 Thread Roman Lebedev via cfe-commits
Thank you!

On Wed, Nov 23, 2022 at 3:11 PM Benjamin Kramer via cfe-commits
 wrote:
>
>
> Author: Benjamin Kramer
> Date: 2022-11-23T13:11:16+01:00
> New Revision: 5cfc22cafe3f2465e0bb324f8daba82ffcabd0df
>
> URL: 
> https://github.com/llvm/llvm-project/commit/5cfc22cafe3f2465e0bb324f8daba82ffcabd0df
> DIFF: 
> https://github.com/llvm/llvm-project/commit/5cfc22cafe3f2465e0bb324f8daba82ffcabd0df.diff
>
> LOG: Revert "[SROA] `isVectorPromotionViable()`: memory intrinsics operate on 
> vectors of bytes"
>
> This reverts commit cf624b23bc5d5a6161706d1663def49380ff816a. It
> triggers crashes in clang, see the comments on github on the original
> change.
>
> Added:
>
>
> Modified:
> clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
> llvm/lib/Transforms/Scalar/SROA.cpp
> llvm/test/CodeGen/AMDGPU/v1024.ll
> llvm/test/DebugInfo/X86/sroasplit-1.ll
> llvm/test/DebugInfo/X86/sroasplit-4.ll
> llvm/test/Transforms/PhaseOrdering/instcombine-sroa-inttoptr.ll
> llvm/test/Transforms/SROA/address-spaces.ll
> llvm/test/Transforms/SROA/alignment.ll
> llvm/test/Transforms/SROA/alloca-address-space.ll
> llvm/test/Transforms/SROA/basictest.ll
> llvm/test/Transforms/SROA/pointer-offset-size.ll
> llvm/test/Transforms/SROA/scalable-vectors.ll
> llvm/test/Transforms/SROA/slice-width.ll
> llvm/test/Transforms/SROA/sroa-common-type-fail-promotion.ll
> llvm/test/Transforms/SROA/tbaa-struct.ll
> llvm/test/Transforms/SROA/tbaa-struct2.ll
> llvm/test/Transforms/SROA/vector-promotion.ll
>
> Removed:
>
>
>
> 
> diff  --git a/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl 
> b/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
> index 859e81f08d6bd..65f6f2e7d8c24 100644
> --- a/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
> +++ b/clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
> @@ -515,17 +515,13 @@ typedef struct {
>private char *p;
>  } StructTy3;
>
> -// CHECK-LABEL: @test_memset_private(
> -// CHECK-NEXT:  entry:
> -// CHECK-NEXT:[[TMP0:%.*]] = bitcast [[STRUCT_STRUCTTY3:%.*]] 
> addrspace(5)* [[PTR:%.*]] to i8 addrspace(5)*
> -// CHECK-NEXT:
> [[S3_SROA_0_SROA_0_0_S3_SROA_0_0__SROA_CAST2_SROA_CAST:%.*]] = bitcast 
> [[STRUCT_STRUCTTY3]] addrspace(5)* [[PTR]] to <32 x i8> addrspace(5)*
> -// CHECK-NEXT:store <32 x i8> zeroinitializer, <32 x i8> addrspace(5)* 
> [[S3_SROA_0_SROA_0_0_S3_SROA_0_0__SROA_CAST2_SROA_CAST]], align 8, 
> !tbaa.struct !9
> -// CHECK-NEXT:[[S3_SROA_4_0__SROA_IDX6:%.*]] = getelementptr inbounds 
> [[STRUCT_STRUCTTY3]], [[STRUCT_STRUCTTY3]] addrspace(5)* [[PTR]], i32 0, i32 4
> -// CHECK-NEXT:store i8 addrspace(5)* addrspacecast (i8* null to i8 
> addrspace(5)*), i8 addrspace(5)* addrspace(5)* [[S3_SROA_4_0__SROA_IDX6]], 
> align 8, !tbaa.struct !12
> -// CHECK-NEXT:[[S3_SROA_5_0__SROA_IDX:%.*]] = getelementptr inbounds i8, 
> i8 addrspace(5)* [[TMP0]], i32 36
> -// CHECK-NEXT:[[S3_SROA_5_0__SROA_CAST8:%.*]] = bitcast i8 addrspace(5)* 
> [[S3_SROA_5_0__SROA_IDX]] to i32 addrspace(5)*
> -// CHECK-NEXT:store i32 0, i32 addrspace(5)* 
> [[S3_SROA_5_0__SROA_CAST8]], align 4, !tbaa.struct !13
> -// CHECK-NEXT:ret void
> +// CHECK-LABEL: test_memset_private
> +// CHECK: call void @llvm.memset.p5i8.i64(i8 addrspace(5)* noundef align 8 
> {{.*}}, i8 0, i64 32, i1 false)
> +// CHECK: [[GEP:%.*]] = getelementptr inbounds %struct.StructTy3, 
> %struct.StructTy3 addrspace(5)* %ptr, i32 0, i32 4
> +// CHECK: store i8 addrspace(5)* addrspacecast (i8* null to i8 
> addrspace(5)*), i8 addrspace(5)* addrspace(5)* [[GEP]]
> +// CHECK: [[GEP1:%.*]] = getelementptr inbounds i8, i8 addrspace(5)* {{.*}}, 
> i32 36
> +// CHECK: [[GEP1_CAST:%.*]] = bitcast i8 addrspace(5)* [[GEP1]] to i32 
> addrspace(5)*
> +// CHECK: store i32 0, i32 addrspace(5)* [[GEP1_CAST]], align 4
>  void test_memset_private(private StructTy3 *ptr) {
>StructTy3 S3 = {0, 0, 0, 0, 0};
>*ptr = S3;
>
> diff  --git a/llvm/lib/Transforms/Scalar/SROA.cpp 
> b/llvm/lib/Transforms/Scalar/SROA.cpp
> index 09a445c236fa7..6dcdd630b6bae 100644
> --- a/llvm/lib/Transforms/Scalar/SROA.cpp
> +++ b/llvm/lib/Transforms/Scalar/SROA.cpp
> @@ -1806,10 +1806,8 @@ static bool isVectorPromotionViableForSlice(Partition 
> &P, const Slice &S,
>? Ty->getElementType()
>: FixedVectorType::get(Ty->getElementType(), 
> NumElements);
>
> -  Type *SplitIntTy = nullptr;
> -  if (uint64_t Bitwidth = NumElements * ElementSize * 8;
> -  Bitwidth <= IntegerType::MAX_INT_BITS)
> -SplitIntTy = Type::getIntNTy(Ty->getContext(), Bitwidth);
> +  Type *SplitIntTy =
> +  Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
>
>Use *U = S.getUse();
>
> @@ -1828,8 +1826,7 @@ static bool isVectorPromotionViableForSlice(Partition 
> &P, const Slice &S,
>  // Disable vector promotion when there are loads or stores of an FCA.
>  if (LTy->isStructTy())
>retur

[clang] 93b98eb - [analyzer] getBinding should auto-detect type only if it was not given

2022-11-23 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-11-23T15:52:11+01:00
New Revision: 93b98eb399a14f2c626ed82eaaa70997f8323406

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

LOG: [analyzer] getBinding should auto-detect type only if it was not given

Casting a pointer to a suitably large integral type by reinterpret-cast
should result in the same value as by using the `__builtin_bit_cast()`.
The compiler exploits this: https://godbolt.org/z/zMP3sG683

However, the analyzer does not bind the same symbolic value to these
expressions, resulting in weird situations, such as failing equality
checks and even results in crashes: https://godbolt.org/z/oeMP7cj8q

Previously, in the `RegionStoreManager::getBinding()` even if `T` was
non-null, we replaced it with `TVR->getValueType()` in case the `MR` was
`TypedValueRegion`.
It doesn't make much sense to auto-detect the type if the type is
already given. By not doing the auto-detection, we would just do the
right thing and perform the load by that type.
This means that we will cast the value to that type.

So, in this patch, I'm proposing to do auto-detection only if the type
was null.

Here is a snippet of code, annotated by the previous and new dump values.
`LocAsInteger` should wrap the `SymRegion`, since we want to load the
address as if it was an integer.
In none of the following cases should type auto-detection be triggered,
hence we should eventually reach an `evalCast()` to lazily cast the loaded
value into that type.

```lang=C++
void LValueToRValueBitCast_dumps(void *p, char (*array)[8]) {
  clang_analyzer_dump(p); // remained: &SymRegion{reg_$0}
  clang_analyzer_dump(array); // remained: {{&SymRegion{reg_$1}
  clang_analyzer_dump((unsigned long)p);
  // remained: {{&SymRegion{reg_$0} [as 64 bit integer]}}
  clang_analyzer_dump(__builtin_bit_cast(unsigned long, p)); <- 
change #1
  // previously: {{&SymRegion{reg_$0}}}
  // now:{{&SymRegion{reg_$0} [as 64 bit integer]}}
  clang_analyzer_dump((unsigned long)array); // remained: 
{{&SymRegion{reg_$1} [as 64 bit integer]}}
  clang_analyzer_dump(__builtin_bit_cast(unsigned long, array)); <- 
change #2
  // previously: {{&SymRegion{reg_$1}}}
  // now:{{&SymRegion{reg_$1} [as 64 bit integer]}}
}
```

Reviewed By: xazax.hun

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/test/Analysis/ptr-arith.cpp
clang/test/Analysis/svalbuilder-float-cast.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 8af351f642469..3e638be787b51 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1414,19 +1414,20 @@ SVal 
RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T)
 return UnknownVal();
   }
 
-  if (!isa(MR)) {
-if (T.isNull()) {
-  if (const TypedRegion *TR = dyn_cast(MR))
-T = TR->getLocationType()->getPointeeType();
-  else if (const SymbolicRegion *SR = dyn_cast(MR))
-T = SR->getPointeeStaticType();
-}
-assert(!T.isNull() && "Unable to auto-detect binding type!");
-assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
+  // Auto-detect the binding type.
+  if (T.isNull()) {
+if (const auto *TVR = dyn_cast(MR))
+  T = TVR->getValueType();
+else if (const auto *TR = dyn_cast(MR))
+  T = TR->getLocationType()->getPointeeType();
+else if (const auto *SR = dyn_cast(MR))
+  T = SR->getPointeeStaticType();
+  }
+  assert(!T.isNull() && "Unable to auto-detect binding type!");
+  assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
+
+  if (!isa(MR))
 MR = GetElementZeroRegion(cast(MR), T);
-  } else {
-T = cast(MR)->getValueType();
-  }
 
   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
   //  instead of 'Loc', and have the other Loc cases handled at a higher level.

diff  --git a/clang/test/Analysis/ptr-arith.cpp 
b/clang/test/Analysis/ptr-arith.cpp
index e44939768960d..a1264a1f04839 100644
--- a/clang/test/Analysis/ptr-arith.cpp
+++ b/clang/test/Analysis/ptr-arith.cpp
@@ -1,4 +1,9 @@
-// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 
-analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm -verify %s
+// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -verify %s -triple 
x86_64-pc-linux-gnu \
+// RUN:-analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm
+
+// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -verify %s -triple 
x86_64-pc-linux-gnu \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-analyzer-c

[PATCH] D136603: [analyzer] getBinding should auto-detect type only if it was not given

2022-11-23 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG93b98eb399a1: [analyzer] getBinding should auto-detect type 
only if it was not given (authored by steakhal).

Changed prior to commit:
  https://reviews.llvm.org/D136603?vs=471112&id=477493#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136603

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/ptr-arith.cpp
  clang/test/Analysis/svalbuilder-float-cast.c

Index: clang/test/Analysis/svalbuilder-float-cast.c
===
--- clang/test/Analysis/svalbuilder-float-cast.c
+++ clang/test/Analysis/svalbuilder-float-cast.c
@@ -1,16 +1,25 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker debug.ExprInspection -Wno-deprecated-non-prototype -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker debug.ExprInspection -Wno-deprecated-non-prototype -verify %s \
+// RUN:-analyzer-config support-symbolic-integer-casts=true
+
 void clang_analyzer_denote(int, const char *);
 void clang_analyzer_express(int);
+void clang_analyzer_dump(int);
+void clang_analyzer_dump_ptr(int *);
 
 void SymbolCast_of_float_type_aux(int *p) {
+  clang_analyzer_dump_ptr(p); // expected-warning {{&x}}
+  clang_analyzer_dump(*p); // expected-warning {{Unknown}}
+  // Storing to the memory region of 'float x' as 'int' will
+  // materialize a fresh conjured symbol to regain accuracy.
   *p += 0;
-  // FIXME: Ideally, all unknown values should be symbolicated.
-  clang_analyzer_denote(*p, "$x"); // expected-warning{{Not a symbol}}
+  clang_analyzer_dump_ptr(p); // expected-warning {{&x}}
+  clang_analyzer_dump(*p); // expected-warning {{conj_$0{int}}
+  clang_analyzer_denote(*p, "$x");
 
   *p += 1;
   // This should NOT be (float)$x + 1. Symbol $x was never casted to float.
-  // FIXME: Ideally, this should be $x + 1.
-  clang_analyzer_express(*p); // expected-warning{{Not a symbol}}
+  clang_analyzer_express(*p); // expected-warning{{$x + 1}}
 }
 
 void SymbolCast_of_float_type(void) {
Index: clang/test/Analysis/ptr-arith.cpp
===
--- clang/test/Analysis/ptr-arith.cpp
+++ clang/test/Analysis/ptr-arith.cpp
@@ -1,4 +1,9 @@
-// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm -verify %s
+// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -verify %s -triple x86_64-pc-linux-gnu \
+// RUN:-analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm
+
+// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -verify %s -triple x86_64-pc-linux-gnu \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm
 
 template  void clang_analyzer_dump(T);
 
@@ -141,3 +146,22 @@
   return bits->b; // no-warning
 }
 } // namespace Bug_55934
+
+void LValueToRValueBitCast_dumps(void *p, char (*array)[8]) {
+  clang_analyzer_dump(p);
+  clang_analyzer_dump(array);
+  // expected-warning@-2 {{&SymRegion{reg_$0}}}
+  // expected-warning@-2 {{&SymRegion{reg_$1}}}
+  clang_analyzer_dump((unsigned long)p);
+  clang_analyzer_dump(__builtin_bit_cast(unsigned long, p));
+  // expected-warning@-2 {{&SymRegion{reg_$0} [as 64 bit integer]}}
+  // expected-warning@-2 {{&SymRegion{reg_$0} [as 64 bit integer]}}
+  clang_analyzer_dump((unsigned long)array);
+  clang_analyzer_dump(__builtin_bit_cast(unsigned long, array));
+  // expected-warning@-2 {{&SymRegion{reg_$1} [as 64 bit integer]}}
+  // expected-warning@-2 {{&SymRegion{reg_$1} [as 64 bit integer]}}
+}
+
+unsigned long ptr_arithmetic(void *p) {
+  return __builtin_bit_cast(unsigned long, p) + 1; // no-crash
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1414,19 +1414,20 @@
 return UnknownVal();
   }
 
-  if (!isa(MR)) {
-if (T.isNull()) {
-  if (const TypedRegion *TR = dyn_cast(MR))
-T = TR->getLocationType()->getPointeeType();
-  else if (const SymbolicRegion *SR = dyn_cast(MR))
-T = SR->getPointeeStaticType();
-}
-assert(!T.isNull() && "Unable to auto-detect binding type!");
-assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
+  // Auto-detect the binding type.
+  if (T.isNull()) {
+if (const auto *TVR = dyn_cast(MR))
+  T = TVR->getValueType();
+else if (const auto *TR = dyn_cast(MR))
+  T = TR->getLocationType()->getPointeeType();
+else if (const auto *SR = dyn_cast(MR))
+  T = SR->getPointeeStaticType();
+  }
+  assert(!T.isNull() && "Unable to auto-detect binding type!");
+  assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
+
+  

[PATCH] D138216: [AMDGPU] Intrinsic to expose s_wait_event for export ready

2022-11-23 Thread Joe Nash via Phabricator via cfe-commits
Joe_Nash accepted this revision.
Joe_Nash 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/D138216/new/

https://reviews.llvm.org/D138216

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


[PATCH] D138319: [analyzer] Prepare structures for integral cast feature introducing

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

I spent some time on this patch. But I'm left thinking about why we need the 
extra indirection?
Couldn't we just use a `std::pair` pair as a key instead?
You mention //effective// bitwidths in your summary, but the code does not 
mention this concept.
Maybe you could elaborate on what //effective// bitwidth means in this context 
and how this changes the eqclass lookups.
In addition to this, I'd be curious about an informal proof of the correctness.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138319

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


[PATCH] D138157: Make -fsanitize=scudo use scudo_standalone. Delete check-scudo.

2022-11-23 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Reverted in 907baeec49bfbe9e76498634a9418e1dc6c973d9 for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138157

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


[PATCH] D138329: [-Wunsafe-buffer-usage] Add a new recursive matcher to replace `forEachDescendant` in unsafe buffer check

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



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:54-55
+  bool TraverseDecl(Decl *Node) {
+if (!Node)
+  return true;
+if (!match(*Node))

Can `Node` be ever null if the visitor is initiated only be `AST_MATCHER_P`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138329

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


[PATCH] D138554: [clang][Interp] Use placement new to construct opcode arguments into bytecode vector

2022-11-23 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeEmitter.cpp:166
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+if constexpr (std::is_trivially_copyable_v) {
+  const char *Data = reinterpret_cast(&Val);

Do we really need a separate case for trivially copyable types?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138554

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


[PATCH] D138577: Use proper triple in CmdArgsSansAnalyses for html info files

2022-11-23 Thread Anthony Groyer via Phabricator via cfe-commits
angroyer created this revision.
angroyer added a reviewer: LLVM.
angroyer added a project: LLVM.
Herald added a reviewer: NoQ.
Herald added a project: All.
angroyer requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The CmdArgsSansAnalyses array does not contain the "-target" argument required 
to define a valid "-triple" argument in the html info files. This patch aims to 
fix that.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138577

Files:
  clang/tools/scan-build/libexec/ccc-analyzer


Index: clang/tools/scan-build/libexec/ccc-analyzer
===
--- clang/tools/scan-build/libexec/ccc-analyzer
+++ clang/tools/scan-build/libexec/ccc-analyzer
@@ -226,6 +226,10 @@
   else {
 $Cmd = $Clang;
 
+if (defined $AnalyzerTarget) {
+  push @Args, "-target", $AnalyzerTarget;
+}
+
 # Create arguments for doing regular parsing.
 my $SyntaxArgs = GetCCArgs($HtmlDir, "-fsyntax-only", \@Args);
 @CmdArgsSansAnalyses = @$SyntaxArgs;
@@ -245,10 +249,6 @@
   push @Args, "-Xclang", $arg;
 }
 
-if (defined $AnalyzerTarget) {
-  push @Args, "-target", $AnalyzerTarget;
-}
-
 my $AnalysisArgs = GetCCArgs($HtmlDir, "--analyze", \@Args);
 @CmdArgs = @$AnalysisArgs;
   }


Index: clang/tools/scan-build/libexec/ccc-analyzer
===
--- clang/tools/scan-build/libexec/ccc-analyzer
+++ clang/tools/scan-build/libexec/ccc-analyzer
@@ -226,6 +226,10 @@
   else {
 $Cmd = $Clang;
 
+if (defined $AnalyzerTarget) {
+  push @Args, "-target", $AnalyzerTarget;
+}
+
 # Create arguments for doing regular parsing.
 my $SyntaxArgs = GetCCArgs($HtmlDir, "-fsyntax-only", \@Args);
 @CmdArgsSansAnalyses = @$SyntaxArgs;
@@ -245,10 +249,6 @@
   push @Args, "-Xclang", $arg;
 }
 
-if (defined $AnalyzerTarget) {
-  push @Args, "-target", $AnalyzerTarget;
-}
-
 my $AnalysisArgs = GetCCArgs($HtmlDir, "--analyze", \@Args);
 @CmdArgs = @$AnalysisArgs;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138554: [clang][Interp] Use placement new to construct opcode arguments into bytecode vector

2022-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeEmitter.cpp:166
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+if constexpr (std::is_trivially_copyable_v) {
+  const char *Data = reinterpret_cast(&Val);

sepavloff wrote:
> Do we really need a separate case for trivially copyable types?
It's not necessary, placement new'ing all everything works. I was just trying 
to keep the old behavior as much as possible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138554

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


[PATCH] D138579: [AArch64] Assembly support for FEAT_LRCPC3

2022-11-23 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson created this revision.
Herald added subscribers: hiraditya, kristof.beyls.
Herald added a project: All.
tmatheson requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This patch implements assembly support for the 2022 A-Profile Architecture
extension FEAT_LRCPC3. FEAT_LRCPC3 is AArch64 only and introduces new
variants of load/store instructions with release consistency ordering.

Specs for individual instructions can be found here:
https://developer.arm.com/documentation/ddi0602/2022-09/Base-Instructions/

This feature is optionally available from v8.2a and therefore not enabled by
default.

Contributors:

  Lucas Prates
  Sam Elliot
  Son Tuan Vu
  Tomas Matheson


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138579

Files:
  clang/test/Driver/aarch64-lrcpc3.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/lib/Target/AArch64/AArch64.td
  llvm/lib/Target/AArch64/AArch64InstrFormats.td
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
  llvm/test/MC/AArch64/arm64-memory.s
  llvm/test/MC/AArch64/armv8.9a-lrcpc3.s
  llvm/test/MC/Disassembler/AArch64/armv8.9a-lrcpc3.txt
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1606,7 +1606,8 @@
   AArch64::AEK_SME, AArch64::AEK_SMEF64F64, AArch64::AEK_SMEI16I64,
   AArch64::AEK_SME2,AArch64::AEK_HBC,  AArch64::AEK_MOPS,
   AArch64::AEK_PERFMON, AArch64::AEK_SVE2p1,   AArch64::AEK_SME2p1,
-  AArch64::AEK_B16B16,  AArch64::AEK_SMEF16F16, AArch64::AEK_CSSC};
+  AArch64::AEK_B16B16,  AArch64::AEK_SMEF16F16, AArch64::AEK_CSSC,
+  AArch64::AEK_RCPC3};
 
   std::vector Features;
 
@@ -1672,6 +1673,7 @@
   EXPECT_TRUE(llvm::is_contained(Features, "+mops"));
   EXPECT_TRUE(llvm::is_contained(Features, "+perfmon"));
   EXPECT_TRUE(llvm::is_contained(Features, "+cssc"));
+  EXPECT_TRUE(llvm::is_contained(Features, "+rcpc3"));
 
   // Assuming we listed every extension above, this should produce the same
   // result. (note that AEK_NONE doesn't have a name so it won't be in the
Index: llvm/test/MC/Disassembler/AArch64/armv8.9a-lrcpc3.txt
===
--- /dev/null
+++ llvm/test/MC/Disassembler/AArch64/armv8.9a-lrcpc3.txt
@@ -0,0 +1,113 @@
+# RUN: llvm-mc -triple aarch64-none-linux-gnu -disassemble -show-encoding   -mattr=+rcpc3 < %s | FileCheck %s
+# RUN: llvm-mc -triple aarch64-none-linux-gnu -disassemble -show-encoding -mattr=+v8.9a -mattr=+rcpc3 < %s | FileCheck %s
+# RUN: llvm-mc -triple aarch64-none-linux-gnu -disassemble -show-encoding -mattr=+v9.4a -mattr=+rcpc3 < %s | FileCheck %s
+
+# RUN: not llvm-mc -triple aarch64-none-linux-gnu -disassemble   < %s 2>&1 | FileCheck --check-prefix=ERROR-NO-RCPC3 %s
+# RUN: not llvm-mc -triple aarch64-none-linux-gnu -disassemble -mattr=+v8.9a < %s 2>&1 | FileCheck --check-prefix=ERROR-NO-RCPC3 %s
+# RUN: not llvm-mc -triple aarch64-none-linux-gnu -disassemble -mattr=+v9.4a < %s 2>&1 | FileCheck --check-prefix=ERROR-NO-RCPC3 %s
+
+[0x18,0x0a,0x00,0x99]
+# CHECK:  stilp   w24, w0, [x16, #-8]! // encoding: [0x18,0x0a,0x00,0x99]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x18,0x0a,0x00,0x99]
+# CHECK:  stilp   w24, w0, [x16, #-8]! // encoding: [0x18,0x0a,0x00,0x99]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x39,0x0a,0x01,0xd9]
+# CHECK:  stilp   x25, x1, [x17, #-16]!// encoding: [0x39,0x0a,0x01,0xd9]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x39,0x0a,0x01,0xd9]
+# CHECK:  stilp   x25, x1, [x17, #-16]!// encoding: [0x39,0x0a,0x01,0xd9]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x5a,0x1a,0x02,0x99]
+# CHECK:  stilp   w26, w2, [x18]   // encoding: [0x5a,0x1a,0x02,0x99]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0xfb,0x1b,0x03,0xd9]
+# CHECK:  stilp   x27, x3, [sp]// encoding: [0xfb,0x1b,0x03,0xd9]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x9c,0x0a,0x44,0x99]
+# CHECK:  ldiapp  w28, w4, [x20], #8   // encoding: [0x9c,0x0a,0x44,0x99]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0x9c,0x0a,0x44,0x99]
+# CHECK:  ldiapp  w28, w4, [x20], #8   // encoding: [0x9c,0x0a,0x44,0x99]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encoding
+[0xbd,0x0a,0x45,0xd9]
+# CHECK:  ldiapp  x29, x5, [x21], #16  // encoding: [0xbd,0x0a,0x45,0xd9]
+# ERROR-NO-RCPC3: [[@LINE-2]]:2: warning: invalid instruction encodi

[PATCH] D138583: Create unused non-trivially-destructible check in clang-tidy

2022-11-23 Thread Andrei via Phabricator via cfe-commits
ankineri created this revision.
ankineri added a reviewer: sammccall.
Herald added a subscriber: carlosgalvezp.
Herald added a reviewer: njames93.
Herald added a project: All.
ankineri requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Adds a check to clang-tidy to ensure that some (`absl::Status` by default) 
non-trivially-destructible objects are used.

Example code that should trigger a warning:

  {
absl::Status status = call_some_function();
  }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138583

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UnusedNtdObjectCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnusedNtdObjectCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-ntd-object.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-ntd-object.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-ntd-object.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-ntd-object.cpp
@@ -0,0 +1,64 @@
+// RUN: %check_clang_tidy %s bugprone-unused-ntd-object %t
+namespace absl {
+class Status {
+public:
+  bool ok() {return true;}
+};
+}
+bool simple_used_value() {
+  absl::Status status;
+  return status.ok();
+}
+
+bool if_used_value() {
+  absl::Status status;
+  if (status.ok()) {
+return true;
+  }
+  return false;
+}
+
+void accepts_status(absl::Status status) {
+}
+
+void used_by_function() {
+  absl::Status status;
+  accepts_status(status);
+}
+
+int value;
+int& accepts_status_returns_ref(absl::Status status) {
+  return value;
+}
+
+int* accepts_status_returns_ptr(absl::Status status) {
+  return &value;
+}
+
+
+void used_assign_lhs() {
+  absl::Status for_ref;
+  accepts_status_returns_ref(for_ref) = 7;
+  absl::Status for_ptr;
+  *accepts_status_returns_ptr(for_ptr) = 42;
+}
+
+void unused_simple() {
+  absl::Status unused;
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: 'unused' is unlikely to be RAII and is potentially unused [bugprone-unused-ntd-object]
+}
+
+void unused_reassigned() {
+  absl::Status unused;
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: 'unused' is unlikely to be RAII and is potentially unused [bugprone-unused-ntd-object]
+  unused = absl::Status();
+}
+
+void unused_checked_reassigned() {
+  absl::Status unused;
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: 'unused' is unlikely to be RAII and is potentially unused [bugprone-unused-ntd-object]
+  if (!unused.ok()) {
+return;
+  }
+  unused = absl::Status();
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -136,6 +136,7 @@
`bugprone-undelegated-constructor `_,
`bugprone-unhandled-exception-at-new `_,
`bugprone-unhandled-self-assignment `_,
+   `bugprone-unused-ntd-object `_,
`bugprone-unused-raii `_, "Yes"
`bugprone-unused-return-value `_,
`bugprone-use-after-move `_,
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-ntd-object.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-ntd-object.rst
@@ -0,0 +1,33 @@
+.. title:: clang-tidy - bugprone-unused-ntd-object
+
+bugprone-unused-ntd-object
+==
+
+Finds unused variables with nontrivial destructors that are unlikely to be used
+as RAII.
+
+Options
+---
+
+.. option:: CheckedTypes
+
+   Semicolon-separated list of types to check. The variable is checked if
+   the its type is from ``CheckedTypes``.
+   By default the following types are checked:
+   ``absl::Status``
+
+By default unused variables are reported only if they have trivial destructors,
+otherwise the destructor call is a usage of the variable, a pattern used in RAII.
+
+Some objects however have destructors because of internal state management, not
+to enable RAII. One such examle is ``absl::Status``. This class has reference counting (and thus a non-trivial destructor), but it is a "meaningless" usage. Consider the following code.
+
+.. code-block:: c++
+
+  {
+absl::Status status = call_some_function();
+  } // status.~Status() is called here
+
+This does not cause unused variable warning, but is likely to contain a bug.
+
+This check is not absolutely precise and aims to capture the most common scenarios like the one above.
\ No newline at end of file
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-

[PATCH] D138577: Use proper triple in CmdArgsSansAnalyses for html info files

2022-11-23 Thread Anthony Groyer via Phabricator via cfe-commits
angroyer added a reviewer: honggyu.kim.
angroyer added a comment.

Please review this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138577

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


[PATCH] D138426: Fix #58958 on github

2022-11-23 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

In D138426#3946202 , @krsch wrote:

> Should I change the title myself or you can change it during commit? If it's 
> on me, how do I change it? `git commit --amend; arc diff`?

phabricator isn't very elegant, locally changing the commit message doesn't 
propagate to phabricator even with `arc diff`, you have to change it on 
phabricator, then to propagate it locally `arc amend`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138426

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


[PATCH] D138426: Fix #58958 on github

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D138426#3947044 , @aeubanks wrote:

> In D138426#3946202 , @krsch wrote:
>
>> Should I change the title myself or you can change it during commit? If it's 
>> on me, how do I change it? `git commit --amend; arc diff`?
>
> phabricator isn't very elegant, locally changing the commit message doesn't 
> propagate to phabricator even with `arc diff`, you have to change it on 
> phabricator, then to propagate it locally `arc amend`

That's OK, I'll just change it when I commit - I've got something lined up but 
didn't get it through yesterday.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138426

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


[PATCH] D137149: Use PassGate from LLVMContext if any otherwise global one

2022-11-23 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks accepted this revision.
aeubanks added a comment.
This revision is now accepted and ready to land.

the precommit bot is still complaining that 
flang/lib/Frontend/FrontendActions.cpp needs to be updated

lgtm if the precommit bot doesn't show anything related to this patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137149

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


[PATCH] D137258: [clang] Optimize storage and lookup of analyzer options

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

Are you sure about the speedup?
When I looked at the implementation of the `StringSwitch`, it boiled down to an 
`if-else` chain under the hood.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137258

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


[PATCH] D137534: [C++20] [Modules] [ClangScanDeps] Allow clang-scan-deps to without specified compilation database in P1689 (3/3)

2022-11-23 Thread Ben Boeckel via Phabricator via cfe-commits
ben.boeckel added inline comments.



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:192
+"p1689-targeted-directory", llvm::cl::Optional,
+llvm::cl::desc("Only supported for P1689, the targeted directory of which "
+   "the dependencies are to be computed."),

I'm not sure what this means. Is it the compiler's working directory when 
compiling?



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:197
+llvm::cl::opt P1689TargetedCommand(
+"p1689-targeted-command", llvm::cl::Optional,
+llvm::cl::desc("Only supported for P1689, the targeted command of which "

Can this be something like `--` so that I don't have to figure out how to quote 
the thing (for the shell and whatever parsing Clang does internally)?


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

https://reviews.llvm.org/D137534

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


[PATCH] D138559: Record macro references in #ifdef clause.

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 477549.
VitaNuo added a comment.

Update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138559

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 //===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,72 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesConditionalMacroRefs) {
+   llvm::Annotations Header(R"cpp(
+#define Z 2
+  )cpp");
+
+  llvm::Annotations MainFile(R"cpp(
+#include "header.h"
+
+#define X 1
+
+#ifdef ^X
+ #define Y 2
+#endif
+
+#ifndef ^Z
+ #define W 3
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  Inputs.ExtraFiles["header.h"] = Header.code();
+  auto AST = build();
+
+  std::vector RefOffsets;
+  std::vector RefNames = {"X", "Z"};
+  SourceManager &SM = AST.sourceManager();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  for (auto I = 0u; I < Recorded.MacroReferences.size(); I++) {
+const auto &Ref = Recorded.MacroReferences[I];
+auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
+ASSERT_EQ(FID, SM.getMainFileID());
+EXPECT_EQ(Ref.RT, RefType::Ambiguous);
+EXPECT_EQ(RefNames[I], Ref.Target.macro().Name->getName());  
+RefOffsets.push_back(Off);
+  }
+  EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
+}
+
+TEST_F(RecordPPTest, CapturesIfNDefMacroRefs) {
+  llvm::Annotations Header(R"cpp(
+#define Z 2
+  )cpp");
+
+  llvm::Annotations MainFile(R"cpp(
+#include "header.h"
+
+#ifndef $def^Z
+ #define W 3
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  Inputs.ExtraFiles["header.h"] = Header.code();
+  auto AST = build();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  SourceManager &SM = AST.sourceManager();
+  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), MainFile.point("def"));
+
+  SymbolReference XRef = Recorded.MacroReferences.front();
+  EXPECT_EQ(XRef.RT, RefType::Ambiguous);
+  EXPECT_EQ("Z", XRef.Target.macro().Name->getName());
+  EXPECT_EQ(XRef.RefLocation, Def);
+}
+
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -53,7 +53,7 @@
 SourceRange Range, const MacroArgs *Args) override {
 if (!Active)
   return;
-recordMacroRef(MacroName, *MD.getMacroInfo());
+recordMacroRef(MacroName, *MD.getMacroInfo(), RefType::Explicit);
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override {
@@ -71,7 +71,7 @@
   llvm::is_contained(MI->params(), II))
 continue;
   if (const MacroInfo *MI = PP.getMacroInfo(II))
-recordMacroRef(Tok, *MI);
+recordMacroRef(Tok, *MI, RefType::Explicit);
 }
   }
 
@@ -80,17 +80,33 @@
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
-  recordMacroRef(MacroName, *MI);
+  recordMacroRef(MacroName, *MI, RefType::Explicit);
+  }
+
+  void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
+ const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
+  }
+
+  void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
+  const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
   }
 
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
 Recorded.MacroReferences.push_back(

[PATCH] D138387: [Clang] Implement static operator[]

2022-11-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 477550.
royjacobson added a comment.

Add a missing test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138387

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CXX/over/over.oper/p7.cpp
  clang/test/CodeGenCXX/cxx2b-static-call-operator.cpp
  clang/test/CodeGenCXX/cxx2b-static-subscript-operator.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1518,7 +1518,7 @@
 
   static operator[]
   https://wg21.link/P2589R1";>P2589R1
-  No
+  16
 
 
   Permitting static constexpr variables in constexpr functions (DR)
Index: clang/test/Lexer/cxx-features.cpp
===
--- clang/test/Lexer/cxx-features.cpp
+++ clang/test/Lexer/cxx-features.cpp
@@ -43,7 +43,7 @@
 #error "wrong value for __cpp_if_consteval"
 #endif
 
-#if check(multidimensional_subscript, 0, 0, 0, 0, 0, 202110)
+#if check(multidimensional_subscript, 0, 0, 0, 0, 0, 202211)
 #error "wrong value for __cpp_multidimensional_subscript"
 #endif
 
Index: clang/test/CodeGenCXX/cxx2b-static-subscript-operator.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/cxx2b-static-subscript-operator.cpp
@@ -0,0 +1,66 @@
+// RUN: %clang_cc1 -std=c++2b %s -emit-llvm -triple x86_64-linux -o - | FileCheck %s
+// RUN: %clang_cc1 -std=c++2b %s -emit-llvm -triple x86_64-windows-msvc -o - | FileCheck %s
+
+struct Functor {
+  static int operator[](int x, int y) {
+return x + y;
+  }
+};
+
+void call_static_subscript_operator() {
+  Functor f;
+  f[101, 102];
+  f.operator[](201, 202);
+  Functor{}[301, 302];
+  Functor::operator[](401, 402);
+}
+
+// CHECK:  define {{.*}}call_static_subscript_operator{{.*}}
+// CHECK-NEXT: entry:
+// CHECK:{{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 101, i32 noundef 102)
+// CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 201, i32 noundef 202)
+// CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 301, i32 noundef 302)
+// CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 401, i32 noundef 402)
+// CHECK-NEXT:   ret void
+// CHECK-NEXT: }
+
+struct FunctorConsteval {
+  consteval static int operator[](int x, int y) {
+  return x + y;
+  }
+};
+
+struct FunctorConstexpr {
+  constexpr static int operator[](int x, int y) {
+  return x + y;
+  }
+};
+
+void test_consteval_constexpr() {
+  int x = 0;
+  int y = FunctorConstexpr{}[x, 2];
+  constexpr int z1 = FunctorConsteval{}[2, 2];
+  constexpr int z2 = FunctorConstexpr{}[2, 2];
+  
+  static_assert(z1 == 4);
+  static_assert(z2 == 4);
+}
+
+template 
+struct DepFunctor {
+  static int operator[](T t) {
+return int(t);
+  }
+};
+
+void test_dep_functors() {
+  int x = DepFunctor{}[1.0f];
+  int y = DepFunctor{}[true];
+}
+
+// CHECK:  define {{.*}}test_dep_functors{{.*}}
+// CHECK-NEXT: entry:
+// CHECK:%call = call noundef i32 {{.*}}DepFunctor{{.*}}(float noundef 1.00e+00)
+// CHECK:%call1 = call noundef i32 {{.*}}DepFunctor{{.*}}(i1 noundef zeroext true)
+// CHECK:ret void
+// CHECK-NEXT: }
Index: clang/test/CodeGenCXX/cxx2b-static-call-operator.cpp
===
--- clang/test/CodeGenCXX/cxx2b-static-call-operator.cpp
+++ clang/test/CodeGenCXX/cxx2b-static-call-operator.cpp
@@ -28,6 +28,7 @@
   f(101, 102);
   f.operator()(201, 202);
   Functor{}(301, 302);
+  Functor::operator()(401, 402);
 }
 
 // CHECK:  define {{.*}}call_static_call_operator{{.*}}
@@ -35,6 +36,7 @@
 // CHECK:{{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 101, i32 noundef 102)
 // CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 201, i32 noundef 202)
 // CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 301, i32 noundef 302)
+// CHECK-NEXT:   {{.*}} = call noundef i32 {{.*}}Functor{{.*}}(i32 noundef 401, i32 noundef 402)
 // CHECK-NEXT:   ret void
 // CHECK-NEXT: }
 
Index: clang/test/CXX/over/over.oper/p7.cpp
===
--- clang/test/CXX/over/over.oper/p7.cpp
+++ clang/test/CXX/over/over.oper/p7.cpp
@@ -5,14 +5,19 @@
 
 struct Functor {
   static int operator()(int a, int b);
-  // cxx11-warning@-1 {{is a C++2b extension}}
-  // precxx2b-warning@-2 {{declaring overloaded 'operator()' as 'static' is a C++2b extension}}
+  static int operator[](int a1);
+  // cxx11-warning@-2 {{declaring overlo

[PATCH] D138559: Record macro references in #ifdef clause.

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 477551.
VitaNuo added a comment.

Remove the extra test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138559

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 //===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,45 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesConditionalMacroRefs) {
+   llvm::Annotations Header(R"cpp(
+#define Z 2
+  )cpp");
+
+  llvm::Annotations MainFile(R"cpp(
+#include "header.h"
+
+#define X 1
+
+#ifdef ^X
+ #define Y 2
+#endif
+
+#ifndef ^Z
+ #define W 3
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  Inputs.ExtraFiles["header.h"] = Header.code();
+  auto AST = build();
+
+  std::vector RefOffsets;
+  std::vector RefNames = {"X", "Z"};
+  SourceManager &SM = AST.sourceManager();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  for (auto I = 0u; I < Recorded.MacroReferences.size(); I++) {
+const auto &Ref = Recorded.MacroReferences[I];
+auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
+ASSERT_EQ(FID, SM.getMainFileID());
+EXPECT_EQ(Ref.RT, RefType::Ambiguous);
+EXPECT_EQ(RefNames[I], Ref.Target.macro().Name->getName());  
+RefOffsets.push_back(Off);
+  }
+  EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
+}
+
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -53,7 +53,7 @@
 SourceRange Range, const MacroArgs *Args) override {
 if (!Active)
   return;
-recordMacroRef(MacroName, *MD.getMacroInfo());
+recordMacroRef(MacroName, *MD.getMacroInfo(), RefType::Explicit);
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override {
@@ -71,7 +71,7 @@
   llvm::is_contained(MI->params(), II))
 continue;
   if (const MacroInfo *MI = PP.getMacroInfo(II))
-recordMacroRef(Tok, *MI);
+recordMacroRef(Tok, *MI, RefType::Explicit);
 }
   }
 
@@ -80,17 +80,33 @@
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
-  recordMacroRef(MacroName, *MI);
+  recordMacroRef(MacroName, *MI, RefType::Explicit);
+  }
+
+  void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
+ const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
+  }
+
+  void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
+  const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
   }
 
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
 Recorded.MacroReferences.push_back(
 SymbolReference{Tok.getLocation(),
 Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RefType::Explicit});
+RT});
   }
 
   bool Active = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138387: [Clang] Implement static operator[]

2022-11-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson marked 3 inline comments as done.
royjacobson added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:14462-14467
+  RLoc, CurFPFeatureOverrides());
+else
+  TheCall =
+  CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
+   RLoc, CurFPFeatureOverrides());
+

cor3ntin wrote:
> This looks weird, did you clang-format?
clang-format insists on this, personally I wouldn't write it like this either :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138387

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


[PATCH] D138387: [Clang] Implement static operator[]

2022-11-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson marked an inline comment as done.
royjacobson added a comment.

In D138387#3944211 , @cor3ntin wrote:

> Beside the formatting nitpick this looks good

Thanks! I'll wait until next week to let other people have a chance to take a 
look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138387

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


[PATCH] D138559: Record macro references in #ifdef clause.

2022-11-23 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 477554.
VitaNuo added a comment.

Make explicit RefType default.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138559

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -7,12 +7,13 @@
 //===--===//
 
 #include "clang-include-cleaner/Record.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -218,6 +219,45 @@
   EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
 }
 
+TEST_F(RecordPPTest, CapturesConditionalMacroRefs) {
+   llvm::Annotations Header(R"cpp(
+#define Z 2
+  )cpp");
+
+  llvm::Annotations MainFile(R"cpp(
+#include "header.h"
+
+#define X 1
+
+#ifdef ^X
+ #define Y 2
+#endif
+
+#ifndef ^Z
+ #define W 3
+#endif
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  Inputs.ExtraFiles["header.h"] = Header.code();
+  auto AST = build();
+
+  std::vector RefOffsets;
+  std::vector RefNames = {"X", "Z"};
+  SourceManager &SM = AST.sourceManager();
+  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
+
+  for (auto I = 0u; I < Recorded.MacroReferences.size(); I++) {
+const auto &Ref = Recorded.MacroReferences[I];
+auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
+ASSERT_EQ(FID, SM.getMainFileID());
+EXPECT_EQ(Ref.RT, RefType::Ambiguous);
+EXPECT_EQ(RefNames[I], Ref.Target.macro().Name->getName());  
+RefOffsets.push_back(Off);
+  }
+  EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
+}
+
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -83,14 +83,30 @@
   recordMacroRef(MacroName, *MI);
   }
 
+  void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
+ const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
+  }
+
+  void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
+  const MacroDefinition &MD) override {
+if (!Active)
+  return;
+if (const auto *MI = MD.getMacroInfo())
+  recordMacroRef(MacroNameTok, *MI, RefType::Ambiguous);
+  }
+
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT = RefType::Explicit) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
 Recorded.MacroReferences.push_back(
 SymbolReference{Tok.getLocation(),
 Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RefType::Explicit});
+RT});
   }
 
   bool Active = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138554: [clang][Interp] Use placement new to construct opcode arguments into bytecode vector

2022-11-23 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeEmitter.cpp:166
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+if constexpr (std::is_trivially_copyable_v) {
+  const char *Data = reinterpret_cast(&Val);

tbaeder wrote:
> sepavloff wrote:
> > Do we really need a separate case for trivially copyable types?
> It's not necessary, placement new'ing all everything works. I was just trying 
> to keep the old behavior as much as possible.
Another thing: when copy constructor for APFloat works, it can allocate data in 
heap. So the serialization is not perfect in this case. Would it be suitable 
for the interpretator?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138554

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


[PATCH] D137885: [modules] Support zstd in .pcm file

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Sounds good


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137885

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


[PATCH] D138552: [docs] Document that the modules can improve the linking time

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

I'm not sure I follow this - the comparison doesn't seem equal. If you wanted 
the modules-like code in non-modules, you could get it by having 
`notDirectlyUsed` declared-but-not-defined in the header file, and defined in 
the corresponding .cpp file, yeah?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138552

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


[PATCH] D138539: Use std::nullopt_t instead of NoneType (NFC)

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Sounds good to me, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138539

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


[PATCH] D138426: Fix #58958 on github

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2cea4c239570: Do not suggest taking the address of a const 
pointer to get void* (authored by krsch, committed by dblaikie).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138426

Files:
  clang/lib/Sema/SemaFixItUtils.cpp
  clang/test/FixIt/fixit-function-call.cpp


Index: clang/test/FixIt/fixit-function-call.cpp
===
--- clang/test/FixIt/fixit-function-call.cpp
+++ clang/test/FixIt/fixit-function-call.cpp
@@ -115,4 +115,25 @@
   u(c);
 }
 
+void accept_void(void*);
+
+void issue58958(const char* a, volatile char * v, const volatile char * cv) {
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(a);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(v);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(cv);
+char b;
+// CHECK: no matching function for call to 'accept_void'
+// CHECK: take the address of the argument with &
+accept_void(b);
+// CHECK-NOT: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(&b);
+}
+
 // CHECK: errors generated
Index: clang/lib/Sema/SemaFixItUtils.cpp
===
--- clang/lib/Sema/SemaFixItUtils.cpp
+++ clang/lib/Sema/SemaFixItUtils.cpp
@@ -124,7 +124,7 @@
 
   // Check if the pointer to the argument needs to be passed:
   //   (type -> type *) or (type & -> type *).
-  if (isa(ToQTy)) {
+  if (const auto *ToPtrTy = dyn_cast(ToQTy)) {
 bool CanConvert = false;
 OverloadFixItKind FixKind = OFIK_TakeAddress;
 
@@ -132,6 +132,10 @@
 if (!Expr->isLValue() || Expr->getObjectKind() != OK_Ordinary)
   return false;
 
+// Do no take address of const pointer to get void*
+if (isa(FromQTy) && ToPtrTy->isVoidPointerType())
+  return false;
+
 CanConvert = CompareTypes(S.Context.getPointerType(FromQTy), ToQTy, S,
   Begin, VK_PRValue);
 if (CanConvert) {


Index: clang/test/FixIt/fixit-function-call.cpp
===
--- clang/test/FixIt/fixit-function-call.cpp
+++ clang/test/FixIt/fixit-function-call.cpp
@@ -115,4 +115,25 @@
   u(c);
 }
 
+void accept_void(void*);
+
+void issue58958(const char* a, volatile char * v, const volatile char * cv) {
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(a);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(v);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(cv);
+char b;
+// CHECK: no matching function for call to 'accept_void'
+// CHECK: take the address of the argument with &
+accept_void(b);
+// CHECK-NOT: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(&b);
+}
+
 // CHECK: errors generated
Index: clang/lib/Sema/SemaFixItUtils.cpp
===
--- clang/lib/Sema/SemaFixItUtils.cpp
+++ clang/lib/Sema/SemaFixItUtils.cpp
@@ -124,7 +124,7 @@
 
   // Check if the pointer to the argument needs to be passed:
   //   (type -> type *) or (type & -> type *).
-  if (isa(ToQTy)) {
+  if (const auto *ToPtrTy = dyn_cast(ToQTy)) {
 bool CanConvert = false;
 OverloadFixItKind FixKind = OFIK_TakeAddress;
 
@@ -132,6 +132,10 @@
 if (!Expr->isLValue() || Expr->getObjectKind() != OK_Ordinary)
   return false;
 
+// Do no take address of const pointer to get void*
+if (isa(FromQTy) && ToPtrTy->isVoidPointerType())
+  return false;
+
 CanConvert = CompareTypes(S.Context.getPointerType(FromQTy), ToQTy, S,
   Begin, VK_PRValue);
 if (CanConvert) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2cea4c2 - Do not suggest taking the address of a const pointer to get void*

2022-11-23 Thread David Blaikie via cfe-commits

Author: Alexey Kreshchuk
Date: 2022-11-23T18:43:06Z
New Revision: 2cea4c239570c37f46ad0003b3d41d9473aca60f

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

LOG: Do not suggest taking the address of a const pointer to get void*

It's more likely the user needs a const cast, but probably not sure
enough that we should suggest that either - so err on the side of
caution and offer no suggestion.

Fixes pr58958

Reviewed By: dblaikie

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

Added: 


Modified: 
clang/lib/Sema/SemaFixItUtils.cpp
clang/test/FixIt/fixit-function-call.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaFixItUtils.cpp 
b/clang/lib/Sema/SemaFixItUtils.cpp
index 2910a56f866bb..2c85a53194301 100644
--- a/clang/lib/Sema/SemaFixItUtils.cpp
+++ b/clang/lib/Sema/SemaFixItUtils.cpp
@@ -124,7 +124,7 @@ bool ConversionFixItGenerator::tryToFixConversion(const 
Expr *FullExpr,
 
   // Check if the pointer to the argument needs to be passed:
   //   (type -> type *) or (type & -> type *).
-  if (isa(ToQTy)) {
+  if (const auto *ToPtrTy = dyn_cast(ToQTy)) {
 bool CanConvert = false;
 OverloadFixItKind FixKind = OFIK_TakeAddress;
 
@@ -132,6 +132,10 @@ bool ConversionFixItGenerator::tryToFixConversion(const 
Expr *FullExpr,
 if (!Expr->isLValue() || Expr->getObjectKind() != OK_Ordinary)
   return false;
 
+// Do no take address of const pointer to get void*
+if (isa(FromQTy) && ToPtrTy->isVoidPointerType())
+  return false;
+
 CanConvert = CompareTypes(S.Context.getPointerType(FromQTy), ToQTy, S,
   Begin, VK_PRValue);
 if (CanConvert) {

diff  --git a/clang/test/FixIt/fixit-function-call.cpp 
b/clang/test/FixIt/fixit-function-call.cpp
index 273e4a41ec8dd..88f636ea5859d 100644
--- a/clang/test/FixIt/fixit-function-call.cpp
+++ b/clang/test/FixIt/fixit-function-call.cpp
@@ -115,4 +115,25 @@ void dbcaller(A *ptra, B *ptrb, C &c, B &refb) {
   u(c);
 }
 
+void accept_void(void*);
+
+void issue58958(const char* a, volatile char * v, const volatile char * cv) {
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(a);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(v);
+// CHECK: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(cv);
+char b;
+// CHECK: no matching function for call to 'accept_void'
+// CHECK: take the address of the argument with &
+accept_void(b);
+// CHECK-NOT: no matching function for call to 'accept_void'
+// CHECK-NOT: take the address of the argument with &
+accept_void(&b);
+}
+
 // CHECK: errors generated



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


[PATCH] D137375: [AIX][pg] Add Correct Search Paths for Profiled Libraries

2022-11-23 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm accepted this revision.
cebowleratibm 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/D137375/new/

https://reviews.llvm.org/D137375

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


[PATCH] D137894: [clangd] Add extension for adding context (enclosing function or class) in references results

2022-11-23 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders updated this revision to Diff 477566.
tom-anders added a comment.

Add end-to-end test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137894

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h
  clang-tools-extra/clangd/test/references-container.test
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -302,6 +302,9 @@
 MATCHER_P(sym, Name, "") { return arg.Name == Name; }
 
 MATCHER_P(rangeIs, R, "") { return arg.Loc.range == R; }
+MATCHER_P(containerIs, C, "") {
+  return arg.Loc.containerName.value_or("") == C;
+}
 MATCHER_P(attrsAre, A, "") { return arg.Attributes == A; }
 MATCHER_P(hasID, ID, "") { return arg.ID == ID; }
 
@@ -1900,28 +1903,30 @@
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
-  for (const auto &R : T.ranges())
-ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+  for (const auto &[R, Context] : T.rangesWithPayload())
+ExpectedLocations.push_back(
+AllOf(rangeIs(R), containerIs(Context), attrsAre(0u)));
   // $def is actually shorthand for both definition and declaration.
   // If we have cases that are definition-only, we should change this.
-  for (const auto &R : T.ranges("def"))
-ExpectedLocations.push_back(
-AllOf(rangeIs(R), attrsAre(ReferencesResult::Definition |
-   ReferencesResult::Declaration)));
-  for (const auto &R : T.ranges("decl"))
-ExpectedLocations.push_back(
-AllOf(rangeIs(R), attrsAre(ReferencesResult::Declaration)));
-  for (const auto &R : T.ranges("overridedecl"))
+  for (const auto &[R, Context] : T.rangesWithPayload("def"))
+ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
+  attrsAre(ReferencesResult::Definition |
+   ReferencesResult::Declaration)));
+  for (const auto &[R, Context] : T.rangesWithPayload("decl"))
+ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
+  attrsAre(ReferencesResult::Declaration)));
+  for (const auto &[R, Context] : T.rangesWithPayload("overridedecl"))
 ExpectedLocations.push_back(AllOf(
-rangeIs(R),
+rangeIs(R), containerIs(Context),
 attrsAre(ReferencesResult::Declaration | ReferencesResult::Override)));
-  for (const auto &R : T.ranges("overridedef"))
-ExpectedLocations.push_back(
-AllOf(rangeIs(R), attrsAre(ReferencesResult::Declaration |
-   ReferencesResult::Definition |
-   ReferencesResult::Override)));
+  for (const auto &[R, Context] : T.rangesWithPayload("overridedef"))
+ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
+  attrsAre(ReferencesResult::Declaration |
+   ReferencesResult::Definition |
+   ReferencesResult::Override)));
   for (const auto &P : T.points()) {
-EXPECT_THAT(findReferences(AST, P, 0, UseIndex ? TU.index().get() : nullptr)
+EXPECT_THAT(findReferences(AST, P, 0, UseIndex ? TU.index().get() : nullptr,
+   /*AddContext*/ true)
 .References,
 UnorderedElementsAreArray(ExpectedLocations))
 << "Failed for Refs at " << P << "\n"
@@ -1933,18 +1938,18 @@
   const char *Tests[] = {
   R"cpp(// Local variable
 int main() {
-  int $def[[foo]];
-  [[^foo]] = 2;
-  int test1 = [[foo]];
+  int $def(main)[[foo]];
+  $(main)[[^foo]] = 2;
+  int test1 = $(main)[[foo]];
 }
   )cpp",
 
   R"cpp(// Struct
 namespace ns1 {
-struct $def[[Foo]] {};
+struct $def(ns1)[[Foo]] {};
 } // namespace ns1
 int main() {
-  ns1::[[Fo^o]]* Params;
+  ns1::$(main)[[Fo^o]]* Params;
 }
   )cpp",
 
@@ -1952,51 +1957,51 @@
 class $decl[[Foo]];
 class $def[[Foo]] {};
 int main() {
-  [[Fo^o]] foo;
+  $(main)[[Fo^o]] foo;
 }
   )cpp",
 
   R"cpp(// Function
 int $def[[foo]](int) {}
 int main() {
-  auto *X = &[[^foo]];
-  [[

[PATCH] D138597: DebugInfo: Add/support new DW_LANG codes for recent C and C++ versions

2022-11-23 Thread David Blaikie via Phabricator via cfe-commits
dblaikie created this revision.
dblaikie added reviewers: aprantl, probinson.
Herald added a reviewer: deadalnix.
Herald added a subscriber: hiraditya.
Herald added a project: All.
dblaikie requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This may be a breaking change for consumers if they're trying to detect
if code is C or C++, since it'll start using new codes that they may not
be ready to recognize, in which case they may fall back to non-C
handling.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138597

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-programming-language.c
  clang/test/CodeGenCXX/debug-info-programming-language.cpp
  llvm/include/llvm-c/DebugInfo.h
  llvm/include/llvm/BinaryFormat/Dwarf.def
  llvm/include/llvm/BinaryFormat/Dwarf.h
  llvm/lib/IR/DIBuilder.cpp

Index: llvm/lib/IR/DIBuilder.cpp
===
--- llvm/lib/IR/DIBuilder.cpp
+++ llvm/lib/IR/DIBuilder.cpp
@@ -156,7 +156,7 @@
 DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
 StringRef SysRoot, StringRef SDK) {
 
-  assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
+  assert(((Lang <= dwarf::DW_LANG_Ada2012 && Lang >= dwarf::DW_LANG_C89) ||
   (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
  "Invalid Language tag");
 
Index: llvm/include/llvm/BinaryFormat/Dwarf.h
===
--- llvm/include/llvm/BinaryFormat/Dwarf.h
+++ llvm/include/llvm/BinaryFormat/Dwarf.h
@@ -216,6 +216,8 @@
   case DW_LANG_C_plus_plus_03:
   case DW_LANG_C_plus_plus_11:
   case DW_LANG_C_plus_plus_14:
+  case DW_LANG_C_plus_plus_17:
+  case DW_LANG_C_plus_plus_20:
 result = true;
 break;
   case DW_LANG_C89:
@@ -256,6 +258,13 @@
   case DW_LANG_BORLAND_Delphi:
   case DW_LANG_lo_user:
   case DW_LANG_hi_user:
+  case DW_LANG_Kotlin:
+  case DW_LANG_Zig:
+  case DW_LANG_Crystal:
+  case DW_LANG_C17:
+  case DW_LANG_Fortran18:
+  case DW_LANG_Ada2005:
+  case DW_LANG_Ada2012:
 result = false;
 break;
   }
@@ -274,6 +283,7 @@
   case DW_LANG_Fortran95:
   case DW_LANG_Fortran03:
   case DW_LANG_Fortran08:
+  case DW_LANG_Fortran18:
 result = true;
 break;
   case DW_LANG_C89:
@@ -313,6 +323,14 @@
   case DW_LANG_BORLAND_Delphi:
   case DW_LANG_lo_user:
   case DW_LANG_hi_user:
+  case DW_LANG_Kotlin:
+  case DW_LANG_Zig:
+  case DW_LANG_Crystal:
+  case DW_LANG_C_plus_plus_17:
+  case DW_LANG_C_plus_plus_20:
+  case DW_LANG_C17:
+  case DW_LANG_Ada2005:
+  case DW_LANG_Ada2012:
 result = false;
 break;
   }
Index: llvm/include/llvm/BinaryFormat/Dwarf.def
===
--- llvm/include/llvm/BinaryFormat/Dwarf.def
+++ llvm/include/llvm/BinaryFormat/Dwarf.def
@@ -915,11 +915,22 @@
 HANDLE_DW_LANG(0x0023, Fortran08, 1, 5, DWARF)
 HANDLE_DW_LANG(0x0024, RenderScript, 0, 5, DWARF)
 HANDLE_DW_LANG(0x0025, BLISS, 0, 5, DWARF)
+// New since DWARF v5:
+HANDLE_DW_LANG(0x0026, Kotlin, 0, 0, DWARF)
+HANDLE_DW_LANG(0x0027, Zig, 0, 0, DWARF)
+HANDLE_DW_LANG(0x0028, Crystal, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002a, C_plus_plus_17, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002b, C_plus_plus_20, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002c, C17, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002d, Fortran18, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002e, Ada2005, 0, 0, DWARF)
+HANDLE_DW_LANG(0x002f, Ada2012, 0, 0, DWARF)
 // Vendor extensions:
 HANDLE_DW_LANG(0x8001, Mips_Assembler, None, 0, MIPS)
 HANDLE_DW_LANG(0x8e57, GOOGLE_RenderScript, 0, 0, GOOGLE)
 HANDLE_DW_LANG(0xb000, BORLAND_Delphi, 0, 0, BORLAND)
 
+
 // DWARF attribute type encodings.
 HANDLE_DW_ATE(0x01, address, 2, DWARF)
 HANDLE_DW_ATE(0x02, boolean, 2, DWARF)
Index: llvm/include/llvm-c/DebugInfo.h
===
--- llvm/include/llvm-c/DebugInfo.h
+++ llvm/include/llvm-c/DebugInfo.h
@@ -116,6 +116,15 @@
   LLVMDWARFSourceLanguageFortran08,
   LLVMDWARFSourceLanguageRenderScript,
   LLVMDWARFSourceLanguageBLISS,
+  LLVMDWARFSourceLanguageKotlin,
+  LLVMDWARFSourceLanguageZig,
+  LLVMDWARFSourceLanguageCrystal,
+  LLVMDWARFSourceLanguageC_plus_plus_17,
+  LLVMDWARFSourceLanguageC_plus_plus_20,
+  LLVMDWARFSourceLanguageC17,
+  LLVMDWARFSourceLanguageFortran18,
+  LLVMDWARFSourceLanguageAda2005,
+  LLVMDWARFSourceLanguageAda2012,
   // Vendor extensions:
   LLVMDWARFSourceLanguageMips_Assembler,
   LLVMDWARFSourceLanguageGOOGLE_RenderScript,
Index: clang/test/CodeGenCXX/debug-info-programming-language.cpp
===
--- clang/test/CodeGenCXX/debug-info-programming-language.cpp
+++ clang/test/CodeGenCXX/debug-info-programming-language.cpp
@@ -4,6 +4,12 @@
 // RUN: %clang_cc1 -dwarf-version=3 -emit-llvm -triple %itanium_abi_triple %s -o - \
 // 

  1   2   >