[PATCH] D144540: [Clang] [Doc] Explicitly note noreturn bug as a miscompilation

2023-02-22 Thread Sam James via Phabricator via cfe-commits
thesamesam created this revision.
thesamesam added a reviewer: aaron.ballman.
Herald added a project: All.
thesamesam requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is for 16.x.

Bug: https://github.com/llvm/llvm-project/issues/59792


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144540

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -345,7 +345,7 @@
   character sequence that differed from the primary source file.
   `Issue 59736 `_
 - In C mode, when ``e1`` has ``__attribute__((noreturn))`` but ``e2`` doesn't,
-  ``(c ? e1 : e2)`` is no longer considered noreturn.
+  ``(c ? e1 : e2)`` is no longer considered noreturn, fixing a miscompilation.
   `Issue 59792 `_
 - Fix an issue that makes Clang crash on lambda template parameters. This fixes
   `Issue 57960 `_


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -345,7 +345,7 @@
   character sequence that differed from the primary source file.
   `Issue 59736 `_
 - In C mode, when ``e1`` has ``__attribute__((noreturn))`` but ``e2`` doesn't,
-  ``(c ? e1 : e2)`` is no longer considered noreturn.
+  ``(c ? e1 : e2)`` is no longer considered noreturn, fixing a miscompilation.
   `Issue 59792 `_
 - Fix an issue that makes Clang crash on lambda template parameters. This fixes
   `Issue 57960 `_
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143984: [DebugMetadata] Simplify handling subprogram's retainedNodes field. NFCI (1/7)

2023-02-22 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb added a comment.

@jmmartinez thank you for looking at this!




Comment at: llvm/lib/IR/DIBuilder.cpp:789
+  return createLocalVariable(
+  VMContext, getSubprogramNodesTrackingVector(Scope), Scope, Name,
+  /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, Flags, AlignInBits);

jmmartinez wrote:
> I'll be tempted to move the call to `getSubprogramNodesTrackingVector(Scope)` 
> into `createLocalVariable`. It seems that every time `createLocalVariable` is 
> called, `getSubprogramNodesTrackingVector(Scope)` is passed as value for 
> `PreservedNodes`.
> 
> (I've just started reviewing so I may be missing some other modifications)
That's right, but the problem is in the fact that `createLocalVariable()` is 
static while `getSubprogramNodesTrackingVector()` is a DIBuilder's member. To 
move the call inside `createLocalVariable()` we need either to make it a member 
of DIBuilder or to pass DIBuilder object to it. None of these options looks 
much better to me, honestly. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143984

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


[PATCH] D143666: [Clang] Fix clang_rt tests when LLVM_ENABLE_PER_TARGET_RUNTIME_DIR is ON

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

Hi Petr,
In LLVM Embedded Toolchain for Arm we put libclang_rt in the regular library 
directory, not the resource dir. Therefore `-resource-dir` has no effect for us.
Instead of this change, I could have added a `--sysroot` argument to each test, 
but this change seemed to fit well with the discussion in 
https://discourse.llvm.org/t/rfc-time-to-drop-legacy-runtime-paths/64628.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143666

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


[PATCH] D143666: [Clang] Fix clang_rt tests when LLVM_ENABLE_PER_TARGET_RUNTIME_DIR is ON

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

I'm happy to revert this and add `--sysroot` if you prefer. That would fit with 
keeping the tests hermetic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143666

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


[clang] 8498ba6 - [clang] Add the check of membership for the issue #58674 and improve the lookup process

2023-02-22 Thread Liming Liu via cfe-commits

Author: Liming Liu
Date: 2023-02-22T16:43:50+08:00
New Revision: 8498ba6c2860c838183f9951b63df26ab5f02265

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

LOG: [clang] Add the check of membership for the issue #58674 and improve the 
lookup process

This patch includes the commit 01adf96ebc86 and a fix of unhandled declaration
references.

When looking up base classes, Clang first checks whether a base class is a
template and takes the specialized template based on it. However, the base class
might be instantiated, and the above behavior can lose information.

This patch fixes the problem by first checking whether a base class is a record
declaration, so the instantiated one will be taken.

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

Added: 
clang/test/CodeGenCXX/decl-ref-inheritance.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/DeclCXX.h
clang/lib/AST/CXXInheritance.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/decltype.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 640317e32fe70..24ceac59a96a2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -165,6 +165,9 @@ Bug Fixes to C++ Support
 - Fix crash when evaluating consteval constructor of derived class whose base
   has more than one field.
   (`#60166 `_)
+- Fix an issue about ``decltype`` in the members of class templates derived 
from
+  templates with related parameters.
+  (`#58674 `_)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 11276c77490ce..8909acc71c0a3 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1546,8 +1546,11 @@ class CXXRecordDecl : public RecordDecl {
   ///
   /// \param Base the base class we are searching for.
   ///
+  /// \param LookupInDependentTypes whether to look up in dependent types.
+  ///
   /// \returns true if this class is derived from Base, false otherwise.
-  bool isDerivedFrom(const CXXRecordDecl *Base) const;
+  bool isDerivedFrom(const CXXRecordDecl *Base,
+ bool LookupInDependentTypes = false) const;
 
   /// Determine whether this class is derived from the type \p Base.
   ///
@@ -1561,11 +1564,14 @@ class CXXRecordDecl : public RecordDecl {
   /// \param Paths will contain the paths taken from the current class to the
   /// given \p Base class.
   ///
+  /// \param LookupInDependentTypes whether to look up independent types.
+  ///
   /// \returns true if this class is derived from \p Base, false otherwise.
   ///
   /// \todo add a separate parameter to configure IsDerivedFrom, rather than
   /// tangling input and output in \p Paths
-  bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
+  bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths,
+ bool LookupInDependentTypes = false) const;
 
   /// Determine whether this class is virtually derived from
   /// the class \p Base.

diff  --git a/clang/lib/AST/CXXInheritance.cpp 
b/clang/lib/AST/CXXInheritance.cpp
index 25de2a20a7f3b..32b17fc64a463 100644
--- a/clang/lib/AST/CXXInheritance.cpp
+++ b/clang/lib/AST/CXXInheritance.cpp
@@ -64,14 +64,16 @@ void CXXBasePaths::swap(CXXBasePaths &Other) {
   std::swap(DetectedVirtual, Other.DetectedVirtual);
 }
 
-bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
+bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
+  bool LookupInDependentTypes) const {
   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
  /*DetectVirtual=*/false);
-  return isDerivedFrom(Base, Paths);
+  return isDerivedFrom(Base, Paths, LookupInDependentTypes);
 }
 
 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
-  CXXBasePaths &Paths) const {
+  CXXBasePaths &Paths,
+  bool LookupInDependentTypes) const {
   if (getCanonicalDecl() == Base->getCanonicalDecl())
 return false;
 
@@ -83,7 +85,7 @@ bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
 return Specifier->getType()->getAsRecordDecl() &&
FindBaseClass(Specifier, Path, BaseDecl);
   },
-  Paths);
+  Paths, LookupInDependentTypes);
 }
 
 bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
@@ -246,17 +248,16 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context,
 } else if (VisitBase) {
   CXXRecordDecl *BaseRecord;
   if (Looku

[PATCH] D143840: [clang] Add the check of membership for the issue #58674 and improve the lookup process

2023-02-22 Thread Liming Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8498ba6c2860: [clang] Add the check of membership for the 
issue #58674 and improve the lookup… (authored by lime).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143840

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/lib/AST/CXXInheritance.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGenCXX/decl-ref-inheritance.cpp
  clang/test/SemaCXX/decltype.cpp

Index: clang/test/SemaCXX/decltype.cpp
===
--- clang/test/SemaCXX/decltype.cpp
+++ clang/test/SemaCXX/decltype.cpp
@@ -101,6 +101,44 @@
   template void foo(decltype(T(LP1{ .p1 = g1, .p1.x[1] = 'x' }))) {}
 }
 
+namespace GH58674 {
+  struct Foo {
+float value_;
+struct nested {
+  float value_;
+};
+  };
+
+  template 
+  struct TemplateFoo {
+float value_;
+  };
+
+  float bar;
+
+  template 
+  struct Animal{};
+
+  template 
+  class Cat : Animal {
+using okay = decltype(Foo::value_);
+using also_okay = decltype(bar);
+using okay2 = decltype(Foo::nested::value_);
+using okay3 = decltype(TemplateFoo::value_);
+  public:
+void meow() {
+  using okay = decltype(Foo::value_);
+  using also_okay = decltype(bar);
+  using okay2 = decltype(Foo::nested::value_);
+  using okay3 = decltype(TemplateFoo::value_);
+}
+  };
+
+  void baz() {
+  Cat{}.meow();
+  }
+}
+
 template
 class conditional {
 };
Index: clang/test/CodeGenCXX/decl-ref-inheritance.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/decl-ref-inheritance.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: [[FOO:%.+]] = type { i32 }
+struct foo {
+  int val;
+};
+
+template  struct bar : T {
+};
+
+struct baz : bar {
+  // CHECK-LABEL: define{{.*}} i32 @_ZN3baz3getEv
+  // CHECK: {{%.+}} = getelementptr inbounds [[FOO]], ptr {{%.+}}, i32 0, i32 0
+  int get() {
+return val;
+  }
+};
+
+int qux() {
+  auto f = baz{};
+  return f.get();
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -2698,20 +2698,36 @@
   // to get this right here so that we don't end up making a
   // spuriously dependent expression if we're inside a dependent
   // instance method.
+  //
+  // We also don't need to do this if R resolved to a member in another
+  // class, which can happen in an unevaluated operand:
+  //
+  // C++ [expr.prim.id]p3.3:
+  //   If that id-expression denotes a non-static data member and it
+  //   appears in an unevaluated operand.
   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
-bool MightBeImplicitMember;
-if (!IsAddressOfOperand)
-  MightBeImplicitMember = true;
-else if (!SS.isEmpty())
-  MightBeImplicitMember = false;
-else if (R.isOverloadedResult())
-  MightBeImplicitMember = false;
-else if (R.isUnresolvableResult())
-  MightBeImplicitMember = true;
-else
-  MightBeImplicitMember = isa(R.getFoundDecl()) ||
-  isa(R.getFoundDecl()) ||
-  isa(R.getFoundDecl());
+bool MightBeImplicitMember = true, CheckField = true;
+if (IsAddressOfOperand) {
+  MightBeImplicitMember = SS.isEmpty() && !R.isOverloadedResult();
+  CheckField = !R.isUnresolvableResult();
+}
+if (MightBeImplicitMember && CheckField) {
+  if (R.isSingleResult() &&
+  isa(R.getFoundDecl())) {
+auto Class = cast((*R.begin())->getDeclContext());
+for (auto Curr = S->getLookupEntity(); Curr && !Curr->isFileContext();
+ Curr = Curr->getParent()) {
+  if (auto ThisClass = dyn_cast_if_present(Curr)) {
+if ((MightBeImplicitMember =
+ ThisClass->Equals(Class) ||
+ ThisClass->isDerivedFrom(Class,
+  /*LookupIndependent=*/true)))
+  break;
+  }
+}
+  } else if (IsAddressOfOperand)
+MightBeImplicitMember = false;
+}
 
 if (MightBeImplicitMember)
   return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
Index: clang/lib/AST/CXXInheritance.cpp
===
--- clang/lib/AST/CXXInheritance.cpp
+++ clang/lib/AST/CXXInheritance.cpp
@@ -64,14 +64,16 @@
   std::swap(DetectedVirtual, Other.DetectedVirtual);
 }
 
-bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
+bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
+  bool LookupInDependentTypes) const {
   CXXBasePaths Paths

[PATCH] D144054: [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

2023-02-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Lex/TokenLexer.cpp:1029
+  // Including Limit will not mischeck for across-file-id tokens
+  // because SourceManager allocates FileSize + 1 for each SLocEntry.
+  //

Naively, it seems like if recovery tokens could lead us to read 
one-past-the-end, it could also cause us to read two-past-the-end in which case 
this check would fail.

We're relying on this never happening, so I think the comment should refer more 
specifically to the tokens that get inserted.

Maybe "recovery only ever inserts a single token past the end of the FileID, 
specifically the `)` when a macro-arg containing a comma should be guarded by 
parentheses"?



Comment at: clang/lib/Lex/TokenLexer.cpp:1031
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit

hokein wrote:
> shafik wrote:
> > I don't believe we include links to issues in comments but you should 
> > definitely add the information to the commit message and when folks look at 
> > the commit they can get the that context there.
> I'm happy to remove it. But is there any guideline discouraging this 
> practise? I have already seen this pattern in LLVM project. I think this is 
> based on the author's judgement (IMO, it seems better to keep it for this 
> case).
I see 50+ refs to github issues, 70+ links to bugs.llvm.org, 1K+ references to 
PRN.
The reference seems useful when it's a strange workaround like this.



Comment at: clang/test/Lexer/update_consecutive_macro_crash.cpp:8
+void foo() {
+  X(int{,}); // expected-error {{too many arguments provided to function-like 
macro invocation}} \
+ expected-error {{expected expression}} \

hokein wrote:
> More details about the issue :
> 
> - due to the error recovery, the clang lexer inserts a pair of `()` around 
> the macro argument `int{,}`, so we will see [`(`, `int`, `{`, `,`, `}`, `)`] 
> tokens
> - however, the size of file id for the macro argument only take account the 
> written tokens which are [`int`, `{`, `,`, `}`], and the extra inserted `)` 
> token is at the `Limit` source location which triggers an empty `Partition`. 
can you add these as comments to the test?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144054

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


[PATCH] D143666: [Clang] Fix clang_rt tests when LLVM_ENABLE_PER_TARGET_RUNTIME_DIR is ON

2023-02-22 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D143666#4143702 , @michaelplatings 
wrote:

> I'm happy to revert this and add `--sysroot` if you prefer. That would fit 
> with keeping the tests hermetic.

That would be my preference and it would match what we do in other Clang tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143666

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


[PATCH] D144542: [Clang] Improve hermeticity of clang_rt tests

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings created this revision.
michaelplatings added a reviewer: phosek.
Herald added a project: All.
michaelplatings requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Specifying --sysroot prevents libclang_rt from being located in standard
library directories.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144542

Files:
  clang/test/Driver/arm-compiler-rt.c
  clang/test/Driver/print-libgcc-file-name-clangrt.c

Index: clang/test/Driver/print-libgcc-file-name-clangrt.c
===
--- clang/test/Driver/print-libgcc-file-name-clangrt.c
+++ clang/test/Driver/print-libgcc-file-name-clangrt.c
@@ -2,55 +2,64 @@
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=x86_64-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-X8664 %s
-// CHECK-CLANGRT-X8664: libclang_rt.builtins{{(-x86_64)?}}.a
+// CHECK-CLANGRT-X8664: libclang_rt.builtins-x86_64.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=i386-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-I386 %s
-// CHECK-CLANGRT-I386: libclang_rt.builtins{{(-i386)?}}.a
+// CHECK-CLANGRT-I386: libclang_rt.builtins-i386.a
 
 // Check whether alternate arch values map to the correct library.
 //
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=i686-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-I386 %s
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM %s
-// CHECK-CLANGRT-ARM: libclang_rt.builtins{{(-arm)?}}.a
+// CHECK-CLANGRT-ARM: libclang_rt.builtins-arm.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-androideabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-ANDROID %s
 // CHECK-CLANGRT-ARM-ANDROID: libclang_rt.builtins-arm-android.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabihf \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARMHF %s
-// CHECK-CLANGRT-ARMHF: libclang_rt.builtins{{(-armhf)?}}.a
+// CHECK-CLANGRT-ARMHF: libclang_rt.builtins-armhf.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabi -mfloat-abi=hard \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-ABI %s
-// CHECK-CLANGRT-ARM-ABI: libclang_rt.builtins{{(-armhf)?}}.a
+// CHECK-CLANGRT-ARM-ABI: libclang_rt.builtins-armhf.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=armv7m-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-BAREMETAL %s
-// CHECK-CLANGRT-ARM-BAREMETAL: libclang_rt.builtins{{(-armv7m)?}}.a
+// CHECK-CLANGRT-ARM-BAREMETAL: libclang_rt.builtins-armv7m.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=armv7m-vendor-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-BAREMETAL-PER-TARGET %s
 // CHECK-CLANGRT-ARM-BAREMETAL-PER-TARGET: libclang_rt.builtins.a
Index: clang/test/Driver/arm-compiler-rt.c
===
--- clang/test/Driver/arm-compiler-rt.c
+++ clang/test/Driver/arm-compiler-rt.c
@@ -1,48 +1,56 @@
 // RUN: %clang -target arm-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-EABI
-// ARM-EABI: "-lclang_rt.builtins{{(-arm)?}}"
+// ARM-EAB

[PATCH] D143666: [Clang] Fix clang_rt tests when LLVM_ENABLE_PER_TARGET_RUNTIME_DIR is ON

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

https://reviews.llvm.org/D144542


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143666

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


[PATCH] D144217: [clang-tidy] Fix false-positive in readability-container-size-empty

2023-02-22 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:101
+  IgnoreComparisonForTypesRegexp(
+  Options.get("IgnoreComparisonForTypesRegexp", "^::std::array")) {}
+

carlosgalvezp wrote:
> I also realize that in other checks, this is typically implemented as a list 
> (comma or semicolon-separated) instead of a regex. Would it make sense to do 
> that here as well, for consistency? As a user I would also find it easier and 
> more intuitive to type a list than to have to google how to create a list 
> using regex :) 
I usually prefer regexp, as it allow more flexibility (like matching 
templates), but I can change this to use semicolon separated list, in this case 
it would also do a job.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144217

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


[PATCH] D144542: [Clang] Improve hermeticity of clang_rt tests

2023-02-22 Thread Petr Hosek via Phabricator via cfe-commits
phosek accepted this revision.
phosek added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144542

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


[PATCH] D144054: [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

2023-02-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 499405.
hokein marked 2 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144054

Files:
  clang/lib/Lex/TokenLexer.cpp
  clang/test/Lexer/update_consecutive_macro_crash.cpp


Index: clang/test/Lexer/update_consecutive_macro_crash.cpp
===
--- /dev/null
+++ clang/test/Lexer/update_consecutive_macro_crash.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -fsyntax-only -verify %s 2>&1
+
+#define X(val2) Y(val2++) // expected-note {{macro 'X' defined here}}
+#define Y(expression) expression ;
+
+void foo() {
+  // https://github.com/llvm/llvm-project/issues/60722:
+  //
+  // - Due to to the error recovery, the lexer inserts a pair of () around the
+  //   macro argument int{,}, so we will see [(, int, {, ,, }, )] tokens.
+  // - however, the size of file id for the macro argument only takes account
+  //   the written tokens  int{,} , and the extra inserted ) token points to 
the
+  //Limit source location which triggered an empty Partition violation.
+  X(int{,}); // expected-error {{too many arguments provided to function-like 
macro invocation}} \
+ expected-error {{expected expression}} \
+ expected-note {{parentheses are required around macro 
argument containing braced initializer list}}
+}
Index: clang/lib/Lex/TokenLexer.cpp
===
--- clang/lib/Lex/TokenLexer.cpp
+++ clang/lib/Lex/TokenLexer.cpp
@@ -1019,8 +1019,16 @@
 SourceLocation Limit =
 SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! The lexer recovery only ever inserts a
+  // single token past the end of the FileID, specifically the ) when a
+  // macro-arg containing a comma should be guarded by parentheses.
+  //
+  // It is safe to include the Limit here because SourceManager allocates
+  // FileSize + 1 for each SLocEntry.
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
+ &&  NearLast(T.getLocation());
 });
   }
   assert(!Partition.empty());


Index: clang/test/Lexer/update_consecutive_macro_crash.cpp
===
--- /dev/null
+++ clang/test/Lexer/update_consecutive_macro_crash.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -fsyntax-only -verify %s 2>&1
+
+#define X(val2) Y(val2++) // expected-note {{macro 'X' defined here}}
+#define Y(expression) expression ;
+
+void foo() {
+  // https://github.com/llvm/llvm-project/issues/60722:
+  //
+  // - Due to to the error recovery, the lexer inserts a pair of () around the
+  //   macro argument int{,}, so we will see [(, int, {, ,, }, )] tokens.
+  // - however, the size of file id for the macro argument only takes account
+  //   the written tokens  int{,} , and the extra inserted ) token points to the
+  //Limit source location which triggered an empty Partition violation.
+  X(int{,}); // expected-error {{too many arguments provided to function-like macro invocation}} \
+ expected-error {{expected expression}} \
+ expected-note {{parentheses are required around macro argument containing braced initializer list}}
+}
Index: clang/lib/Lex/TokenLexer.cpp
===
--- clang/lib/Lex/TokenLexer.cpp
+++ clang/lib/Lex/TokenLexer.cpp
@@ -1019,8 +1019,16 @@
 SourceLocation Limit =
 SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! The lexer recovery only ever inserts a
+  // single token past the end of the FileID, specifically the ) when a
+  // macro-arg containing a comma should be guarded by parentheses.
+  //
+  // It is safe to include the Limit here because SourceManager allocates
+  // FileSize + 1 for each SLocEntry.
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
+ &&  NearLast(T.getLocation());
 });
   }
   assert(!Partition.empty());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 341dd60 - [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

2023-02-22 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-22T10:16:02+01:00
New Revision: 341dd6076b123946f79a3148b660d6579f9683a7

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

LOG: [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

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

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

Added: 
clang/test/Lexer/update_consecutive_macro_crash.cpp

Modified: 
clang/lib/Lex/TokenLexer.cpp

Removed: 




diff  --git a/clang/lib/Lex/TokenLexer.cpp b/clang/lib/Lex/TokenLexer.cpp
index e0cd77b0db8f0..856d5682727fe 100644
--- a/clang/lib/Lex/TokenLexer.cpp
+++ b/clang/lib/Lex/TokenLexer.cpp
@@ -1019,8 +1019,16 @@ static void 
updateConsecutiveMacroArgTokens(SourceManager &SM,
 SourceLocation Limit =
 SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! The lexer recovery only ever inserts a
+  // single token past the end of the FileID, specifically the ) when a
+  // macro-arg containing a comma should be guarded by parentheses.
+  //
+  // It is safe to include the Limit here because SourceManager allocates
+  // FileSize + 1 for each SLocEntry.
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
+ &&  NearLast(T.getLocation());
 });
   }
   assert(!Partition.empty());

diff  --git a/clang/test/Lexer/update_consecutive_macro_crash.cpp 
b/clang/test/Lexer/update_consecutive_macro_crash.cpp
new file mode 100644
index 0..c66e734a4894f
--- /dev/null
+++ b/clang/test/Lexer/update_consecutive_macro_crash.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -fsyntax-only -verify %s 2>&1
+
+#define X(val2) Y(val2++) // expected-note {{macro 'X' defined here}}
+#define Y(expression) expression ;
+
+void foo() {
+  // https://github.com/llvm/llvm-project/issues/60722:
+  //
+  // - Due to to the error recovery, the lexer inserts a pair of () around the
+  //   macro argument int{,}, so we will see [(, int, {, ,, }, )] tokens.
+  // - however, the size of file id for the macro argument only takes account
+  //   the written tokens  int{,} , and the extra inserted ) token points to 
the
+  //Limit source location which triggered an empty Partition violation.
+  X(int{,}); // expected-error {{too many arguments provided to function-like 
macro invocation}} \
+ expected-error {{expected expression}} \
+ expected-note {{parentheses are required around macro 
argument containing braced initializer list}}
+}



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


[PATCH] D144054: [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

2023-02-22 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG341dd6076b12: [Lex] Fix a crash in 
updateConsecutiveMacroArgTokens. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144054

Files:
  clang/lib/Lex/TokenLexer.cpp
  clang/test/Lexer/update_consecutive_macro_crash.cpp


Index: clang/test/Lexer/update_consecutive_macro_crash.cpp
===
--- /dev/null
+++ clang/test/Lexer/update_consecutive_macro_crash.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -fsyntax-only -verify %s 2>&1
+
+#define X(val2) Y(val2++) // expected-note {{macro 'X' defined here}}
+#define Y(expression) expression ;
+
+void foo() {
+  // https://github.com/llvm/llvm-project/issues/60722:
+  //
+  // - Due to to the error recovery, the lexer inserts a pair of () around the
+  //   macro argument int{,}, so we will see [(, int, {, ,, }, )] tokens.
+  // - however, the size of file id for the macro argument only takes account
+  //   the written tokens  int{,} , and the extra inserted ) token points to 
the
+  //Limit source location which triggered an empty Partition violation.
+  X(int{,}); // expected-error {{too many arguments provided to function-like 
macro invocation}} \
+ expected-error {{expected expression}} \
+ expected-note {{parentheses are required around macro 
argument containing braced initializer list}}
+}
Index: clang/lib/Lex/TokenLexer.cpp
===
--- clang/lib/Lex/TokenLexer.cpp
+++ clang/lib/Lex/TokenLexer.cpp
@@ -1019,8 +1019,16 @@
 SourceLocation Limit =
 SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! The lexer recovery only ever inserts a
+  // single token past the end of the FileID, specifically the ) when a
+  // macro-arg containing a comma should be guarded by parentheses.
+  //
+  // It is safe to include the Limit here because SourceManager allocates
+  // FileSize + 1 for each SLocEntry.
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
+ &&  NearLast(T.getLocation());
 });
   }
   assert(!Partition.empty());


Index: clang/test/Lexer/update_consecutive_macro_crash.cpp
===
--- /dev/null
+++ clang/test/Lexer/update_consecutive_macro_crash.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -fsyntax-only -verify %s 2>&1
+
+#define X(val2) Y(val2++) // expected-note {{macro 'X' defined here}}
+#define Y(expression) expression ;
+
+void foo() {
+  // https://github.com/llvm/llvm-project/issues/60722:
+  //
+  // - Due to to the error recovery, the lexer inserts a pair of () around the
+  //   macro argument int{,}, so we will see [(, int, {, ,, }, )] tokens.
+  // - however, the size of file id for the macro argument only takes account
+  //   the written tokens  int{,} , and the extra inserted ) token points to the
+  //Limit source location which triggered an empty Partition violation.
+  X(int{,}); // expected-error {{too many arguments provided to function-like macro invocation}} \
+ expected-error {{expected expression}} \
+ expected-note {{parentheses are required around macro argument containing braced initializer list}}
+}
Index: clang/lib/Lex/TokenLexer.cpp
===
--- clang/lib/Lex/TokenLexer.cpp
+++ clang/lib/Lex/TokenLexer.cpp
@@ -1019,8 +1019,16 @@
 SourceLocation Limit =
 SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! The lexer recovery only ever inserts a
+  // single token past the end of the FileID, specifically the ) when a
+  // macro-arg containing a comma should be guarded by parentheses.
+  //
+  // It is safe to include the Limit here because SourceManager allocates
+  // FileSize + 1 for each SLocEntry.
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
+ &&  NearLast(T.getLocation());
 });
   }
   assert(!Partition.empty());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 67e28a3 - [Clang] Improve hermeticity of clang_rt tests

2023-02-22 Thread Michael Platings via cfe-commits

Author: Michael Platings
Date: 2023-02-22T09:23:10Z
New Revision: 67e28a3010e1852ec670cf5346fd171bf2a16774

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

LOG: [Clang] Improve hermeticity of clang_rt tests

Specifying --sysroot prevents libclang_rt from being located in standard
library directories.

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

Added: 


Modified: 
clang/test/Driver/arm-compiler-rt.c
clang/test/Driver/print-libgcc-file-name-clangrt.c

Removed: 




diff  --git a/clang/test/Driver/arm-compiler-rt.c 
b/clang/test/Driver/arm-compiler-rt.c
index b31e210b0376f..8b9bcfe778097 100644
--- a/clang/test/Driver/arm-compiler-rt.c
+++ b/clang/test/Driver/arm-compiler-rt.c
@@ -1,48 +1,56 @@
 // RUN: %clang -target arm-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-EABI
-// ARM-EABI: "-lclang_rt.builtins{{(-arm)?}}"
+// ARM-EABI: "-lclang_rt.builtins-arm"
 
 // RUN: %clang -target arm-linux-gnueabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-GNUEABI
-// ARM-GNUEABI: "{{.*[/\\]}}libclang_rt.builtins{{(-arm)?}}.a"
+// ARM-GNUEABI: "{{.*[/\\]}}libclang_rt.builtins-arm.a"
 
 // RUN: %clang -target arm-linux-gnueabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -mfloat-abi=hard -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-GNUEABI-ABI
-// ARM-GNUEABI-ABI: "{{.*[/\\]}}libclang_rt.builtins{{(-armhf)?}}.a"
+// ARM-GNUEABI-ABI: "{{.*[/\\]}}libclang_rt.builtins-armhf.a"
 
 // RUN: %clang -target arm-linux-gnueabihf \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-GNUEABIHF
-// ARM-GNUEABIHF: "{{.*[/\\]}}libclang_rt.builtins{{(-armhf)?}}.a"
+// ARM-GNUEABIHF: "{{.*[/\\]}}libclang_rt.builtins-armhf.a"
 
 // RUN: %clang -target arm-linux-gnueabihf \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -mfloat-abi=soft -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-GNUEABIHF-ABI
-// ARM-GNUEABIHF-ABI: "{{.*[/\\]}}libclang_rt.builtins{{(-arm)?}}.a"
+// ARM-GNUEABIHF-ABI: "{{.*[/\\]}}libclang_rt.builtins-arm.a"
 
 // RUN: %clang -target arm-windows-itanium \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-WINDOWS
-// ARM-WINDOWS: "{{.*[/\\]}}clang_rt.builtins{{(-arm)?}}.lib"
+// ARM-WINDOWS: "{{.*[/\\]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clang -target arm-linux-androideabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-ANDROID
-// ARM-ANDROID: "{{.*[/\\]}}libclang_rt.builtins{{(-arm-android)?}}.a"
+// ARM-ANDROID: "{{.*[/\\]}}libclang_rt.builtins-arm-android.a"
 
 // RUN: %clang -target arm-linux-androideabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -mfloat-abi=hard -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-ANDROIDHF
-// ARM-ANDROIDHF: "{{.*[/\\]}}libclang_rt.builtins{{(-armhf-android)?}}.a"
+// ARM-ANDROIDHF: "{{.*[/\\]}}libclang_rt.builtins-armhf-android.a"
 

diff  --git a/clang/test/Driver/print-libgcc-file-name-clangrt.c 
b/clang/test/Driver/print-libgcc-file-name-clangrt.c
index 6e6e73213c212..d5e7c48dde296 100644
--- a/clang/test/Driver/print-libgcc-file-name-clangrt.c
+++ b/clang/test/Driver/print-libgcc-file-name-clangrt.c
@@ -2,55 +2,64 @@
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=x86_64-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-X8664 %s
-// CHECK-CLANGRT-X8664: libclang_rt.builtins{{(-x86_64)?}}.a
+// CHECK-CLANGRT-X8664: libclang_rt.builtins-x86_64.a
 
 // RUN: %clang -rtli

[PATCH] D144542: [Clang] Improve hermeticity of clang_rt tests

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG67e28a3010e1: [Clang] Improve hermeticity of clang_rt tests 
(authored by michaelplatings).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144542

Files:
  clang/test/Driver/arm-compiler-rt.c
  clang/test/Driver/print-libgcc-file-name-clangrt.c

Index: clang/test/Driver/print-libgcc-file-name-clangrt.c
===
--- clang/test/Driver/print-libgcc-file-name-clangrt.c
+++ clang/test/Driver/print-libgcc-file-name-clangrt.c
@@ -2,55 +2,64 @@
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=x86_64-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-X8664 %s
-// CHECK-CLANGRT-X8664: libclang_rt.builtins{{(-x86_64)?}}.a
+// CHECK-CLANGRT-X8664: libclang_rt.builtins-x86_64.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=i386-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-I386 %s
-// CHECK-CLANGRT-I386: libclang_rt.builtins{{(-i386)?}}.a
+// CHECK-CLANGRT-I386: libclang_rt.builtins-i386.a
 
 // Check whether alternate arch values map to the correct library.
 //
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=i686-pc-linux \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-I386 %s
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM %s
-// CHECK-CLANGRT-ARM: libclang_rt.builtins{{(-arm)?}}.a
+// CHECK-CLANGRT-ARM: libclang_rt.builtins-arm.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-androideabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-ANDROID %s
 // CHECK-CLANGRT-ARM-ANDROID: libclang_rt.builtins-arm-android.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabihf \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARMHF %s
-// CHECK-CLANGRT-ARMHF: libclang_rt.builtins{{(-armhf)?}}.a
+// CHECK-CLANGRT-ARMHF: libclang_rt.builtins-armhf.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=arm-linux-gnueabi -mfloat-abi=hard \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-ABI %s
-// CHECK-CLANGRT-ARM-ABI: libclang_rt.builtins{{(-armhf)?}}.a
+// CHECK-CLANGRT-ARM-ABI: libclang_rt.builtins-armhf.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=armv7m-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-BAREMETAL %s
-// CHECK-CLANGRT-ARM-BAREMETAL: libclang_rt.builtins{{(-armv7m)?}}.a
+// CHECK-CLANGRT-ARM-BAREMETAL: libclang_rt.builtins-armv7m.a
 
 // RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
 // RUN: --target=armv7m-vendor-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-BAREMETAL-PER-TARGET %s
 // CHECK-CLANGRT-ARM-BAREMETAL-PER-TARGET: libclang_rt.builtins.a
Index: clang/test/Driver/arm-compiler-rt.c
===
--- clang/test/Driver/arm-compiler-rt.c
+++ clang/test/Driver/arm-compiler-rt.c
@@ -1,48 +1,56 @@
 // RUN: %clang -target arm-none-eabi \
+// RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-EABI
-// ARM-EABI: "-lclang_rt.builtins{{(-arm)?}}"
+// ARM-EABI: "-lclang_rt.built

[clang] 850dab0 - [NFC] Class for building MultilibSet

2023-02-22 Thread Michael Platings via cfe-commits

Author: Michael Platings
Date: 2023-02-22T09:24:48Z
New Revision: 850dab0f2537bb31103578fc35caef2f1ad98f04

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

LOG: [NFC] Class for building MultilibSet

The functionality in MultilibSet for creating it is tied to its current
implementation. Putting that code in a separate class is an enabler for
changing the MultilibSet implementation.

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

Added: 
clang/include/clang/Driver/MultilibBuilder.h
clang/lib/Driver/MultilibBuilder.cpp
clang/unittests/Driver/MultilibBuilderTest.cpp

Modified: 
clang/include/clang/Driver/Multilib.h
clang/lib/Driver/CMakeLists.txt
clang/lib/Driver/Multilib.cpp
clang/lib/Driver/ToolChains/BareMetal.cpp
clang/lib/Driver/ToolChains/Fuchsia.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/unittests/Driver/CMakeLists.txt
clang/unittests/Driver/MultilibTest.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Multilib.h 
b/clang/include/clang/Driver/Multilib.h
index cf2dbf6ff58a6..feb12f3638d34 100644
--- a/clang/include/clang/Driver/Multilib.h
+++ b/clang/include/clang/Driver/Multilib.h
@@ -24,7 +24,9 @@ namespace clang {
 namespace driver {
 
 /// This corresponds to a single GCC Multilib, or a segment of one controlled
-/// by a command line flag
+/// by a command line flag.
+/// See also MultilibBuilder for building a multilib by mutating it
+/// incrementally.
 class Multilib {
 public:
   using flags_list = std::vector;
@@ -37,71 +39,37 @@ class Multilib {
   int Priority;
 
 public:
+  /// GCCSuffix, OSSuffix & IncludeSuffix will be appended directly to the
+  /// sysroot string so they must either be empty or begin with a '/' 
character.
+  /// This is enforced with an assert in the constructor.
   Multilib(StringRef GCCSuffix = {}, StringRef OSSuffix = {},
-   StringRef IncludeSuffix = {}, int Priority = 0);
+   StringRef IncludeSuffix = {}, int Priority = 0,
+   const flags_list &Flags = flags_list());
 
   /// Get the detected GCC installation path suffix for the multi-arch
   /// target variant. Always starts with a '/', unless empty
-  const std::string &gccSuffix() const {
-assert(GCCSuffix.empty() ||
-   (StringRef(GCCSuffix).front() == '/' && GCCSuffix.size() > 1));
-return GCCSuffix;
-  }
-
-  /// Set the GCC installation path suffix.
-  Multilib &gccSuffix(StringRef S);
+  const std::string &gccSuffix() const { return GCCSuffix; }
 
   /// Get the detected os path suffix for the multi-arch
   /// target variant. Always starts with a '/', unless empty
-  const std::string &osSuffix() const {
-assert(OSSuffix.empty() ||
-   (StringRef(OSSuffix).front() == '/' && OSSuffix.size() > 1));
-return OSSuffix;
-  }
-
-  /// Set the os path suffix.
-  Multilib &osSuffix(StringRef S);
+  const std::string &osSuffix() const { return OSSuffix; }
 
   /// Get the include directory suffix. Always starts with a '/', unless
   /// empty
-  const std::string &includeSuffix() const {
-assert(IncludeSuffix.empty() ||
-   (StringRef(IncludeSuffix).front() == '/' && IncludeSuffix.size() > 
1));
-return IncludeSuffix;
-  }
-
-  /// Set the include directory suffix
-  Multilib &includeSuffix(StringRef S);
+  const std::string &includeSuffix() const { return IncludeSuffix; }
 
   /// Get the flags that indicate or contraindicate this multilib's use
   /// All elements begin with either '+' or '-'
   const flags_list &flags() const { return Flags; }
-  flags_list &flags() { return Flags; }
 
   /// Returns the multilib priority. When more than one multilib matches flags,
   /// the one with the highest priority is selected, with 0 being the default.
   int priority() const { return Priority; }
 
-  /// Add a flag to the flags list
-  /// \p Flag must be a flag accepted by the driver with its leading '-' 
removed,
-  /// and replaced with either:
-  ///   '-' which contraindicates using this multilib with that flag
-  /// or:
-  ///   '+' which promotes using this multilib in the presence of that flag
-  /// otherwise '-print-multi-lib' will not emit them correctly.
-  Multilib &flag(StringRef F) {
-assert(F.front() == '+' || F.front() == '-');
-Flags.push_back(std::string(F));
-return *this;
-  }
-
   LLVM_DUMP_METHOD void dump() const;
   /// print summary of the Multilib
   void print(raw_ostream &OS) const;
 
-  /// Check whether any of the 'against' flags contradict the 'for' flags.
-  bool isValid() const;
-
   /// Check whether the default is selected
   bool isDefault() const
   { return GCCSuffix.empty() && OSSuffix.empty() && IncludeSuffix.empty(); }
@@ -111,10 +79,10 @@ class Multilib {
 
 raw_ostream &operator<<(raw_o

[PATCH] D142893: [NFC] Class for building MultilibSet

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
michaelplatings marked 4 inline comments as done.
Closed by commit rG850dab0f2537: [NFC] Class for building MultilibSet (authored 
by michaelplatings).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142893

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/MultilibBuilder.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/MultilibBuilder.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/CMakeLists.txt
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -11,34 +11,17 @@
 //===--===//
 
 #include "clang/Driver/Multilib.h"
+#include "../../lib/Driver/ToolChains/CommonArgs.h"
 #include "clang/Basic/LLVM.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/SourceMgr.h"
 #include "gtest/gtest.h"
 
 using namespace clang::driver;
 using namespace clang;
 
-TEST(MultilibTest, MultilibValidity) {
-
-  ASSERT_TRUE(Multilib().isValid()) << "Empty multilib is not valid";
-
-  ASSERT_TRUE(Multilib().flag("+foo").isValid())
-  << "Single indicative flag is not valid";
-
-  ASSERT_TRUE(Multilib().flag("-foo").isValid())
-  << "Single contraindicative flag is not valid";
-
-  ASSERT_FALSE(Multilib().flag("+foo").flag("-foo").isValid())
-  << "Conflicting flags should invalidate the Multilib";
-
-  ASSERT_TRUE(Multilib().flag("+foo").flag("+foo").isValid())
-  << "Multilib should be valid even if it has the same flag twice";
-
-  ASSERT_TRUE(Multilib().flag("+foo").flag("-foobar").isValid())
-  << "Seemingly conflicting prefixes shouldn't actually conflict";
-}
-
 TEST(MultilibTest, OpEqReflexivity1) {
   Multilib M;
   ASSERT_TRUE(M == M) << "Multilib::operator==() is not reflexive";
@@ -50,40 +33,28 @@
 }
 
 TEST(MultilibTest, OpEqReflexivity3) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("+foo");
+  Multilib M1({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, 0, {"+foo"});
   ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
 }
 
 TEST(MultilibTest, OpEqInequivalence1) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("-foo");
+  Multilib M1({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, 0, {"-foo"});
   ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
   ASSERT_FALSE(M2 == M1)
   << "Multilibs with conflicting flags are not the same (commuted)";
 }
 
 TEST(MultilibTest, OpEqInequivalence2) {
-  Multilib M1, M2;
-  M2.flag("+foo");
+  Multilib M1;
+  Multilib M2({}, {}, {}, 0, {"+foo"});
   ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
 }
 
-TEST(MultilibTest, OpEqEquivalence1) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("+foo").flag("+foo");
-  ASSERT_TRUE(M1 == M2) << "Flag duplication shouldn't affect equivalence";
-  ASSERT_TRUE(M2 == M1)
-  << "Flag duplication shouldn't affect equivalence (commuted)";
-}
-
 TEST(MultilibTest, OpEqEquivalence2) {
-  Multilib M1("64");
-  Multilib M2;
-  M2.gccSuffix("/64");
+  Multilib M1("/64");
+  Multilib M2("/64");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::gccSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -91,9 +62,8 @@
 }
 
 TEST(MultilibTest, OpEqEquivalence3) {
-  Multilib M1("", "32");
-  Multilib M2;
-  M2.osSuffix("/32");
+  Multilib M1("", "/32");
+  Multilib M2("", "/32");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::osSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -101,9 +71,8 @@
 }
 
 TEST(MultilibTest, OpEqEquivalence4) {
-  Multilib M1("", "", "16");
-  Multilib M2;
-  M2.includeSuffix("/16");
+  Multilib M1("", "", "/16");
+  Multilib M2("", "", "/16");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::includeSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -111,31 +80,31 @@
 }
 
 TEST(MultilibTest, OpEqInequivalence3) {
-  Multilib M1("foo");
-  Multilib M2("bar");
+  Multilib M1("/foo");
+  Multilib M2("/bar");
   ASSERT_FALSE(M1 == M2) << "Differing gccSuffixes should be different";
   ASSERT_FALSE(M2 == M1)
   << "Differing gccSuffixes should be different (commuted)";
 }
 
 TEST(MultilibTest, OpEqInequivalence4) {
-  Multilib M1("", "foo");
-  Multilib M2("", "bar");
+  Multilib M1("", "/foo");
+  Multilib M2("", "/bar");
   ASSERT_FALSE(M1 == M2) << "Differing osSuffixes should be different";
   ASSERT_FALSE(M2 == M1)
   << "Differing osSuffixes should be d

[PATCH] D144544: [OpenMP] Improve LIT tests on composite target constructs

2023-02-22 Thread Animesh Kumar via Phabricator via cfe-commits
animeshk-amd created this revision.
animeshk-amd added reviewers: saiislam, JonChesterfield.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
animeshk-amd requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This commit improves the "target_teams_distribute_paralle
l_for_simd_codegen.cpp" and "target_teams_distribute_redu
ction_codegen.cpp" tests based upon some of the execution
tests present in the SOLLVE tests. Based on SOLLVE, a new
test "target_task_affinity_codegen.cpp" is also being
added. These tests are required to be added because the
existing tests do not test the combination of directives
these will be testing.

Link to SOLLVE page: https://github.com/SOLLVE/sollve_vv


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144544

Files:
  clang/test/OpenMP/target_task_affinity_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_reduction_codegen.cpp

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


[PATCH] D143306: [Driver] Default to -fno-openmp-implicit-rpath

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

I don't know how this configuration file works. Running clang from the build 
directory is useful when developing, but to avoid user facing regression we'd 
need it to run from the install directory. The use case is someone builds trunk 
or a release on a HPC machine and expects it to run without hacking with the 
environment variables, which is especially important as module systems managing 
the machine are likely to be hacking with the environment variables.

It's not obvious to me how that helps fedora. Maybe changing rpath is 
forbidden, but global installs put the shared libraries somewhere that is 
detectable anyway, and the config file handling has some special case to not 
set rpath on binaries if it would point to system anyway? That logic would 
probably work for openmp too - if the library we want to find is the one on the 
system path, great - the problem is when the library we want to find is not on 
the system path. However if this machinery is already implemented as something 
that reads a text configuration file and we can use that instead, great.

I would rather we not apply this patch as-is to trunk, and further not apply it 
to the previous release, because it'll break anyone running clang -fopenmp who 
doesn't have clang globally installed. If we can add some config file change to 
this patch which keeps things working then sure, back-porting is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143306

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


[PATCH] D142905: Change multilib selection algorithm

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499416.
michaelplatings marked 2 inline comments as done.
michaelplatings added a comment.

Remove braces as requested by @MaskRay


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142905

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/MultilibBuilder.h
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/MultilibBuilder.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -33,14 +33,14 @@
 }
 
 TEST(MultilibTest, OpEqReflexivity3) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
 }
 
 TEST(MultilibTest, OpEqInequivalence1) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"-foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"-foo"});
   ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
   ASSERT_FALSE(M2 == M1)
   << "Multilibs with conflicting flags are not the same (commuted)";
@@ -48,7 +48,7 @@
 
 TEST(MultilibTest, OpEqInequivalence2) {
   Multilib M1;
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
 }
 
@@ -124,9 +124,9 @@
 }
 
 TEST(MultilibTest, Construction3) {
-  Multilib M({}, {}, {}, 0, {"+f1", "+f2", "-f3"});
-  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
-E = M.flags().end();
+  Multilib M({}, {}, {}, {"+f1", "+f2", "-f3"});
+  for (Multilib::flag_set::const_iterator I = M.flags().begin(),
+  E = M.flags().end();
I != E; ++I) {
 ASSERT_TRUE(llvm::StringSwitch(*I)
 .Cases("+f1", "+f2", "-f3", true)
@@ -149,20 +149,41 @@
 
 TEST(MultilibTest, SetPriority) {
   MultilibSet MS({
-  Multilib("/foo", {}, {}, 1, {"+foo"}),
-  Multilib("/bar", {}, {}, 2, {"+bar"}),
+  Multilib("/foo", {}, {}, {"+foo"}),
+  Multilib("/bar", {}, {}, {"+bar"}),
   });
-  Multilib::flags_list Flags1 = {"+foo", "-bar"};
+  Multilib::flag_set Flags1 = {"+foo", "-bar"};
   Multilib Selection1;
   ASSERT_TRUE(MS.select(Flags1, Selection1))
   << "Flag set was {\"+foo\"}, but selection not found";
   ASSERT_TRUE(Selection1.gccSuffix() == "/foo")
   << "Selection picked " << Selection1 << " which was not expected";
 
-  Multilib::flags_list Flags2 = {"+foo", "+bar"};
+  Multilib::flag_set Flags2 = {"+foo", "+bar"};
   Multilib Selection2;
   ASSERT_TRUE(MS.select(Flags2, Selection2))
   << "Flag set was {\"+bar\"}, but selection not found";
   ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
   << "Selection picked " << Selection2 << " which was not expected";
 }
+
+TEST(MultilibTest, SelectMultiple) {
+  MultilibSet MS({
+  Multilib("/a", {}, {}, {"x"}),
+  Multilib("/b", {}, {}, {"y"}),
+  });
+  std::vector Selection;
+
+  Selection = MS.select({"x"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/b", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y", "x"});
+  ASSERT_EQ(2u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+  EXPECT_EQ("/b", Selection[1].gccSuffix());
+}
Index: clang/unittests/Driver/MultilibBuilderTest.cpp
===
--- clang/unittests/Driver/MultilibBuilderTest.cpp
+++ clang/unittests/Driver/MultilibBuilderTest.cpp
@@ -157,14 +157,14 @@
 .Maybe(MultilibBuilder("64").flag("+m64"))
 .makeMultilibSet();
 
-  Multilib::flags_list FlagM64 = {"+m64"};
+  Multilib::flag_set FlagM64 = {"+m64"};
   Multilib SelectionM64;
   ASSERT_TRUE(MS1.select(FlagM64, SelectionM64))
   << "Flag set was {\"+m64\"}, but selection not found";
   ASSERT_TRUE(SelectionM64.gccSuffix() == "/64")
   << "Selection picked " << SelectionM64 << " which was not expected";
 
-  Multilib::flags_list FlagNoM64 = {"-m64"};
+  Multilib::flag_set FlagNoM64 = {"-m64"};
   Multilib SelectionNoM64;
   ASSERT_TRUE(MS1.select(FlagNoM64, SelectionNoM64))
   << "Flag set was {\"-m64\"}, but selection not found";
@@ -181,16 +181,16 @@
   for (unsigned I = 0; I

[PATCH] D143319: [clangd] Support iwyu pragma: no_include

2023-02-22 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 499417.
zyounan added a comment.

Move parsing logic to Record.cpp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143319

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  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
@@ -20,8 +20,10 @@
 
 namespace clang::include_cleaner {
 namespace {
+using testing::AllOf;
 using testing::ElementsAreArray;
 using testing::IsEmpty;
+using testing::UnorderedElementsAre;
 
 // Matches a Decl* if it is a NamedDecl with the given name.
 MATCHER_P(named, N, "") {
@@ -284,19 +286,23 @@
   // We don't build an AST, we just run a preprocessor action!
   TestInputs Inputs;
   PragmaIncludes PI;
+  RecordedNoIncludes NI;
 
   PragmaIncludeTest() {
 Inputs.MakeAction = [this] {
   struct Hook : public PreprocessOnlyAction {
   public:
-Hook(PragmaIncludes *Out) : Out(Out) {}
+Hook(PragmaIncludes *Out, RecordedNoIncludes *NoInc)
+: Out(Out), NoInc(NoInc) {}
 bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
   Out->record(CI);
+  NoInc->record(CI);
   return true;
 }
 PragmaIncludes *Out;
+RecordedNoIncludes *NoInc;
   };
-  return std::make_unique(&PI);
+  return std::make_unique(&PI, &NI);
 };
   }
 
@@ -486,6 +492,40 @@
   EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
 }
 
+MATCHER_P(written, Name, "") { return arg.Written == Name; }
+MATCHER_P(includeLine, N, "") { return arg.HashLine == N; }
+MATCHER_P(resolved, Name, "") { return arg.Resolved == Name; }
+
+TEST_F(PragmaIncludeTest, IWYUNoInclude) {
+  Inputs.Code = R"cpp(
+// IWYU pragma: no_include "baz.h"
+#include "external.h"
+#include "foo.h"
+// IWYU pragma: no_include 
+// IWYU pragma: no_include  "headers.hpp" are not 
+// IWYU pragma: no_include  "headers.hpp" 
+// IWYU pragma: no_include "multiple"  "invalid"
+// IWYU pragma: no_include no_quotes are considered invalid
+// IWYU pragma: no_include  texts after are ignored
+// IWYU pragma: no_include not starting with quotes  "ignored"
+  )cpp";
+  Inputs.ExtraFiles["external.h"] = R"cpp(
+#pragma once
+// IWYU pragma: no_include 
+  )cpp";
+  Inputs.ExtraArgs.emplace_back("-I.");
+  createEmptyFiles({"foo.h", "bar.h", "baz.h", "valid", "invalid", "multiple",
+"are", "ignored", "headers.hpp"});
+  TestAST Processed = build();
+  auto &NoIncludes = NI.IwyuNoIncludes;
+  EXPECT_THAT(
+  NoIncludes,
+  UnorderedElementsAre(
+  AllOf(written("\"baz.h\""), resolved("baz.h"), includeLine(1)),
+  AllOf(written(""), resolved("bar.h"), includeLine(4)),
+  AllOf(written(""), resolved("valid"), includeLine(9;
+}
+
 TEST_F(PragmaIncludeTest, SelfContained) {
   Inputs.Code = R"cpp(
   #include "guarded.h"
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
@@ -423,4 +423,91 @@
   return std::make_unique(*this, PP);
 }
 
+void RecordedNoIncludes::record(const CompilerInstance &Clang) {
+  // Derived from PPCallbacks as we want to make Clang take the ownership of
+  // collector.
+  class NoIncludePragmaCollector : public CommentHandler, public PPCallbacks {
+  public:
+NoIncludePragmaCollector(const CompilerInstance &Clang,
+ RecordedNoIncludes &Out)
+: SM(Clang.getSourceManager()), Out(Out) {}
+bool HandleComment(Preprocessor &PP, SourceRange Range) override {
+  bool InMainFile = SM.isInMainFile(Range.getBegin());
+  auto Pragma =
+  tooling::parseIWYUPragma(SM.getCharacterData(Range.getBegin()));
+  if (!Pragma)
+return false;
+
+  // Record no_include pragma. We only care about main files.
+  if (InMainFile && Pragma->consume_front("no_include")) {
+auto Spelling =
+Pragma->take_until([](char C) { return C == '\n'; }).trim();
+if (Spelling.empty())
+  return false;
+const auto SplitQuotedIncl

[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-22 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

Overall not bad, except reported things, I don't have any complains.
Number of options is not an issue.
90% of users wont use them, 10% will be happy to find them instead of dealing 
with NOLINT.




Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp:51
+  lambdaExpr(hasDescendant(declRefExpr(equalsBoundNode("ref"))),
+ valueCapturesVar(equalsBoundNode("param"))
+  .bind("move-call");

i thing you dont need here "hasDescendant(declRefExpr(equalsBoundNode("ref"))),"
simply because hasAncestor alone is doing a trick, if lambda is ancestor, then 
this call is a descendant for it.




Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp:56-57
+  parmVarDecl(
+  parmVarDecl(hasType(type(rValueReferenceType(.bind("param"),
+  parmVarDecl(
+  optionally(hasType(

consider:
```
hasType(type(rValueReferenceType())),
decl().bind("param"),
optionally(hasType(
  qualType(references(templateTypeParmType(hasDeclaration(
  templateTypeParmDecl().bind("template-type"))),
```
no need to duplicate parmVarDecl



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp:61
+  templateTypeParmDecl().bind("template-type"))),
+  unless(hasType(references(qualType(
+  anyOf(isConstQualified(), substTemplateTypeParmType()),

put this unless before optionally...



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp:64-74
+  hasAncestor(compoundStmt(hasParent(lambdaExpr(
+  has(cxxRecordDecl(
+  has(cxxMethodDecl(ToParam, hasName("operator()"),
+  optionally(hasDescendant(MoveCallMatcher)),
+  hasAncestor(cxxConstructorDecl(
+  ToParam, isDefinition(), unless(isMoveConstructor()),
+  optionally(hasDescendant(MoveCallMatcher,

looks like lambda context is visible as both operator() and as body to 
lambaExpr directly.
this mean that it may match twice, once as functionDecl, and once as lambdaExpr.
You can merge functionDecl with cxxConstructorDecl, just do same trick like 
with isMoveAssignmentOperator.

I would probably start with functionDecl, and then would try do some trick like 
forEachParam, but we dont have such matcher
You missing also isDefinition() in functionDecl even that you got hasBody.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp:110
+  const auto *MoveCall = Result.Nodes.getNodeAs("move-call");
+  if (!MoveCall) {
+diag(Param->getLocation(),

consider style:
if (MoveCall) return;

 



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst:24
+
+.. option:: AllowAnyMoveExpr
+

maybe AllowPartialMove


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[PATCH] D143436: [clangd] Apply standard adaptors to CDBs pushed from LSP

2023-02-22 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 499433.
DmitryPolukhin added a comment.

Move call addTargetAndModeForProgramName after SystemIncludeExtractor


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143436

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang-tools-extra/clangd/CompileCommands.h
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/test/Inputs/did-change-configuration-params.args
  clang-tools-extra/clangd/test/did-change-configuration-params.test
  clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
  clang/include/clang/Tooling/Tooling.h
  clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
  clang/lib/Tooling/Tooling.cpp

Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -43,6 +43,7 @@
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
@@ -299,6 +300,31 @@
   }
 }
 
+void addExpandedResponseFiles(std::vector &CommandLine,
+  llvm::StringRef WorkingDir,
+  llvm::cl::TokenizerCallback Tokenizer,
+  llvm::vfs::FileSystem &FS) {
+  bool SeenRSPFile = false;
+  llvm::SmallVector Argv;
+  Argv.reserve(CommandLine.size());
+  for (auto &Arg : CommandLine) {
+Argv.push_back(Arg.c_str());
+if (!Arg.empty())
+  SeenRSPFile |= Arg.front() == '@';
+  }
+  if (!SeenRSPFile)
+return;
+  llvm::BumpPtrAllocator Alloc;
+  llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
+  llvm::Error Err =
+  ECtx.setVFS(&FS).setCurrentDir(WorkingDir).expandResponseFiles(Argv);
+  if (Err)
+llvm::errs() << Err;
+  // Don't assign directly, Argv aliases CommandLine.
+  std::vector ExpandedArgv(Argv.begin(), Argv.end());
+  CommandLine = std::move(ExpandedArgv);
+}
+
 } // namespace tooling
 } // namespace clang
 
@@ -684,7 +710,7 @@
 
   if (!Invocation.run())
 return nullptr;
- 
+
   assert(ASTs.size() == 1);
   return std::move(ASTs[0]);
 }
Index: clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
===
--- clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
+++ clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ConvertUTF.h"
@@ -48,28 +49,9 @@
 
 private:
   std::vector expand(std::vector Cmds) const {
-for (auto &Cmd : Cmds) {
-  bool SeenRSPFile = false;
-  llvm::SmallVector Argv;
-  Argv.reserve(Cmd.CommandLine.size());
-  for (auto &Arg : Cmd.CommandLine) {
-Argv.push_back(Arg.c_str());
-if (!Arg.empty())
-  SeenRSPFile |= Arg.front() == '@';
-  }
-  if (!SeenRSPFile)
-continue;
-  llvm::BumpPtrAllocator Alloc;
-  llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
-  llvm::Error Err = ECtx.setVFS(FS.get())
-.setCurrentDir(Cmd.Directory)
-.expandResponseFiles(Argv);
-  if (Err)
-llvm::errs() << Err;
-  // Don't assign directly, Argv aliases CommandLine.
-  std::vector ExpandedArgv(Argv.begin(), Argv.end());
-  Cmd.CommandLine = std::move(ExpandedArgv);
-}
+for (auto &Cmd : Cmds)
+  tooling::addExpandedResponseFiles(Cmd.CommandLine, Cmd.Directory,
+Tokenizer, *FS);
 return Cmds;
   }
 
Index: clang/include/clang/Tooling/Tooling.h
===
--- clang/include/clang/Tooling/Tooling.h
+++ clang/include/clang/Tooling/Tooling.h
@@ -506,6 +506,12 @@
 void addTargetAndModeForProgramName(std::vector &CommandLine,
 StringRef InvokedAs);
 
+/// Helper function that expands response files in command line.
+void addExpandedResponseFiles(std::vector &CommandLine,
+  llvm::StringRef WorkingDir,
+  llvm::cl::TokenizerCallback Tokenizer,
+  llvm::vfs::FileSystem &FS);
+
 /// Creates a \c CompilerInvocation.
 CompilerInvocation *newInvocation(DiagnosticsEngine *Diagnostics,
   ArrayRef CC1Args,
Index: clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
===
--- clang-tools-extra/clangd/unittests/CompileCommands

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 499436.
VitaNuo marked 2 inline comments as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp

Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -197,6 +197,36 @@
Distance(getID(BazHeader, Includes), 1u)));
 }
 
+TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
+  std::string FooHeader = testPath("foo.h");
+  FS.Files[FooHeader] = R"cpp(
+  void foo();
+)cpp";
+  std::string BarHeader = testPath("bar.h");
+  FS.Files[BarHeader] = R"cpp(
+  void bar();
+)cpp";
+  std::string BazHeader = testPath("baz.h");
+  FS.Files[BazHeader] = R"cpp(
+  void baz();
+)cpp";
+  FS.Files[MainFile] = R"cpp(
+#include "foo.h"
+#include "bar.h"
+#include "baz.h"
+)cpp";
+  auto Includes = collectIncludes();
+  EXPECT_THAT(Includes.MainFileIncludes,
+  UnorderedElementsAre(written("\"foo.h\""), written("\"bar.h\""),
+   written("\"baz.h\"")));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"foo.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[0]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"bar.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[1]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"baz.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[2]));
+}
+
 TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
   // We use TestTU here, to ensure we use the preamble replay logic.
   // We're testing that the logic doesn't crash, and doesn't result in duplicate
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,16 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +493,37 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert(HeaderID);
- break;
-   case include_cleaner::Header::Verbatim:
- for (auto HeaderID : BySpelling.l

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the comments!




Comment at: clang-tools-extra/clangd/Headers.cpp:303
+  llvm::SmallVector Includes;
+  auto It = MainFileIncludesBySpelling.find(Spelling);
+  if (It == MainFileIncludesBySpelling.end())

kadircet wrote:
> nit:
> ```
> llvm::SmallVector Includes;
> for (auto Idx : MainFileIncludesBySpelling.lookup(Spelling))
>   Includes.push_back(&MainFileIncludes[Idx]);
> return Includes;
> ```
But `lookup` will return 0 if it doesn't find the spelling in the map (default 
value of `int`). And at the same time 0 is a valid index. Isn't that just wrong?



Comment at: clang-tools-extra/clangd/Headers.h:167
+  // Spelling should include brackets or quotes, e.g. .
+  llvm::SmallVector
+  mainFileIncludesWithSpelling(llvm::StringRef Spelling) const {

kadircet wrote:
> kadircet wrote:
> > we're still returning just the `HeaderID`, the suggestion was to return 
> > `llvm::SmallVector` so that applications can work with other 
> > information available in the `Inclusion`. we also won't have any 
> > requirements around include being resolved that way. the application should 
> > figure out what to do if `HeaderID` is missing.
> > 
> > also can you move this function body to source file instead?
> almost, but not right. we're returning copies of `Inclusion`s here, not 
> pointers to `Inclusion`s inside the main file. the suggested signature was 
> `llvm::SmallVector` any reason for returning by value? 
Sure, thanks. No particular reason.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D144273: [clang][ASTImporter] Add VaList declaration to lookup table.

2023-02-22 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

Note that the Debian x64 test failure is from the unit test

  TEST(ClangdServer, MemoryUsageTest) {
MockFS FS;
MockCompilationDatabase CDB;
ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
  
auto FooCpp = testPath("foo.cpp");
Server.addDocument(FooCpp, "");
ASSERT_TRUE(Server.blockUntilIdleForTest());  // THIS ASSERTION FAILED
  
llvm::BumpPtrAllocator Alloc;
MemoryTree MT(&Alloc);
Server.profile(MT);
ASSERT_TRUE(MT.children().count("tuscheduler"));
EXPECT_TRUE(MT.child("tuscheduler").children().count(FooCpp));
  }

(from clang-tools-extra/clangd/unittests/ClangdTests.cpp lines 1244-1258). I'm 
not familiar with this area but it's unrelated to the commit and words like 
"scheduler" and "block until idle" suggest that this unit test is not entirely 
deterministic, so it's plausible that its failure is not connected to the 
commit under review. Is there a possibility to retrigger test execution to see 
whether this error reappears on another run?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144273

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


[PATCH] D142932: [NFC] Multilib YAML parsing

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499443.
michaelplatings added a subscriber: peter.smith.
michaelplatings added a comment.

- Squash D143763  into this change as 
suggested by @MaskRay
- Use PascalCase field names as requested by @phosek
- Applied improvements to error messages suggested by @peter.smith
- Removed some braces as requested by @MaskRay
- Moved serialization structs to anonymous namespace as requested by @MaskRay


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142932

Files:
  clang/include/clang/Driver/Multilib.h
  clang/lib/Driver/Multilib.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -13,6 +13,7 @@
 #include "clang/Driver/Multilib.h"
 #include "../../lib/Driver/ToolChains/CommonArgs.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Version.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
@@ -187,3 +188,408 @@
   EXPECT_EQ("/a", Selection[0].gccSuffix());
   EXPECT_EQ("/b", Selection[1].gccSuffix());
 }
+
+static void diagnosticCallback(const llvm::SMDiagnostic &D, void *Out) {
+  *reinterpret_cast(Out) = D.getMessage();
+}
+
+static bool parse(MultilibSet &MS, std::string &Diagnostic, const char *Data) {
+  return MS.parse(llvm::MemoryBufferRef(Data, "TEST"), diagnosticCallback,
+  &Diagnostic);
+}
+
+static bool parse(MultilibSet &MS, std::string &Diagnostic,
+  const std::string &Data) {
+  return MS.parse(llvm::MemoryBufferRef(Data, "TEST"), diagnosticCallback,
+  &Diagnostic);
+}
+
+static bool parse(MultilibSet &MS, const char *Data) {
+  return MS.parse(llvm::MemoryBufferRef(Data, "TEST"));
+}
+
+#define _STRINGIFY(x) #x
+#define STRINGIFY(x) _STRINGIFY(x)
+// Avoid using MULTILIB_CLANG_VERSION in case it has extra non-numeric parts.
+#define MULTILIB_CLANG_VERSION \
+  STRINGIFY(CLANG_VERSION_MAJOR)   \
+  "." STRINGIFY(CLANG_VERSION_MINOR) "." STRINGIFY(CLANG_VERSION_PATCHLEVEL)
+#define YAML_PREAMBLE "ClangMinimumVersion: " MULTILIB_CLANG_VERSION "\n"
+
+TEST(MultilibTest, ParseInvalid) {
+  std::string Diagnostic;
+
+  MultilibSet MS;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+Variants: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic)
+  .contains("missing required key 'ClangMinimumVersion'"))
+  << Diagnostic;
+
+  // Require all 3 major.minor.patch version components
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+ClangMinimumVersion: )" STRINGIFY(CLANG_VERSION_MAJOR) R"(.0
+Variants: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic)
+  .contains("not a valid version string. Expected "
+"MAJOR.MINOR.PATCHLEVEL but got \"" STRINGIFY(
+CLANG_VERSION_MAJOR) ".0\""))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+ClangMinimumVersion: )" MULTILIB_CLANG_VERSION R"(a
+Variants: []
+)"));
+  EXPECT_TRUE(
+  StringRef(Diagnostic)
+  .contains("not a valid version string. Expected "
+"MAJOR.MINOR.PATCHLEVEL where all components are decimal "
+"integers but got \"" MULTILIB_CLANG_VERSION "a\""))
+  << Diagnostic;
+
+  // Reject configurations that require a later clang version
+  EXPECT_FALSE(parse(MS, Diagnostic,
+ R"(
+ClangMinimumVersion: )" + std::to_string(CLANG_VERSION_MAJOR + 1) +
+ R"(.0.0
+Variants: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic)
+  .contains("clang version " MULTILIB_CLANG_VERSION
+" is less than ClangMinimumVersion: " +
+std::to_string(CLANG_VERSION_MAJOR + 1) + ".0.0"))
+  << Diagnostic;
+
+  // but accept configurations that only need an earlier clang version
+  EXPECT_TRUE(parse(MS, Diagnostic, R"(
+ClangMinimumVersion: 16.0.0
+Variants: []
+)")) << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, YAML_PREAMBLE));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("missing required key 'Variants'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, YAML_PREAMBLE R"(
+Variants:
+- Dir: /abc
+  Flags: []
+  PrintArgs: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("paths must be relative"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, YAML_PREAMBLE R"(
+Variants:
+- Flags: []
+  PrintArgs: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("missing required key 'Dir'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, YAML_PREAMBLE R"(
+Variants:
+- Dir: .
+  PrintArgs: []
+)"));
+  EXPECT_TRUE(Stri

[PATCH] D143763: [Clang] Add clangMinimumVersion to multilib.yaml

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings abandoned this revision.
michaelplatings marked 3 inline comments as done.
michaelplatings added a comment.

Squashed into D142932 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143763

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


[PATCH] D142933: Add -print-multi-selection-flags argument

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499450.
michaelplatings marked 2 inline comments as done.
michaelplatings added a comment.

Remove braces and blank lines as requested by @MaskRay


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142933

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.h
  clang/test/Driver/print-multi-selection-flags.c

Index: clang/test/Driver/print-multi-selection-flags.c
===
--- /dev/null
+++ clang/test/Driver/print-multi-selection-flags.c
@@ -0,0 +1,54 @@
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-linux -fc++-abi=itanium -fsanitize=address | FileCheck --check-prefix=CHECK-LINUX %s
+// CHECK-LINUX: fc++-abi=itanium
+// CHECK-LINUX: fexceptions
+// CHECK-LINUX: frtti
+// CHECK-LINUX: fsanitize=address
+// CHECK-LINUX: target=aarch64-unknown-linux
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-fuchsia -fsanitize=hwaddress | FileCheck --check-prefix=CHECK-FUCHSIA %s
+// CHECK-FUCHSIA: fsanitize=hwaddress
+// CHECK-FUCHSIA: target=aarch64-unknown-fuchsia
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=soft -fno-exceptions -fno-rtti | FileCheck --check-prefix=CHECK-ARMV4T %s
+// CHECK-ARMV4T: fno-exceptions
+// CHECK-ARMV4T: fno-rtti
+// CHECK-ARMV4T: mfloat-abi=soft
+// CHECK-ARMV4T: mfpu=none
+// CHECK-ARMV4T: target=armv4t-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=armv7em-none-eabi -mfloat-abi=softfp | FileCheck --check-prefix=CHECK-SOFTFP %s
+// CHECK-SOFTFP: mfloat-abi=softfp
+// CHECK-SOFTFP: mfpu=fpv4-sp-d16
+// CHECK-SOFTFP: target=thumbv7em-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabihf -march=armv7em -mfpu=fpv5-d16 | FileCheck --check-prefix=CHECK-HARD %s
+// CHECK-HARD: mfloat-abi=hard
+// CHECK-HARD: mfpu=fpv5-d16
+// CHECK-HARD: target=thumbv7em-none-unknown-eabihf
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=soft -march=armv8-m.main+nofp | FileCheck --check-prefix=CHECK-V8MMAIN-NOFP %s
+// CHECK-V8MMAIN-NOFP: mfloat-abi=soft
+// CHECK-V8MMAIN-NOFP: mfpu=none
+// CHECK-V8MMAIN-NOFP: target=thumbv8m.main-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=hard -march=armv8.1m.main+mve.fp | FileCheck --check-prefix=CHECK-MVE %s
+// CHECK-MVE: march=+mve
+// CHECK-MVE: march=+mve.fp
+// CHECK-MVE: mfloat-abi=hard
+// CHECK-MVE: mfpu=fp-armv8-fullfp16-sp-d16
+// CHECK-MVE: target=thumbv8.1m.main-none-unknown-eabihf
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -march=armv8.1m.main+mve+nofp | FileCheck --check-prefix=CHECK-MVENOFP %s
+// CHECK-MVENOFP: march=+mve
+// CHECK-MVENOFP-NOT: march=+mve.fp
+// CHECK-MVENOFP: mfpu=none
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-none-elf -march=armv8-a+lse | FileCheck --check-prefix=CHECK-LSE %s
+// CHECK-LSE: march=+lse
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-none-elf -march=armv8.5-a+sve+sve2 | FileCheck --check-prefix=CHECK-SVE2 %s
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-none-elf -march=armv9-a| FileCheck --check-prefix=CHECK-SVE2 %s
+// CHECK-SVE2: march=+simd
+// CHECK-SVE2: march=+sve
+// CHECK-SVE2: march=+sve2
+// CHECK-SVE2: target=aarch64-none-unknown-elf
Index: clang/lib/Driver/ToolChains/Arch/ARM.h
===
--- clang/lib/Driver/ToolChains/Arch/ARM.h
+++ clang/lib/Driver/ToolChains/Arch/ARM.h
@@ -64,9 +64,11 @@
 void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args,
llvm::StringRef &Arch, llvm::StringRef &CPU,
bool FromAs = false);
+// Optionally returns the FPUKind
 void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   const llvm::opt::ArgList &Args,
-  std::vector &Features, bool ForAS);
+  std::vector &Features, bool ForAS,
+  unsigned *OutFPUKind = nullptr);
 int getARMSubArchVersionNumber(const llvm::Triple &Triple);
 bool isARMMProfile(const llvm::Triple &Triple);
 bool isARMAProfile(const llvm::Triple &Triple);
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -438,7 +438,8 @@
 
 void arm::getARMTargetFeatures(const Driver &D, const

[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

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

LGTM but we should add a release note for the change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Headers.cpp:303
+  llvm::SmallVector Includes;
+  auto It = MainFileIncludesBySpelling.find(Spelling);
+  if (It == MainFileIncludesBySpelling.end())

VitaNuo wrote:
> kadircet wrote:
> > nit:
> > ```
> > llvm::SmallVector Includes;
> > for (auto Idx : MainFileIncludesBySpelling.lookup(Spelling))
> >   Includes.push_back(&MainFileIncludes[Idx]);
> > return Includes;
> > ```
> But `lookup` will return 0 if it doesn't find the spelling in the map 
> (default value of `int`). And at the same time 0 is a valid index. Isn't that 
> just wrong?
`MainFileIncludesBySpelling` is a map with values of type vector, not int. 
hence it'll be an empty vector, not `0`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D144540: [Clang] [Doc] Explicitly note noreturn bug as a miscompilation

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144540

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


[PATCH] D135495: [clang-tidy] handle exceptions properly in `ExceptionAnalyzer`

2023-02-22 Thread Domján Dániel via Phabricator via cfe-commits
isuckatcs updated this revision to Diff 499453.
isuckatcs added a comment.

Added tests for function pointers


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

https://reviews.llvm.org/D135495

Files:
  clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
  clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.h
  clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
@@ -101,6 +101,126 @@
   }
 }
 
+void throw_catch_pointer_c() noexcept {
+  try {
+int a = 1;
+throw &a;
+  } catch(const int *) {}
+}
+
+void throw_catch_pointer_v() noexcept {
+  try {
+int a = 1;
+throw &a;
+  } catch(volatile int *) {}
+}
+
+void throw_catch_pointer_cv() noexcept {
+  try {
+int a = 1;
+throw &a;
+  } catch(const volatile int *) {}
+}
+
+void throw_catch_multi_ptr_1() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_catch_multi_ptr_1' which should not throw exceptions
+  try {
+char **p = 0;
+throw p;
+  } catch (const char **) {
+  }
+}
+
+void throw_catch_multi_ptr_2() noexcept {
+  try {
+char **p = 0;
+throw p;
+  } catch (const char *const *) {
+  }
+}
+
+void throw_catch_multi_ptr_3() noexcept {
+  try {
+char **p = 0;
+throw p;
+  } catch (volatile char *const *) {
+  }
+}
+
+void throw_catch_multi_ptr_4() noexcept {
+  try {
+char **p = 0;
+throw p;
+  } catch (volatile const char *const *) {
+  }
+}
+
+// FIXME: In this case 'a' is convertible to the handler and should be caught
+// but in reality it's thrown. Note that clang doesn't report a warning for 
+// this either.
+void throw_catch_multi_ptr_5() noexcept {
+  try {
+double *a[2][3];
+throw a;
+  } catch (double *(*)[3]) {
+  }
+}
+
+
+void throw_c_catch_pointer() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_c_catch_pointer' which should not throw exceptions
+  try {
+int a = 1;
+const int *p = &a;
+throw p;
+  } catch(int *) {}
+}
+
+void throw_c_catch_pointer_v() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_c_catch_pointer_v' which should not throw exceptions
+  try {
+int a = 1;
+const int *p = &a;
+throw p;
+  } catch(volatile int *) {}
+}
+
+void throw_v_catch_pointer() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_v_catch_pointer' which should not throw exceptions
+  try {
+int a = 1;
+volatile int *p = &a;
+throw p;
+  } catch(int *) {}
+}
+
+void throw_v_catch_pointer_c() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_v_catch_pointer_c' which should not throw exceptions
+  try {
+int a = 1;
+volatile int *p = &a;
+throw p;
+  } catch(const int *) {}
+}
+
+void throw_cv_catch_pointer_c() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_cv_catch_pointer_c' which should not throw exceptions
+  try {
+int a = 1;
+const volatile int *p = &a;
+throw p;
+  } catch(const int *) {}
+}
+
+void throw_cv_catch_pointer_v() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_cv_catch_pointer_v' which should not throw exceptions
+  try {
+int a = 1;
+const volatile int *p = &a;
+throw p;
+  } catch(volatile int *) {}
+}
+
 class base {};
 class derived: public base {};
 
@@ -112,6 +232,229 @@
   }
 }
 
+void throw_derived_alias_catch_base() noexcept {
+  using alias = derived;
+
+  try {
+throw alias();
+  } catch(base &) {
+  }
+}
+
+void throw_derived_catch_base_alias() noexcept {
+  using alias = base;
+
+  try {
+throw derived();
+  } catch(alias &) {
+  }
+}
+
+void throw_derived_catch_base_ptr_c() noexcept {
+  try {
+derived d;
+throw &d; 
+  } catch(const base *) {
+  }
+}
+
+void throw_derived_catch_base_ptr() noexcept {
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: an exception may be thrown in function 'throw_derived_catch_base_ptr' which should not throw exceptions
+  try {
+derived d;
+const derived *p = &d;
+throw p; 
+  } catch(base *) {
+  }
+}
+
+class A {};
+class B : A {};
+
+// The following alias hell is deliberately created for testing.
+using aliasedA = A;
+class C : protected aliasedA {};
+
+typedef aliasedA moreAliasedA;
+class D : public moreAliasedA {};
+
+using moreMoreAliasedA = moreAliasedA;
+using aliasedD = D;
+class E : public moreMoreAliasedA, public aliasedD {};
+
+void throw_derived_catch_base_private() noexcept {
+  // CHECK-MESSAGES: :[[@LI

[PATCH] D135495: [clang-tidy] handle exceptions properly in `ExceptionAnalyzer`

2023-02-22 Thread Domján Dániel via Phabricator via cfe-commits
isuckatcs added a comment.

@xazax.hun can we merge this or should we wait for someone else's approval too?


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

https://reviews.llvm.org/D135495

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 499456.
VitaNuo marked an inline comment as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp

Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -197,6 +197,36 @@
Distance(getID(BazHeader, Includes), 1u)));
 }
 
+TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
+  std::string FooHeader = testPath("foo.h");
+  FS.Files[FooHeader] = R"cpp(
+  void foo();
+)cpp";
+  std::string BarHeader = testPath("bar.h");
+  FS.Files[BarHeader] = R"cpp(
+  void bar();
+)cpp";
+  std::string BazHeader = testPath("baz.h");
+  FS.Files[BazHeader] = R"cpp(
+  void baz();
+)cpp";
+  FS.Files[MainFile] = R"cpp(
+#include "foo.h"
+#include "bar.h"
+#include "baz.h"
+)cpp";
+  auto Includes = collectIncludes();
+  EXPECT_THAT(Includes.MainFileIncludes,
+  UnorderedElementsAre(written("\"foo.h\""), written("\"bar.h\""),
+   written("\"baz.h\"")));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"foo.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[0]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"bar.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[1]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"baz.h\""),
+  UnorderedElementsAre(&Includes.MainFileIncludes[2]));
+}
+
 TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
   // We use TestTU here, to ensure we use the preamble replay logic.
   // We're testing that the logic doesn't crash, and doesn't result in duplicate
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,16 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +493,37 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert(HeaderID);
- break;
-   case include_cleaner::Header::Verbatim:
- for (auto HeaderID : BySpelling.l

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo marked 2 inline comments as done.
VitaNuo added inline comments.



Comment at: clang-tools-extra/clangd/Headers.cpp:303
+  llvm::SmallVector Includes;
+  auto It = MainFileIncludesBySpelling.find(Spelling);
+  if (It == MainFileIncludesBySpelling.end())

kadircet wrote:
> VitaNuo wrote:
> > kadircet wrote:
> > > nit:
> > > ```
> > > llvm::SmallVector Includes;
> > > for (auto Idx : MainFileIncludesBySpelling.lookup(Spelling))
> > >   Includes.push_back(&MainFileIncludes[Idx]);
> > > return Includes;
> > > ```
> > But `lookup` will return 0 if it doesn't find the spelling in the map 
> > (default value of `int`). And at the same time 0 is a valid index. Isn't 
> > that just wrong?
> `MainFileIncludesBySpelling` is a map with values of type vector, not int. 
> hence it'll be an empty vector, not `0`.
Oh right. Sorry I guess I got confused.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks (both for the patch and for bearing with me)!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D144484: [Tooling/Inclusion] Handle std::get symbol.

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144484

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


[PATCH] D143306: [Driver] Default to -fno-openmp-implicit-rpath

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

So what is this configuration file? Joseph found a Gentoo blog post 
https://blogs.gentoo.org/mgorny/2022/10/07/clang-in-gentoo-now-sets-default-runtimes-via-config-file/
 and I don't have a clang.cfg file in my install dir


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143306

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


[PATCH] D142986: Enable multilib.yaml in the BareMetal ToolChain

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499479.
michaelplatings marked 6 inline comments as done.
michaelplatings added a comment.

Apply changes requested by @peter.smith and @MaskRay


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142986

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.h
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/baremetal-multilib.yaml
  clang/test/Driver/baremetal.cpp
  clang/test/Driver/lit.local.cfg

Index: clang/test/Driver/lit.local.cfg
===
--- clang/test/Driver/lit.local.cfg
+++ clang/test/Driver/lit.local.cfg
@@ -1,7 +1,7 @@
 from lit.llvm import llvm_config
 
 config.suffixes = ['.c', '.cpp', '.cppm', '.h', '.m', '.mm', '.S', '.s', '.f90', '.F90', '.f95',
-   '.cu', '.rs', '.cl', '.clcpp', '.hip', '.hipi', '.hlsl']
+   '.cu', '.rs', '.cl', '.clcpp', '.hip', '.hipi', '.hlsl', '.yaml']
 config.substitutions = list(config.substitutions)
 config.substitutions.insert(0,
 ('%clang_cc1',
Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -118,9 +118,9 @@
 // Verify that the bare metal driver does not include any host system paths:
 // CHECK-AARCH64-NO-HOST-INC: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-AARCH64-NO-HOST-INC: "-resource-dir" "[[RESOURCE:[^"]+]]"
-// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}aarch64-none-elf{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
 // CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
-// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}aarch64-none-elf{{[/\\]+}}include"
+// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
 
 // RUN: %clang %s -### --target=riscv64-unknown-elf -o %t.out -L some/directory/user/asked/for \
 // RUN: --sysroot=%S/Inputs/basic_riscv64_tree/riscv64-unknown-elf 2>&1 \
Index: clang/test/Driver/baremetal-multilib.yaml
===
--- /dev/null
+++ clang/test/Driver/baremetal-multilib.yaml
@@ -0,0 +1,143 @@
+# REQUIRES: shell
+# UNSUPPORTED: system-windows
+
+# RUN: rm -rf %T/baremetal_multilib
+# RUN: mkdir -p %T/baremetal_multilib/bin
+# RUN: mkdir -p %T/baremetal_multilib/lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib
+# RUN: touch %T/baremetal_multilib/lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib/libclang_rt.builtins.a
+# RUN: ln -s %clang %T/baremetal_multilib/bin/clang
+# RUN: ln -s %s %T/baremetal_multilib/lib/clang-runtimes/multilib.yaml
+
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### -o %t.out 2>&1 \
+# RUN: --target=thumbv8m.main-none-eabihf --sysroot= \
+# RUN:   | FileCheck -DSYSROOT=%T/baremetal_multilib %s
+# CHECK:  "-cc1" "-triple" "thumbv8m.main-none-unknown-eabihf"
+# CHECK-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/include/c++/v1"
+# CHECK-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/include"
+# CHECK-SAME: "-x" "c++" "{{.*}}baremetal-multilib.yaml"
+# CHECK-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
+# CHECK-SAME: "-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib"
+# CHECK-SAME: "-lc" "-lm" "-lclang_rt.builtins"
+# CHECK-SAME: "-o" "{{.*}}.tmp.out"
+
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-directory 2>&1 \
+# RUN: --target=thumbv8m.main-none-eabihf --sysroot= \
+# RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-DIRECTORY %s
+# CHECK-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8-m.main/fp
+
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-lib 2>&1 \
+# RUN: --target=arm-none-eabi --sysroot= \
+# RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-LIB %s
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v6-m/nofp;@-target=thumbv6m-none-eabi@mfloat-abi=soft
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7-m/nofp;@-target=thumbv7m-none-eabi@mfloat-abi=soft
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7e-m/nofp;@-target=thumbv7em-none-eabi@mfloat-abi=soft@mfpu=none
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/nofp;@-target=arm-none-eabi@mfloat-abi=soft@march=armv8m.main+nofp
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/th

[PATCH] D142986: Enable multilib.yaml in the BareMetal ToolChain

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added inline comments.



Comment at: clang/test/Driver/baremetal-multilib.cpp:14
+// RUN:   | FileCheck %s
+// CHECK: "{{.*}}clang{{.*}}" "-cc1" "-triple" 
"thumbv8m.main-none-unknown-eabihf"
+// CHECK-SAME: "-internal-isystem" 
"{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/include/c++/v1"

MaskRay wrote:
> With `-cc1` CHECK lines, remove `clang{{.*}}` before `-cc1`, then remove 
> `-no-canonical-prefixes`. See my prior commits in this area.
I found your commit 980679981fbc311bc07f8cd23e3739fd56c22d2a which removes many 
uses of `-no-canonical-prefixes`. However in this case the test relies on 
`-no-canonical-prefixes` to ensure that clang finds the correct 
`lib/clang-runtimes` directory so it's necessary to keep it.

I have removed `clang{{.*}}` which was a copy-paste from 
`baremetal-sysroot.cpp` and applied similar tweaks like your tidy-up to ld.



Comment at: clang/test/Driver/baremetal-multilib.cpp:19
+// CHECK-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" 
"-Bstatic"
+// CHECK-SAME: 
"-L{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib"
+// CHECK-SAME: "-lc" "-lm" "-lclang_rt.builtins"

MaskRay wrote:
> Use a style similar to `linux-cross.cpp`.
> 
> Test a few variants 
> (https://github.com/MaskRay/Config/wiki/LLVM#clanglibdriver)
> Use a style similar to `linux-cross.cpp`.

I think you're referring to the use of `-L[[SYSROOT]]` instead of `-L{{.*}}` 
and I've made that change.

> Test a few variants 
> (https://github.com/MaskRay/Config/wiki/LLVM#clanglibdriver)

The test follows the same pattern as `baremetal-sysroot.cpp` so in theory if 
that works on all the variants then so should this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142986

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


[PATCH] D143306: [Driver] Default to -fno-openmp-implicit-rpath

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/include/clang/Driver/Options.td:4218-4223
 defm openmp_implicit_rpath: BoolFOption<"openmp-implicit-rpath",
   LangOpts<"OpenMP">,
-  DefaultTrue,
+  DefaultFalse,
   PosFlag,
   NegFlag,
   BothFlags<[NoArgumentUnused]>>;

MaskRay wrote:
> yaxunl wrote:
> > I am wondering whether this option can be aliased to `--offload-add-rpath`, 
> > which seems to have the same purpose. (https://reviews.llvm.org/D136854)
> It can be aliased to `--[no-]offload-add-rpath`, but I think it probably 
> makes sense to drop this option completely. This patch as-is is useful for 
> backporting into 16.x.
Folding the flags together seems good to me, I'd have probably used 
offload-add-rpath in the initial implementation if I spotted it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143306

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


[clang-tools-extra] 7177a23 - [clangd] Add config option for fast diagnostics mode

2023-02-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-02-22T15:54:14+01:00
New Revision: 7177a237b68f32befcecedba78a875f1bbc4a609

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

LOG: [clangd] Add config option for fast diagnostics mode

Also wire it up for use with patched preambles and introduce test cases
for behaviour we'd like to improve.

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

Added: 


Modified: 
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/ConfigFragment.h
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
clang-tools-extra/clangd/unittests/PreambleTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index f41906b2f0faf..dffd54b01c459 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -88,7 +88,7 @@ struct Config {
 bool StandardLibrary = true;
   } Index;
 
-  enum UnusedIncludesPolicy {
+  enum class UnusedIncludesPolicy {
 /// Diagnose unused includes.
 Strict,
 None,
@@ -107,7 +107,10 @@ struct Config {
   llvm::StringMap CheckOptions;
 } ClangTidy;
 
-UnusedIncludesPolicy UnusedIncludes = None;
+UnusedIncludesPolicy UnusedIncludes = UnusedIncludesPolicy::None;
+
+/// Enable emitting diagnostics using stale preambles.
+bool AllowStalePreamble = false;
 
 /// IncludeCleaner will not diagnose usages of these headers matched by
 /// these regexes.

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index b1876e21ee30d..18de6e4d5c3b6 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -441,8 +441,14 @@ struct FragmentCompiler {
 Out.Apply.push_back([Val](const Params &, Config &C) {
   C.Diagnostics.UnusedIncludes = *Val;
 });
-compile(std::move(F.Includes));
+if (F.AllowStalePreamble) {
+  if (auto Val = F.AllowStalePreamble)
+Out.Apply.push_back([Val](const Params &, Config &C) {
+  C.Diagnostics.AllowStalePreamble = **Val;
+});
+}
 
+compile(std::move(F.Includes));
 compile(std::move(F.ClangTidy));
   }
 

diff  --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index bcd1a05b4a999..a5597596196fa 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -232,9 +232,13 @@ struct Fragment {
 ///
 /// Valid values are:
 /// - Strict
+/// - Experiment
 /// - None
 std::optional> UnusedIncludes;
 
+/// Enable emitting diagnostics using stale preambles.
+std::optional> AllowStalePreamble;
+
 /// Controls IncludeCleaner diagnostics.
 struct IncludesBlock {
   /// Regexes that will be used to avoid diagnosing certain includes as

diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index ee91753dd88dd..0ec0239fc71e6 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -130,6 +130,9 @@ class Parser {
 });
 Dict.handle("Includes", [&](Node &N) { parse(F.Includes, N); });
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
+Dict.handle("AllowStalePreamble", [&](Node &N) {
+  F.AllowStalePreamble = boolValue(N, "AllowStalePreamble");
+});
 Dict.parse(N);
   }
 
@@ -268,7 +271,7 @@ class Parser {
 // If Key is seen twice, Parse runs only once and an error is reported.
 void handle(llvm::StringLiteral Key, std::function Parse) {
   for (const auto &Entry : Keys) {
-(void) Entry;
+(void)Entry;
 assert(Entry.first != Key && "duplicate key handler");
   }
   Keys.emplace_back(Key, std::move(Parse));

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index f99c4142a4640..f442c852c571a 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -792,5 +792,9 @@ SourceLocation 
translatePreamblePatchLocation(SourceLocation Loc,
   return Loc;
 }
 
+bool PreamblePatch::preserveDiagnostics() const {
+  return PatchContents.empty() ||
+ Config::current().Diagnostics.AllowStalePreamble;
+}
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/Preamble.h 
b/clang-tools-extra/clangd/Preamble.h
index bd5fefcf8f0bc..438a4561ca

[clang-tools-extra] 75ae784 - [clangd] #undef macros inside preamble patch

2023-02-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-02-22T15:54:15+01:00
New Revision: 75ae784e8f49cf2425f3bf702a1bbf6c581e721a

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

LOG: [clangd] #undef macros inside preamble patch

That way we can stop generating false macro redefinition diagnostics.

Depends on D142890

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

Added: 


Modified: 
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/unittests/PreambleTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index f442c852c571..d01601e5a037 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -213,6 +213,9 @@ struct TextualPPDirective {
   // Full text that's representing the directive, including the `#`.
   std::string Text;
   unsigned Offset;
+  tok::PPKeywordKind Directive = tok::PPKeywordKind::pp_not_keyword;
+  // Name of the macro being defined in the case of a #define directive.
+  std::string MacroName;
 
   bool operator==(const TextualPPDirective &RHS) const {
 return std::tie(DirectiveLine, Offset, Text) ==
@@ -283,6 +286,8 @@ struct DirectiveCollector : public PPCallbacks {
   return;
 TextualDirectives.emplace_back();
 TextualPPDirective &TD = TextualDirectives.back();
+TD.Directive = tok::pp_define;
+TD.MacroName = MacroNameTok.getIdentifierInfo()->getName().str();
 
 const auto *MI = MD->getMacroInfo();
 TD.Text =
@@ -560,8 +565,8 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
 
   if (BuiltPreamble) {
 log("Built preamble of size {0} for file {1} version {2} in {3} seconds",
- BuiltPreamble->getSize(), FileName, Inputs.Version,
- PreambleTimer.getTime());
+BuiltPreamble->getSize(), FileName, Inputs.Version,
+PreambleTimer.getTime());
 std::vector Diags = PreambleDiagnostics.take();
 auto Result = std::make_shared(std::move(*BuiltPreamble));
 Result->Version = Inputs.Version;
@@ -724,6 +729,10 @@ PreamblePatch PreamblePatch::create(llvm::StringRef 
FileName,
 // reduce complexity. The former might cause problems because scanning is
 // imprecise and might pick directives from disabled regions.
 for (const auto &TD : ModifiedScan->TextualDirectives) {
+  // Introduce an #undef directive before #defines to suppress any
+  // re-definition warnings.
+  if (TD.Directive == tok::pp_define)
+Patch << "#undef " << TD.MacroName << '\n';
   Patch << "#line " << TD.DirectiveLine << '\n';
   Patch << TD.Text << '\n';
 }

diff  --git a/clang-tools-extra/clangd/unittests/PreambleTests.cpp 
b/clang-tools-extra/clangd/unittests/PreambleTests.cpp
index 0bd5a9f80641..68de063f7168 100644
--- a/clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ b/clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -288,6 +288,7 @@ TEST(PreamblePatchTest, Define) {
 #define BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -299,6 +300,7 @@ TEST(PreamblePatchTest, Define) {
 
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -310,6 +312,7 @@ TEST(PreamblePatchTest, Define) {
 BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 3
 #define BAR
 )cpp",
@@ -342,8 +345,10 @@ TEST(PreamblePatchTest, OrderingPreserved) {
   )cpp");
 
   llvm::StringLiteral ExpectedPatch(R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR\(X, Y\) X Y
+#undef BAR
 #line 3
 #define BAR\(X\) X
 )cpp");
@@ -693,23 +698,17 @@ TEST(PreamblePatch, DiagnosticsToPreamble) {
   {
 Annotations Code("#define [[FOO]] 1\n");
 // Check ranges for notes.
-Annotations NewCode(R"(#define $barxyz[[BARXYZ]] 1
+Annotations NewCode(R"(#define BARXYZ 1
 #define $foo1[[FOO]] 1
 void foo();
 #define $foo2[[FOO]] 2)");
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
 EXPECT_THAT(
 *AST->getDiagnostics(),
-ElementsAre(
-// FIXME: This diagnostics shouldn't exist. It's emitted from the
-// preamble patch to the stale location inside preamble.
-AllOf(Field(&Diag::Name, Eq("-Wmacro-redefined")),
-  Field(&Diag::File, HasSubstr("_preamble_patch_")),
-  withNote(Diag(NewCode.range("barxyz",
-AllOf(
-Diag(NewCode.range("foo2"), "-Wmacro-redefined"),
-// FIXME: This should be translated into main file.
-withNote(Field(&Note::File, HasSubstr("_preamble_patch_"));
+ElementsAre(AllOf(
+  

[clang-tools-extra] 909cd1f - [clangd] Respect preamble-patch when handling diags

2023-02-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-02-22T15:54:15+01:00
New Revision: 909cd1f9a8934033a803659da8c54c87013941ef

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

LOG: [clangd] Respect preamble-patch when handling diags

Depends on D143093

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

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/SourceCode.cpp
clang-tools-extra/clangd/SourceCode.h
clang-tools-extra/clangd/unittests/PreambleTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index 652e9e13b6e2..26b0047951b5 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -98,17 +98,22 @@ bool locationInRange(SourceLocation L, CharSourceRange R,
 // LSP needs a single range.
 Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
   auto &M = D.getSourceManager();
+  auto PatchedRange = [&M](CharSourceRange &R) {
+R.setBegin(translatePreamblePatchLocation(R.getBegin(), M));
+R.setEnd(translatePreamblePatchLocation(R.getEnd(), M));
+return R;
+  };
   auto Loc = M.getFileLoc(D.getLocation());
   for (const auto &CR : D.getRanges()) {
 auto R = Lexer::makeFileCharRange(CR, M, L);
 if (locationInRange(Loc, R, M))
-  return halfOpenToRange(M, R);
+  return halfOpenToRange(M, PatchedRange(R));
   }
   // The range may be given as a fixit hint instead.
   for (const auto &F : D.getFixItHints()) {
 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
 if (locationInRange(Loc, R, M))
-  return halfOpenToRange(M, R);
+  return halfOpenToRange(M, PatchedRange(R));
   }
   // If the token at the location is not a comment, we use the token.
   // If we can't get the token at the location, fall back to using the location
@@ -117,7 +122,7 @@ Range diagnosticRange(const clang::Diagnostic &D, const 
LangOptions &L) {
   if (!Lexer::getRawToken(Loc, Tok, M, L, true) && Tok.isNot(tok::comment)) {
 R = CharSourceRange::getTokenRange(Tok.getLocation(), Tok.getEndLoc());
   }
-  return halfOpenToRange(M, R);
+  return halfOpenToRange(M, PatchedRange(R));
 }
 
 // Try to find a location in the main-file to report the diagnostic D.
@@ -213,13 +218,6 @@ bool tryMoveToMainFile(Diag &D, FullSourceLoc DiagLoc) {
   return true;
 }
 
-bool isInsideMainFile(const clang::Diagnostic &D) {
-  if (!D.hasSourceManager())
-return false;
-
-  return clangd::isInsideMainFile(D.getLocation(), D.getSourceManager());
-}
-
 bool isNote(DiagnosticsEngine::Level L) {
   return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
 }
@@ -713,11 +711,15 @@ void 
StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
   auto FillDiagBase = [&](DiagBase &D) {
 fillNonLocationData(DiagLevel, Info, D);
 
-D.InsideMainFile = isInsideMainFile(Info);
+SourceLocation PatchLoc =
+translatePreamblePatchLocation(Info.getLocation(), SM);
+D.InsideMainFile = isInsideMainFile(PatchLoc, SM);
 D.Range = diagnosticRange(Info, *LangOpts);
-D.File = std::string(SM.getFilename(Info.getLocation()));
-D.AbsFile = getCanonicalPath(
-SM.getFileEntryForID(SM.getFileID(Info.getLocation())), SM);
+auto FID = SM.getFileID(Info.getLocation());
+if (auto *FE = SM.getFileEntryForID(FID)) {
+  D.File = FE->getName().str();
+  D.AbsFile = getCanonicalPath(FE, SM);
+}
 D.ID = Info.getID();
 return D;
   };

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index d01601e5a037..6a7efcd255d2 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -53,7 +53,6 @@
 namespace clang {
 namespace clangd {
 namespace {
-constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
 
 bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
  const tooling::CompileCommand &RHS) {
@@ -381,12 +380,6 @@ const char *spellingForIncDirective(tok::PPKeywordKind 
IncludeDirective) {
   llvm_unreachable("not an include directive");
 }
 
-// Checks whether \p FileName is a valid spelling of main file.
-bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
-  auto FE = SM.getFileManager().getFile(FileName);
-  return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
-}
-
 // Accumulating wall time timer. Similar to llvm::Timer, but much cheaper,
 // it only tracks wall time.
 // Since this is a generic timer, We may want to move this to support/ if we
@@ -660,7 +653,7 @@ PreamblePatch PreamblePatch::create(l

[clang-tools-extra] 8c2a12f - [clangd] Provide patched diagnostics with preamble patch

2023-02-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-02-22T15:54:15+01:00
New Revision: 8c2a12f7f9b6dc078bfb18df979fdf27c6a3

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

LOG: [clangd] Provide patched diagnostics with preamble patch

Translates diagnostics from baseline preamble to relevant modified
contents.

Translation is done by looking for a set of lines that have the same
contents in diagnostic/note/fix ranges inside baseline and modified
contents.

A diagnostic is preserved if its main range is outside of main file or
there's a translation from baseline to modified contents. Later on fixes
and notes attached to that diagnostic with relevant ranges are also
translated and preserved.

Depends on D143095

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

Added: 


Modified: 
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/unittests/PreambleTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index bf639a6fb58e..54a0f979c730 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -675,8 +675,7 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
 Diags = CompilerInvocationDiags;
 // Add diagnostics from the preamble, if any.
 if (Preamble)
-  Diags->insert(Diags->end(), Preamble->Diags.begin(),
-Preamble->Diags.end());
+  llvm::append_range(*Diags, Patch->patchedDiags());
 // Finally, add diagnostics coming from the AST.
 {
   std::vector D = ASTDiags.take(&*CTContext);

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index 6a7efcd255d2..e97564497954 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -9,7 +9,9 @@
 #include "Preamble.h"
 #include "Compiler.h"
 #include "Config.h"
+#include "Diagnostics.h"
 #include "Headers.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "clang-include-cleaner/Record.h"
 #include "support/Logger.h"
@@ -35,6 +37,9 @@
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -43,8 +48,9 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
-#include 
+#include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -306,6 +312,8 @@ struct DirectiveCollector : public PPCallbacks {
 struct ScannedPreamble {
   std::vector Includes;
   std::vector TextualDirectives;
+  // Literal lines of the preamble contents.
+  std::vector Lines;
   PreambleBounds Bounds = {0, false};
 };
 
@@ -332,7 +340,7 @@ scanPreamble(llvm::StringRef Contents, const 
tooling::CompileCommand &Cmd) {
   if (!CI)
 return error("failed to create compiler invocation");
   CI->getDiagnosticOpts().IgnoreWarnings = true;
-  auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
+  auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(PI.Contents);
   // This means we're scanning (though not preprocessing) the preamble section
   // twice. However, it's important to precisely follow the preamble bounds 
used
   // elsewhere.
@@ -363,6 +371,7 @@ scanPreamble(llvm::StringRef Contents, const 
tooling::CompileCommand &Cmd) {
 return std::move(Err);
   Action.EndSourceFile();
   SP.Includes = std::move(Includes.MainFileIncludes);
+  llvm::append_range(SP.Lines, llvm::split(Contents, "\n"));
   return SP;
 }
 
@@ -465,6 +474,93 @@ class TimerFS : public llvm::vfs::ProxyFileSystem {
   WallTimer Timer;
 };
 
+// Helpers for patching diagnostics between two versions of file contents.
+class DiagPatcher {
+  llvm::ArrayRef OldLines;
+  llvm::ArrayRef CurrentLines;
+  llvm::StringMap> CurrentContentsToLine;
+
+  // Translates a range from old lines to current lines.
+  // Finds the consecutive set of lines that corresponds to the same contents 
in
+  // old and current, and applies the same translation to the range.
+  // Returns true if translation succeeded.
+  bool translateRange(Range &R) {
+int OldStart = R.start.line;
+int OldEnd = R.end.line;
+assert(OldStart <= OldEnd);
+
+size_t RangeLen = OldEnd - OldStart + 1;
+auto RangeContents = OldLines.slice(OldStart).take_front(RangeLen);
+// Make sure the whole range is covered in old contents.
+if (RangeContents.size() < RangeLen)
+  return false;
+
+std::optional Closest;
+  

[clang-tools-extra] 465ee9b - [clangd] Publish diagnostics with stale preambles

2023-02-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-02-22T15:54:16+01:00
New Revision: 465ee9bfb26d46f2732d8b238dcbadc38373dbb3

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

LOG: [clangd] Publish diagnostics with stale preambles

This patch achieves this by building an AST and invoking main file
callbacks on each update, in addition to preamble updates.

It means we might have some extra AST builds now (e.g. if an update was
with a stale preamble and there were no reads on it, we would only build
an AST once we had the fresh preamble. Now we'll build 2, once with the
stale preamble and another with the fresh one, but we'll have one more
diagnostics cycle in between.).

This patch preserves forward progress of diagnostics by always using the
latest main file contents when emitting diagnostics after preamble
builds. It also guarantees eventual consistency:
- if an update doesn't invalidate preamble, we'll emit diagnostics with
  fresh preamble already.
- if an update invalidates preamble, we'll first emit diagnostics with
  stale contents, and then once the preamble build finishes it'll emit
  diagnostics (as preamble has changed) with newest version.

This has implications on parsing callbacks, as previously onMainAST
callback was called at most once, now it can be called up to 2 times.
All of the existing clients can already deal with callback firing
multiple times.

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

Added: 


Modified: 
clang-tools-extra/clangd/TUScheduler.cpp
clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 354638cd7b1e..a4f6a93b616a 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -49,6 +49,7 @@
 #include "TUScheduler.h"
 #include "CompileCommands.h"
 #include "Compiler.h"
+#include "Config.h"
 #include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
 #include "ParsedAST.h"
@@ -938,8 +939,19 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics 
WantDiags,
   return;
 }
 
-PreamblePeer.update(std::move(Invocation), std::move(Inputs),
-std::move(CompilerInvocationDiags), WantDiags);
+// Inform preamble peer, before attempting to build diagnostics so that 
they
+// can be built concurrently.
+PreamblePeer.update(std::make_unique(*Invocation),
+Inputs, CompilerInvocationDiags, WantDiags);
+
+// Emit diagnostics from (possibly) stale preamble while waiting for a
+// rebuild. Newly built preamble cannot emit diagnostics before this call
+// finishes (ast callbacks are called from astpeer thread), hence we
+// gurantee eventual consistency.
+if (LatestPreamble && Config::current().Diagnostics.AllowStalePreamble)
+  generateDiagnostics(std::move(Invocation), std::move(Inputs),
+  std::move(CompilerInvocationDiags));
+
 std::unique_lock Lock(Mutex);
 PreambleCV.wait(Lock, [this] {
   // Block until we reiceve a preamble request, unless a preamble already
@@ -1118,6 +1130,18 @@ void 
ASTWorker::updatePreamble(std::unique_ptr CI,
 // We only need to build the AST if diagnostics were requested.
 if (WantDiags == WantDiagnostics::No)
   return;
+// The file may have been edited since we started building this preamble.
+// If diagnostics need a fresh preamble, we must use the old version that
+// matches the preamble. We make forward progress as updatePreamble()
+// receives increasing versions, and this is the only place we emit
+// diagnostics.
+// If diagnostics can use a stale preamble, we use the current contents of
+// the file instead. This provides more up-to-date diagnostics, and avoids
+// diagnostics going backwards (we may have already emitted staler-preamble
+// diagnostics for the new version). We still have eventual consistency: at
+// some point updatePreamble() will catch up to the current file.
+if (Config::current().Diagnostics.AllowStalePreamble)
+  PI = FileInputs;
 // Report diagnostics with the new preamble to ensure progress. Otherwise
 // diagnostics might get stale indefinitely if user keeps invalidating the
 // preamble.

diff  --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp 
b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
index 5b3cab16ddb6..ead85a4ce5f2 100644
--- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -8,6 +8,8 @@
 
 #include "Annotations.h"
 #include "ClangdServer.h"
+#include "Compiler.h"
+#include "Config.h"
 #include "Diagnostics.h"
 #inc

[PATCH] D143093: [clangd] #undef macros inside preamble patch

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG75ae784e8f49: [clangd] #undef macros inside preamble patch 
(authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143093

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -288,6 +288,7 @@
 #define BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -299,6 +300,7 @@
 
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -310,6 +312,7 @@
 BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 3
 #define BAR
 )cpp",
@@ -342,8 +345,10 @@
   )cpp");
 
   llvm::StringLiteral ExpectedPatch(R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR\(X, Y\) X Y
+#undef BAR
 #line 3
 #define BAR\(X\) X
 )cpp");
@@ -693,23 +698,17 @@
   {
 Annotations Code("#define [[FOO]] 1\n");
 // Check ranges for notes.
-Annotations NewCode(R"(#define $barxyz[[BARXYZ]] 1
+Annotations NewCode(R"(#define BARXYZ 1
 #define $foo1[[FOO]] 1
 void foo();
 #define $foo2[[FOO]] 2)");
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
 EXPECT_THAT(
 *AST->getDiagnostics(),
-ElementsAre(
-// FIXME: This diagnostics shouldn't exist. It's emitted from the
-// preamble patch to the stale location inside preamble.
-AllOf(Field(&Diag::Name, Eq("-Wmacro-redefined")),
-  Field(&Diag::File, HasSubstr("_preamble_patch_")),
-  withNote(Diag(NewCode.range("barxyz",
-AllOf(
-Diag(NewCode.range("foo2"), "-Wmacro-redefined"),
-// FIXME: This should be translated into main file.
-withNote(Field(&Note::File, HasSubstr("_preamble_patch_"));
+ElementsAre(AllOf(
+Diag(NewCode.range("foo2"), "-Wmacro-redefined"),
+// FIXME: This should be translated into main file.
+withNote(Field(&Note::File, HasSubstr("_preamble_patch_"));
   }
 }
 
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -213,6 +213,9 @@
   // Full text that's representing the directive, including the `#`.
   std::string Text;
   unsigned Offset;
+  tok::PPKeywordKind Directive = tok::PPKeywordKind::pp_not_keyword;
+  // Name of the macro being defined in the case of a #define directive.
+  std::string MacroName;
 
   bool operator==(const TextualPPDirective &RHS) const {
 return std::tie(DirectiveLine, Offset, Text) ==
@@ -283,6 +286,8 @@
   return;
 TextualDirectives.emplace_back();
 TextualPPDirective &TD = TextualDirectives.back();
+TD.Directive = tok::pp_define;
+TD.MacroName = MacroNameTok.getIdentifierInfo()->getName().str();
 
 const auto *MI = MD->getMacroInfo();
 TD.Text =
@@ -560,8 +565,8 @@
 
   if (BuiltPreamble) {
 log("Built preamble of size {0} for file {1} version {2} in {3} seconds",
- BuiltPreamble->getSize(), FileName, Inputs.Version,
- PreambleTimer.getTime());
+BuiltPreamble->getSize(), FileName, Inputs.Version,
+PreambleTimer.getTime());
 std::vector Diags = PreambleDiagnostics.take();
 auto Result = std::make_shared(std::move(*BuiltPreamble));
 Result->Version = Inputs.Version;
@@ -724,6 +729,10 @@
 // reduce complexity. The former might cause problems because scanning is
 // imprecise and might pick directives from disabled regions.
 for (const auto &TD : ModifiedScan->TextualDirectives) {
+  // Introduce an #undef directive before #defines to suppress any
+  // re-definition warnings.
+  if (TD.Directive == tok::pp_define)
+Patch << "#undef " << TD.MacroName << '\n';
   Patch << "#line " << TD.DirectiveLine << '\n';
   Patch << TD.Text << '\n';
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D142890: [clangd] Add config option for fast diagnostics mode

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rG7177a237b68f: [clangd] Add config option for fast 
diagnostics mode (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D142890?vs=495889&id=499485#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142890

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -8,9 +8,13 @@
 
 #include "Annotations.h"
 #include "Compiler.h"
+#include "Config.h"
+#include "Diagnostics.h"
 #include "Headers.h"
 #include "Hover.h"
+#include "ParsedAST.h"
 #include "Preamble.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestFS.h"
 #include "TestTU.h"
@@ -19,10 +23,13 @@
 #include "clang/Format/Format.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Frontend/PrecompiledPreamble.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest-matchers.h"
 #include "gtest/gtest.h"
@@ -31,10 +38,18 @@
 #include 
 #include 
 
+using testing::AllOf;
 using testing::Contains;
+using testing::ElementsAre;
+using testing::Eq;
 using testing::Field;
+using testing::HasSubstr;
+using testing::IsEmpty;
 using testing::Matcher;
 using testing::MatchesRegex;
+using testing::Not;
+using testing::UnorderedElementsAre;
+using testing::UnorderedElementsAreArray;
 
 namespace clang {
 namespace clangd {
@@ -204,9 +219,12 @@
   Field(&Inclusion::FileKind, SrcMgr::CharacteristicKind::C_User;
 }
 
-std::optional createPatchedAST(llvm::StringRef Baseline,
-  llvm::StringRef Modified) {
-  auto BaselinePreamble = TestTU::withCode(Baseline).preamble();
+std::optional
+createPatchedAST(llvm::StringRef Baseline, llvm::StringRef Modified,
+ llvm::StringMap AdditionalFiles = {}) {
+  auto TU = TestTU::withCode(Baseline);
+  TU.AdditionalFiles = std::move(AdditionalFiles);
+  auto BaselinePreamble = TU.preamble();
   if (!BaselinePreamble) {
 ADD_FAILURE() << "Failed to build baseline preamble";
 return std::nullopt;
@@ -214,7 +232,7 @@
 
   IgnoreDiagnostics Diags;
   MockFS FS;
-  auto TU = TestTU::withCode(Modified);
+  TU.Code = Modified.str();
   auto CI = buildCompilerInvocation(TU.inputs(FS), Diags);
   if (!CI) {
 ADD_FAILURE() << "Failed to build compiler invocation";
@@ -599,6 +617,161 @@
 TU.inputs(FS), *BaselinePreamble);
   EXPECT_TRUE(PP.text().empty());
 }
+
+::testing::Matcher
+withNote(::testing::Matcher NoteMatcher) {
+  return Field(&Diag::Notes, ElementsAre(NoteMatcher));
+}
+MATCHER_P(Diag, Range, "Diag at " + llvm::to_string(Range)) {
+  return arg.Range == Range;
+}
+MATCHER_P2(Diag, Range, Name,
+   "Diag at " + llvm::to_string(Range) + " = [" + Name + "]") {
+  return arg.Range == Range && arg.Name == Name;
+}
+
+TEST(PreamblePatch, DiagnosticsFromMainASTAreInRightPlace) {
+  Config Cfg;
+  Cfg.Diagnostics.AllowStalePreamble = true;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
+  {
+Annotations Code("#define FOO");
+// Check with removals from preamble.
+Annotations NewCode("[[x]];/* error-ok */");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(),
+ElementsAre(Diag(NewCode.range(), "missing_type_specifier")));
+  }
+  {
+// Check with additions to preamble.
+Annotations Code("#define FOO");
+Annotations NewCode(R"(
+#define FOO
+#define BAR
+[[x]];/* error-ok */)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(),
+ElementsAre(Diag(NewCode.range(), "missing_type_specifier")));
+  }
+}
+
+TEST(PreamblePatch, DiagnosticsToPreamble) {
+  Config Cfg;
+  Cfg.Diagnostics.AllowStalePreamble = true;
+  Cfg.Diagnostics.UnusedIncludes = Config::UnusedIncludesPolicy::Strict;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
+  llvm:

[PATCH] D143095: [clangd] Respect preamble-patch when handling diags

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG909cd1f9a893: [clangd] Respect preamble-patch when handling 
diags (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143095

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -41,6 +41,7 @@
 using testing::AllOf;
 using testing::Contains;
 using testing::ElementsAre;
+using testing::ElementsAreArray;
 using testing::Eq;
 using testing::Field;
 using testing::HasSubstr;
@@ -705,10 +706,8 @@
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
 EXPECT_THAT(
 *AST->getDiagnostics(),
-ElementsAre(AllOf(
-Diag(NewCode.range("foo2"), "-Wmacro-redefined"),
-// FIXME: This should be translated into main file.
-withNote(Field(&Note::File, HasSubstr("_preamble_patch_"));
+ElementsAre(AllOf(Diag(NewCode.range("foo2"), "-Wmacro-redefined"),
+  withNote(Diag(NewCode.range("foo1"));
   }
 }
 
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -333,6 +333,10 @@
  (isUppercase(Name[1]) || Name[1] == '_');
 }
 
+/// Translates locations inside preamble patch to their main-file equivalent
+/// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
+SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
+  const SourceManager &SM);
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -796,6 +796,12 @@
   return Results;
 }
 
+// Checks whether \p FileName is a valid spelling of main file.
+bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
+  auto FE = SM.getFileManager().getFile(FileName);
+  return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
+}
+
 } // namespace
 
 std::vector visibleNamespaces(llvm::StringRef Code,
@@ -1219,5 +1225,24 @@
   return SM.getBufferData(FID).startswith(ProtoHeaderComment);
 }
 
+SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
+  const SourceManager &SM) {
+  auto DefFile = SM.getFileID(Loc);
+  if (auto FE = SM.getFileEntryRefForID(DefFile)) {
+auto IncludeLoc = SM.getIncludeLoc(DefFile);
+// Preamble patch is included inside the builtin file.
+if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
+FE->getName().endswith(PreamblePatch::HeaderName)) {
+  auto Presumed = SM.getPresumedLoc(Loc);
+  // Check that line directive is pointing at main file.
+  if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
+  isMainFile(Presumed.getFilename(), SM)) {
+Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
+  Presumed.getColumn());
+  }
+}
+  }
+  return Loc;
+}
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -157,6 +157,8 @@
   /// Whether diagnostics generated using this patch are trustable.
   bool preserveDiagnostics() const;
 
+  static constexpr llvm::StringLiteral HeaderName = "__preamble_patch__.h";
+
 private:
   static PreamblePatch create(llvm::StringRef FileName,
   const ParseInputs &Modified,
@@ -172,11 +174,6 @@
   PreambleBounds ModifiedBounds = {0, false};
 };
 
-/// Translates locations inside preamble patch to their main-file equivalent
-/// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
-SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
-  const SourceManager &SM);
-
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -53,7 +53,6 @@
 namespace clang {
 namespace clangd {
 nam

[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c2a12f7f9b6: [clangd] Provide patched diagnostics with 
preamble patch (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -723,9 +723,8 @@
 #define BAR
 #include [[]])");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Check with removals from preamble.
@@ -734,18 +733,15 @@
 #include [[]])");
 Annotations NewCode("#include [[]]");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop line with diags.
 Annotations Code("#include [[]]");
 Annotations NewCode("#define BAR\n#define BAZ\n");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diagnostics.
-EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
   {
 // Picks closest line in case of multiple alternatives.
@@ -756,18 +752,79 @@
 #define BAR
 #include )");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop diag if line spelling has changed.
 Annotations Code("#include [[]]");
 Annotations NewCode(" # include ");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diags.
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Multiple lines.
+Annotations Code(R"(
+#define BAR
+#include [[]])");
+Annotations NewCode(R"(#include [[]])");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
+  }
+  {
+// Multiple lines with change.
+Annotations Code(R"(
+#define BAR
+#include 
+#include [[]])");
+Annotations NewCode(R"(#include )");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Preserves notes.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define $note[[BAR]] 1
+#define BAZ 0
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  withNote(Diag(NewCode.range("note"));
+  }
+  {
+// Preserves diag without note.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  Field(&Diag::Notes, IsEmpty();
+  }
+  {
+// Make sure orphaned notes are not promoted to diags.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define BAR 1)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
 }
 } // namespace
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -34,6 +34,7 @@
 #include "clang/Frontend/PrecompiledPreamble.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/ArrayRef

[PATCH] D144456: [clangd] Publish diagnostics with stale preambles

2023-02-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG465ee9bfb26d: [clangd] Publish diagnostics with stale 
preambles (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144456

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp

Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -8,6 +8,8 @@
 
 #include "Annotations.h"
 #include "ClangdServer.h"
+#include "Compiler.h"
+#include "Config.h"
 #include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
 #include "Matchers.h"
@@ -21,7 +23,6 @@
 #include "support/Path.h"
 #include "support/TestTracer.h"
 #include "support/Threading.h"
-#include "support/ThreadsafeFS.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/FunctionExtras.h"
@@ -31,19 +32,23 @@
 #include "llvm/ADT/StringRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-#include 
 #include 
 #include 
+#include 
 #include 
+#include 
 #include 
+#include 
 #include 
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
 namespace {
 
+using ::testing::_;
 using ::testing::AllOf;
 using ::testing::AnyOf;
 using ::testing::Contains;
@@ -1194,6 +1199,118 @@
   EXPECT_EQ(PreamblePublishCount, 2);
 }
 
+TEST_F(TUSchedulerTests, PublishWithStalePreamble) {
+  // Callbacks that blocks the preamble thread after the first preamble is
+  // built and stores preamble/main-file versions for diagnostics released.
+  class BlockPreambleThread : public ParsingCallbacks {
+  public:
+using DiagsCB = std::function;
+BlockPreambleThread(Notification &UnblockPreamble, DiagsCB CB)
+: UnblockPreamble(UnblockPreamble), CB(std::move(CB)) {}
+
+void onPreambleAST(PathRef Path, llvm::StringRef Version,
+   const CompilerInvocation &, ASTContext &Ctx,
+   Preprocessor &, const CanonicalIncludes &) override {
+  if (BuildBefore)
+ASSERT_TRUE(UnblockPreamble.wait(timeoutSeconds(5)))
+<< "Expected notification";
+  BuildBefore = true;
+}
+
+void onMainAST(PathRef File, ParsedAST &AST, PublishFn Publish) override {
+  CB(AST);
+}
+
+void onFailedAST(PathRef File, llvm::StringRef Version,
+ std::vector Diags, PublishFn Publish) override {
+  ADD_FAILURE() << "Received failed ast for: " << File << " with version "
+<< Version << '\n';
+}
+
+  private:
+bool BuildBefore = false;
+Notification &UnblockPreamble;
+std::function CB;
+  };
+
+  // Helpers for issuing blocking update requests on a TUScheduler, whose
+  // onMainAST callback would call onDiagnostics.
+  class DiagCollector {
+  public:
+void onDiagnostics(ParsedAST &AST) {
+  std::scoped_lock Lock(DiagMu);
+  DiagVersions.emplace_back(
+  std::make_pair(AST.preambleVersion()->str(), AST.version().str()));
+  DiagsReceived.notify_all();
+}
+
+std::pair
+waitForNewDiags(TUScheduler &S, PathRef File, ParseInputs PI) {
+  std::unique_lock Lock(DiagMu);
+  // Perform the update under the lock to make sure it isn't handled until
+  // we're waiting for it.
+  S.update(File, std::move(PI), WantDiagnostics::Auto);
+  size_t OldSize = DiagVersions.size();
+  bool ReceivedDiags = DiagsReceived.wait_for(
+  Lock, std::chrono::seconds(5),
+  [this, OldSize] { return OldSize + 1 == DiagVersions.size(); });
+  if (!ReceivedDiags) {
+ADD_FAILURE() << "Timed out waiting for diags";
+return {"invalid", "version"};
+  }
+  return DiagVersions.back();
+}
+
+std::vector> diagVersions() {
+  std::scoped_lock Lock(DiagMu);
+  return DiagVersions;
+}
+
+  private:
+std::condition_variable DiagsReceived;
+std::mutex DiagMu;
+std::vector>
+DiagVersions;
+  };
+
+  Config Cfg;
+  Cfg.Diagnostics.AllowStalePreamble = true;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
+  DiagCollector Collector;
+  Notification UnblockPreamble;
+  auto DiagCallbacks = std::make_unique(
+  UnblockPreamble,
+  [&Collector](ParsedAST &AST) { Collector.onDiagnostics(AST); });
+  TUScheduler S(CDB, optsForTest(), std::move(DiagCallbacks));
+  Path File = testPath("foo.cpp");
+  auto BlockForDiags = [&](ParseInputs PI) {
+return Collector.waitForNewDiags(S, File, std::move(PI));
+  };
+
+  // Build first preamble.
+  auto PI = getInputs(File, "");
+  PI.Version = PI.Contents = "1";
+  ASSERT_THAT(BlockForDiags(PI), testing::Pair("1", "1"));
+
+  // Now preamble

[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-22 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis added a comment.

@kiranchandramohan @clementval can you please take a look and let me know if 
any more changes are required for this patch?

Thanks,
Akash


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-22 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan requested changes to this revision.
kiranchandramohan added a comment.
This revision now requires changes to proceed.

Please add tests for the MLIR portion.

Could you also post the full LLVM IR for a construct with the map clause?




Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4157
+Value *OpenMPIRBuilder::getSizeInBytes(Value *BasePtr) {
+
+  LLVMContext &Ctx = Builder.getContext();

Nit:Remove empty line.



Comment at: mlir/lib/Target/LLVMIR/Dialect/Utils.cpp:1
+//===- Utils.cpp - General Utils for translating MLIR dialect to LLVM 
IR---===//
+//

Nit: I would prefer the OpenMPCommon.cpp name suggested in 
https://discourse.llvm.org/t/rfc-adding-new-util-file-to-mlir-dialect-translation/68221.
 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[PATCH] D143075: BareMetal ToolChain multilib layering

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499491.
michaelplatings added a comment.

Rebase and remove some braces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143075

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/BareMetal.h
  clang/test/Driver/baremetal-multilib.yaml

Index: clang/test/Driver/baremetal-multilib.yaml
===
--- clang/test/Driver/baremetal-multilib.yaml
+++ clang/test/Driver/baremetal-multilib.yaml
@@ -25,6 +25,23 @@
 # RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-DIRECTORY %s
 # CHECK-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8-m.main/fp
 
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### -o %t.out 2>&1 \
+# RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+# RUN:   | FileCheck -DSYSROOT=%T/baremetal_multilib --check-prefix=CHECK-LAYERED-MULTILIB %s
+# CHECK-LAYERED-MULTILIB:  "-cc1" "-triple" "thumbv8.1m.main-none-unknown-eabihf"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include/c++/v1"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include/c++/v1"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include"
+# CHECK-LAYERED-MULTILIB-NEXT: "-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/lib"
+# CHECK-LAYERED-MULTILIB-SAME: "-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/lib"
+
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-directory 2>&1 \
+# RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+# RUN:   | FileCheck --check-prefix=CHECK-LAYERED-PRINT-MULTI-DIRECTORY %s
+# CHECK-LAYERED-PRINT-MULTI-DIRECTORY:  arm-none-eabi/thumb/v8.1-m.main/fp
+# CHECK-LAYERED-PRINT-MULTI-DIRECTORY-NEXT: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-lib 2>&1 \
 # RUN: --target=arm-none-eabi --sysroot= \
 # RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-LIB %s
@@ -38,6 +55,7 @@
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/fp;@-target=thumbv8m.main-none-eabihf
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp;@-target=thumbv8.1m.main-none-eabihf
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/nofp/mve;@-target=arm-none-eabihf@march=armv8.1m.main+nofp+mve
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept;@-target=thumbv8.1m.main-none-eabihf@fno-exceptions
 
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x assembler -mexecute-only \
 # RUN: --target=arm-none-eabi --sysroot= %s -c -### 2>&1 \
@@ -118,6 +136,14 @@
   Flags: [target=thumbv8.1m.main-none-unknown-eabihf, march=+mve]
   PrintArgs: [--target=arm-none-eabihf, -march=armv8.1m.main+nofp+mve]
 
+# A specialisation of v8.1-m.main/fp without exceptions.
+# This layers over the top of the regular v8.1-m.main/fp so it doesn't
+# need to have its own include directory or C library, thereby saving
+# disk space.
+- Dir: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+  Flags: [target=thumbv8.1m.main-none-unknown-eabihf, hasfpu, fno-exceptions]
+  PrintArgs: [--target=thumbv8.1m.main-none-eabihf, -fno-exceptions]
+
 
 # The second section of the file is a map from auto-detected flags
 # to custom flags. The auto-detected flags can be printed out
Index: clang/lib/Driver/ToolChains/BareMetal.h
===
--- clang/lib/Driver/ToolChains/BareMetal.h
+++ clang/lib/Driver/ToolChains/BareMetal.h
@@ -70,6 +70,9 @@
   void AddLinkRuntimeLib(const llvm::opt::ArgList &Args,
  llvm::opt::ArgStringList &CmdArgs) const;
   std::string computeSysRoot() const override;
+
+private:
+  llvm::SmallVector getOrderedMultilibs() const;
 };
 
 } // namespace toolchains
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -103,9 +103,12 @@
   findMultilibs(D, Triple, Args);
   SmallString<128> SysRoot(computeSysRoot());
   if (!SysRoot.empty()) {
-llvm::sys::path::append(SysRoot, "lib");
-getFilePaths().push_back(std::string(SysRoot));
-getLibraryPaths().push_back(std::string(SysRoot));
+for (const Multilib &M : getOrderedMultilibs()) {
+  SmallString<128> Dir(SysRoot);
+  llvm::sys::path::append(Dir, M.osSuffix(), "lib")

[PATCH] D143306: [Driver] Default to -fno-openmp-implicit-rpath

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield requested changes to this revision.
JonChesterfield added a comment.
This revision now requires changes to proceed.

Marking this as "no" because as far as I can tell it'll stop anyone running 
openmp built from source which constitutes a severe regression and I am 
struggling to find information on what Fedora are doing here. This link 
https://fedoraproject.org/wiki/Changes/Broken_RPATH_will_fail_rpmbuild suggests 
changing clang to not set rpath when it would be aiming at a "system 
directory", which is unfortunately platform specific magic strings, would be 
fine. That is, maybe Fedora is OK with setting RPATH as long as it isn't set to 
/usr/lib64 or possibly other unspecified strings.

The use case I want to preserve is people running clang -fopenmp from a local 
install and without setting environment variables. That means the binary needs 
to find the shared libraries from that local install and not unrelated files 
with the same name that happen to be under /usr somewhere.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143306

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


[PATCH] D143059: [NFC] Enable selecting multiple multilibs

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499500.
michaelplatings marked 2 inline comments as done.
michaelplatings added a comment.

Rebase and apply changes requested by @peter.smith


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143059

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/CSKYToolChain.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h
  clang/lib/Driver/ToolChains/Hexagon.cpp
  clang/lib/Driver/ToolChains/Hurd.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/MipsLinux.cpp
  clang/lib/Driver/ToolChains/RISCVToolchain.cpp
  clang/test/Driver/fuchsia.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -154,18 +154,18 @@
   Multilib("/bar", {}, {}, {"+bar"}),
   });
   Multilib::flag_set Flags1 = {"+foo", "-bar"};
-  Multilib Selection1;
+  llvm::SmallVector Selection1;
   ASSERT_TRUE(MS.select(Flags1, Selection1))
   << "Flag set was {\"+foo\"}, but selection not found";
-  ASSERT_TRUE(Selection1.gccSuffix() == "/foo")
-  << "Selection picked " << Selection1 << " which was not expected";
+  ASSERT_TRUE(Selection1.back().gccSuffix() == "/foo")
+  << "Selection picked " << Selection1.back() << " which was not expected";
 
   Multilib::flag_set Flags2 = {"+foo", "+bar"};
-  Multilib Selection2;
+  llvm::SmallVector Selection2;
   ASSERT_TRUE(MS.select(Flags2, Selection2))
   << "Flag set was {\"+bar\"}, but selection not found";
-  ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
-  << "Selection picked " << Selection2 << " which was not expected";
+  ASSERT_TRUE(Selection2.back().gccSuffix() == "/bar")
+  << "Selection picked " << Selection2.back() << " which was not expected";
 }
 
 TEST(MultilibTest, SelectMultiple) {
@@ -173,17 +173,17 @@
   Multilib("/a", {}, {}, {"x"}),
   Multilib("/b", {}, {}, {"y"}),
   });
-  std::vector Selection;
+  llvm::SmallVector Selection;
 
-  Selection = MS.select({"x"});
+  ASSERT_TRUE(MS.select({"x"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y"});
+  ASSERT_TRUE(MS.select({"y"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/b", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y", "x"});
+  ASSERT_TRUE(MS.select({"y", "x"}, Selection));
   ASSERT_EQ(2u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
   EXPECT_EQ("/b", Selection[1].gccSuffix());
@@ -383,7 +383,7 @@
 
 TEST(MultilibTest, SelectSoft) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, YAML_PREAMBLE R"(
 Variants:
 - Dir: s
@@ -402,7 +402,7 @@
 
 TEST(MultilibTest, SelectSoftFP) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, YAML_PREAMBLE R"(
 Variants:
 - Dir: f
@@ -418,7 +418,7 @@
   // If hard float is all that's available then select that only if compiling
   // with hard float.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, YAML_PREAMBLE R"(
 Variants:
 - Dir: h
@@ -432,7 +432,7 @@
 
 TEST(MultilibTest, SelectFloatABI) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, YAML_PREAMBLE R"(
 Variants:
 - Dir: s
@@ -453,18 +453,18 @@
   NoMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/f", Selected.gccSuffix());
+  EXPECT_EQ("/f", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=hard"}, Selected);
-  EXPECT_EQ("/h", Selected.gccSuffix());
+  EXPECT_EQ("/h", Selected.back().gccSuffix());
 }
 
 TEST(MultilibTest, SelectFloatABIReversed) {
   // If soft is specified after softfp then softfp will never be
   // selected because soft is compatible with softfp and last wins.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, YAML_PREAMBLE R"(
 Variants:
 - Dir: h
@@ -485,11 +485,11 @@
   NoMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select

[PATCH] D143306: [Driver] Default to -fno-openmp-implicit-rpath

2023-02-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

I'm worried this makes use of LLVM on HPC machines even harder. That said, I'm 
open to suggestions and I am not well versed in all the ways we can make it 
work.
Our problem is that there are N `libomptarget.so` files and N 
`libomptarget.nvptx.so` files on a system, including in system directories and 
in directories you have on your LD_LIBRARY_PATH.
However, we want a clang to pick up its own versions of those files. The former 
is linked into clang, the latter is dynamically loaded with dlopen. That is, 
IIRC, roughly our use case.

> I'd argue that such systems should specify -Wl,-rpath explicitly or in a 
> Clang configuration file.

Could you work me through this, please. We can't install a config file in a 
user or system directory. So all we have is the clang install directory.
Should we not set this flag but then install a file (by default) that says 
`-Wl,-rpath=...`. Is that what you mean? If so, what's the difference for the 
user?
Or would we add `--offload-add-rpath` to the clang build if OpenMP offload is 
enabled?




Comment at: clang/include/clang/Driver/Options.td:4218-4223
 defm openmp_implicit_rpath: BoolFOption<"openmp-implicit-rpath",
   LangOpts<"OpenMP">,
-  DefaultTrue,
+  DefaultFalse,
   PosFlag,
   NegFlag,
   BothFlags<[NoArgumentUnused]>>;

JonChesterfield wrote:
> MaskRay wrote:
> > yaxunl wrote:
> > > I am wondering whether this option can be aliased to 
> > > `--offload-add-rpath`, which seems to have the same purpose. 
> > > (https://reviews.llvm.org/D136854)
> > It can be aliased to `--[no-]offload-add-rpath`, but I think it probably 
> > makes sense to drop this option completely. This patch as-is is useful for 
> > backporting into 16.x.
> Folding the flags together seems good to me, I'd have probably used 
> offload-add-rpath in the initial implementation if I spotted it.
Merging them makes sense. FWIW, this flag was introduced 10 months earlier (I 
think).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143306

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


[PATCH] D144179: [Clang] Added functionality to provide config file name via env variable

2023-02-22 Thread Jolanta Jensen via Phabricator via cfe-commits
jolanta.jensen updated this revision to Diff 499502.
jolanta.jensen added a comment.

Adjusting the test for Windows OS again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144179

Files:
  clang/include/clang/Config/config.h.cmake
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/config-file-from-env.c

Index: clang/test/Driver/config-file-from-env.c
===
--- /dev/null
+++ clang/test/Driver/config-file-from-env.c
@@ -0,0 +1,51 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: mkdir %t/empty_dir
+// RUN: echo "-Wall" > %t/c.cfg
+// RUN: echo "-ffast-math" > %t/cxx.cfg
+// RUN: touch %t/unreadable.cfg
+// RUN: chmod 000 %t/unreadable.cfg
+// RUN: touch %t/test.c
+// RUN: touch %t/test.cpp
+
+// RUN: env CONFIG_FILE=%t/c.cfg %clang -S %t/test.c -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-C1
+// CHECK-C1: Configuration file: {{.*[\/\\]}}c.cfg
+// CHECK-C1: -Wall
+
+// RUN: env CONFIG_FILE=%t/unreadable.cfg not %clang -S %t/test.c -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-C2
+// CHECK-C2: error: cannot read configuration file '{{.*[\/\\]}}unreadable.cfg'
+
+// RUN: env CONFIG_FILE=%t/c.cfg %clang -S %t/test.c --config %S/Inputs/config-1.cfg -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-C3
+// CHECK-C3: Configuration file: {{.*[\/\\]}}config-1.cfg
+// CHECK-C3: -Werror
+// CHECK-C3-NOT: -Wall
+
+// RUN: env CONFIG_FILE= not %clang -S %t/test.c -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-C4
+// CHECK-C4: error: cannot read configuration file ''
+
+// RUN: env CONFIG_FILE=%t/empty_dir not %clang -S %t/test.c -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-C5
+// CHECK-C5: error: configuration file '{{.*[\/\\]}}empty_dir' cannot be opened: not a regular file
+
+// RUN: env CONFIG_FILE=%t/cxx.cfg %clang++ -S %t/test.cpp -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX1
+// CHECK-CXX1: Configuration file: {{.*[\/\\]}}cxx.cfg
+// CHECK-CXX1: -ffast-math
+
+// RUN: env CONFIG_FILE=%t/unreadable.cfg not %clang++ -S %t/test.cpp -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX2
+// CHECK-CXX2: error: cannot read configuration file '{{.*[\/\\]}}unreadable.cfg'
+
+// RUN: env CONFIG_FILE=%t/cxx.cfg %clang++ -S %t/test.cpp --config %S/Inputs/config-1.cfg -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX3
+// CHECK-CXX3: Configuration file: {{.*[\/\\]}}config-1.cfg
+// CHECK-CXX3: -Werror
+// CHECK-CXX3-NOT: -ffast-math
+
+// RUN: env CONFIG_FILE= not %clang++ -S %t/test.cpp -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX4
+// CHECK-CXX4: error: cannot read configuration file ''
+
+// RUN: env CONFIG_FILE=%t/empty_dir not %clang++ -S %t/test.cpp -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX5
+// CHECK-CXX5: error: configuration file '{{.*[\/\\]}}empty_dir' cannot be opened: not a regular file
+
+// RUN: env CONFIG_FILE=%t/c.cfg %clang++ --config=%t/cxx.cfg -S %t/test.cpp -o /dev/null -### 2>&1 | FileCheck %s -check-prefix CHECK-CXX6
+// CHECK-CXX6-NOT: Configuration file: {{.*[\/\\]}}c.cfg
+// CHECK-CXX6-NOT: -Wall
+
+// RUN: rm -rf %t
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -1034,6 +1034,35 @@
   return false;
 }
 
+bool Driver::readConfigFileFromEnv() {
+  llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
+llvm::cl::tokenizeConfigFile);
+  ExpCtx.setVFS(&getVFS());
+  std::string EnvCfgName = "CONFIG_FILE";
+
+#if defined(ENV_CONFIG_FILE_NAME)
+  EnvCfgName = ENV_CONFIG_FILE_NAME;
+#endif
+  const char *EnvCfgFileName = getenv(EnvCfgName.c_str());
+
+  if (!EnvCfgFileName)
+return false;
+
+  std::string CfgFileName = EnvCfgFileName;
+  if (CfgFileName.empty()) {
+Diag(diag::err_drv_cannot_read_config_file) << CfgFileName << "";
+return true;
+  }
+
+  // If argument contains directory separator, treat it as a path to
+  // configuration file.
+  SmallString<128> CfgFilePath;
+  if (llvm::sys::path::is_relative(CfgFileName))
+llvm::sys::fs::current_path(CfgFilePath);
+  llvm::sys::path::append(CfgFilePath, CfgFileName);
+  return readConfigFile(CfgFilePath, ExpCtx);
+}
+
 bool Driver::loadConfigFiles() {
   llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
 llvm::cl::tokenizeConfigFile);
@@ -1099,6 +1128,9 @@
 }
   }
 
+  if (ConfigFiles.empty())
+return readConfigFileFromEnv();
+
   // No error occurred.
   return false;
 }
Index: clang/include/clang/Driver/Driver.h
===
--- clang/include/clang/Driver/Driver.h
+++ clang/include/clang/Driver/Driver.h
@@ -702,6 +702,12 @@
   /// \returns true if error occurred.
 

[PATCH] D143075: BareMetal ToolChain multilib layering

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499503.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143075

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/BareMetal.h
  clang/test/Driver/baremetal-multilib.yaml

Index: clang/test/Driver/baremetal-multilib.yaml
===
--- clang/test/Driver/baremetal-multilib.yaml
+++ clang/test/Driver/baremetal-multilib.yaml
@@ -25,6 +25,23 @@
 # RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-DIRECTORY %s
 # CHECK-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8-m.main/fp
 
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### -o %t.out 2>&1 \
+# RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+# RUN:   | FileCheck -DSYSROOT=%T/baremetal_multilib --check-prefix=CHECK-LAYERED-MULTILIB %s
+# CHECK-LAYERED-MULTILIB:  "-cc1" "-triple" "thumbv8.1m.main-none-unknown-eabihf"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include/c++/v1"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include/c++/v1"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include"
+# CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include"
+# CHECK-LAYERED-MULTILIB-NEXT: "-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/lib"
+# CHECK-LAYERED-MULTILIB-SAME: "-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/lib"
+
+# RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-directory 2>&1 \
+# RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+# RUN:   | FileCheck --check-prefix=CHECK-LAYERED-PRINT-MULTI-DIRECTORY %s
+# CHECK-LAYERED-PRINT-MULTI-DIRECTORY:  arm-none-eabi/thumb/v8.1-m.main/fp
+# CHECK-LAYERED-PRINT-MULTI-DIRECTORY-NEXT: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-lib 2>&1 \
 # RUN: --target=arm-none-eabi --sysroot= \
 # RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-LIB %s
@@ -38,6 +55,7 @@
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/fp;@-target=thumbv8m.main-none-eabihf
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp;@-target=thumbv8.1m.main-none-eabihf
 # CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/nofp/mve;@-target=arm-none-eabihf@march=armv8.1m.main+nofp+mve
+# CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept;@-target=thumbv8.1m.main-none-eabihf@fno-exceptions
 
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x assembler -mexecute-only \
 # RUN: --target=arm-none-eabi --sysroot= %s -c -### 2>&1 \
@@ -118,6 +136,14 @@
   Flags: [target=thumbv8.1m.main-none-unknown-eabihf, march=+mve]
   PrintArgs: [--target=arm-none-eabihf, -march=armv8.1m.main+nofp+mve]
 
+# A specialisation of v8.1-m.main/fp without exceptions.
+# This layers over the top of the regular v8.1-m.main/fp so it doesn't
+# need to have its own include directory or C library, thereby saving
+# disk space.
+- Dir: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+  Flags: [target=thumbv8.1m.main-none-unknown-eabihf, hasfpu, fno-exceptions]
+  PrintArgs: [--target=thumbv8.1m.main-none-eabihf, -fno-exceptions]
+
 
 # The second section of the file is a map from auto-detected flags
 # to custom flags. The auto-detected flags can be printed out
Index: clang/lib/Driver/ToolChains/BareMetal.h
===
--- clang/lib/Driver/ToolChains/BareMetal.h
+++ clang/lib/Driver/ToolChains/BareMetal.h
@@ -70,6 +70,9 @@
   void AddLinkRuntimeLib(const llvm::opt::ArgList &Args,
  llvm::opt::ArgStringList &CmdArgs) const;
   std::string computeSysRoot() const override;
+
+private:
+  llvm::SmallVector getOrderedMultilibs() const;
 };
 
 } // namespace toolchains
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -103,9 +103,12 @@
   findMultilibs(D, Triple, Args);
   SmallString<128> SysRoot(computeSysRoot());
   if (!SysRoot.empty()) {
-llvm::sys::path::append(SysRoot, "lib");
-getFilePaths().push_back(std::string(SysRoot));
-getLibraryPaths().push_back(std::string(SysRoot));
+for (const Multilib &M : getOrderedMultilibs()) {
+  SmallString<128> Dir(SysRoot);
+  llvm::sys::path::append(Dir, M.osSuffix(), "lib");
+  getFilePaths()

[PATCH] D144544: [OpenMP] Improve LIT tests on composite target constructs

2023-02-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

I guess this is fine. We should try to run V&V tests, this is really just 
checking if we generate (some) code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144544

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


[PATCH] D143751: [clang][analyzer][NFC] Refactor code of StdLibraryFunctionsChecker.

2023-02-22 Thread KristĂłf Umann via Phabricator via cfe-commits
Szelethus added a comment.

Ugh, I admit, its a little hard to follow what happened here. You moved a lot 
of code around (I agree with that!), but also changed code as well. Can you 
just summarize what is NOT just moved code and needs a more thorough look?




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:124-125
   // requirement would render the initialization of the Summary map infeasible.
+  // A new value constraint is created furthermore by the negate functionality
+  // of the constraint and returned as pointer.
   using ValueConstraintPtr = std::shared_ptr;

Is this what you meant?



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:218
+  /// Check if a single argument falls into a specific range.
+  /// The "range" can be built from sub-ranges that are closed intervals.
   class RangeConstraint : public ValueConstraint {

If you want a killer doc, use examples. Not saying this is not good enough, but 
it wouldn't hurt.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:220-222
+/// The constraint can be specified by allowing or disallowing the range.
+/// WithinRange indicates allowing the range, OutOfRange indicates
+/// disallowing it.

I'd place parts of this comments above the enum values declaration (now on line 
72), but even that small comment that is already there looks good enough. After 
that, maybe there is not much to note here.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:262
 
+  protected:
 bool checkSpecificValidity(const FunctionDecl *FD) const override {

Nice.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1031
+
+ProgramStateRef 
StdLibraryFunctionsChecker::NotNullConstraint::apply(ProgramStateRef State, 
const CallEvent &Call,
+  const Summary &Summary,

seems like this could use [[ 
https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting | 
clang-format-diff.py]].


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143751

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


[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-22 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D143891#4144161 , @aaron.ballman 
wrote:

> LGTM but we should add a release note for the change.

This fixes P0848R3, which is a clang 16 feature.
If we backport this we don't need a changelog entry.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-22 Thread Shangwu Yao via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8bd13ad6c537: [CUDA][SPIRV] Match builtin types and 
__GCC_ATOMIC_XXX_LOCK_FREE macros on… (authored by shangwuyao).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

Files:
  clang/lib/Basic/Targets/SPIR.h
  clang/test/CodeGenCUDASPIRV/cuda-types.cu

Index: clang/test/CodeGenCUDASPIRV/cuda-types.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDASPIRV/cuda-types.cu
@@ -0,0 +1,56 @@
+// Check that types, widths, __CLANG_ATOMIC* macros, etc. match on the host and
+// device sides of CUDA compilations. Note that we filter out long double and
+// maxwidth of _BitInt(), as this is intentionally different on host and device.
+//
+// Also ignore __CLANG_ATOMIC_LLONG_LOCK_FREE on i386. The default host CPU for
+// an i386 triple is typically at least an i586, which has cmpxchg8b (Clang
+// feature, "cx8"). Therefore, __CLANG_ATOMIC_LLONG_LOCK_FREE is 2 on the host,
+// but the value should be 1 for the device.
+//
+// Unlike CUDA, the width of SPIR-V POINTER type could differ between host and
+// device, because SPIR-V explicitly sets POINTER type width. So it is the
+// user's responsibility to choose the offload with the right POINTER size,
+// otherwise the values for __CLANG_ATOMIC_POINTER_LOCK_FREE could be different.
+
+// RUN: mkdir -p %t
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-device-defines-filtered
+// RUN: diff %t/i386-host-defines-filtered %t/i386-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-device-defines-filtered
+// RUN: diff %t/i386-msvc-host-defines-filtered %t/i386-msvc-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-device-defines-filtered
+// RUN: diff %t/x86_64-host-defines-filtered %t/x86_64-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-device-defines-filtered
+// RUN: diff %t/powerpc64-host-defines-filtered %t/powerpc64-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-device-defines-filtered
+// RUN: diff %t/x86_64-msvc-host-defines-filtered %t/x86_64-msvc-device-defines-filtered
+
Index: clang/lib/Basic/Targets/SPIR.h
===
--- clang/lib/Basic/Targets/SPIR.h
+++ clang/lib/Basic/Targets/SPIR.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 #define LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 
+#include "Targets.h"
 #include "clang/Basic/TargetInf

[clang] 8bd13ad - [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-22 Thread via cfe-commits

Author: ShangwuYao
Date: 2023-02-22T15:44:46Z
New Revision: 8bd13ad6c5374f39408be4a34989007999a57ee9

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

LOG: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on 
host/device

This change matches the CUDA/SPIRV behavior with CUDA/NVPTX, and makes some 
builtin types
and __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device. 
This is only
done when host triple is provided and known, otherwise the behavior is 
unchanged.

Reviewed By: yaxunl

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

Added: 
clang/test/CodeGenCUDASPIRV/cuda-types.cu

Modified: 
clang/lib/Basic/Targets/SPIR.h

Removed: 




diff  --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 24fb2431757c4..0a6ab9ac6b9aa 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 #define LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 
+#include "Targets.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/Support/Compiler.h"
@@ -79,8 +80,10 @@ static const unsigned SPIRDefIsGenMap[] = {
 
 // Base class for SPIR and SPIR-V target info.
 class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public TargetInfo {
+  std::unique_ptr HostTarget;
+
 protected:
-  BaseSPIRTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
+  BaseSPIRTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
   : TargetInfo(Triple) {
 assert((Triple.isSPIR() || Triple.isSPIRV()) &&
"Invalid architecture for SPIR or SPIR-V.");
@@ -98,6 +101,52 @@ class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public 
TargetInfo {
 // Define available target features
 // These must be defined in sorted order!
 NoAsmVariants = true;
+
+llvm::Triple HostTriple(Opts.HostTriple);
+if (!HostTriple.isSPIR() && !HostTriple.isSPIRV() &&
+HostTriple.getArch() != llvm::Triple::UnknownArch) {
+  HostTarget.reset(AllocateTarget(llvm::Triple(Opts.HostTriple), Opts));
+
+  // Copy properties from host target.
+  BoolWidth = HostTarget->getBoolWidth();
+  BoolAlign = HostTarget->getBoolAlign();
+  IntWidth = HostTarget->getIntWidth();
+  IntAlign = HostTarget->getIntAlign();
+  HalfWidth = HostTarget->getHalfWidth();
+  HalfAlign = HostTarget->getHalfAlign();
+  FloatWidth = HostTarget->getFloatWidth();
+  FloatAlign = HostTarget->getFloatAlign();
+  DoubleWidth = HostTarget->getDoubleWidth();
+  DoubleAlign = HostTarget->getDoubleAlign();
+  LongWidth = HostTarget->getLongWidth();
+  LongAlign = HostTarget->getLongAlign();
+  LongLongWidth = HostTarget->getLongLongWidth();
+  LongLongAlign = HostTarget->getLongLongAlign();
+  MinGlobalAlign = HostTarget->getMinGlobalAlign(/* TypeSize = */ 0);
+  NewAlign = HostTarget->getNewAlign();
+  DefaultAlignForAttributeAligned =
+  HostTarget->getDefaultAlignForAttributeAligned();
+  IntMaxType = HostTarget->getIntMaxType();
+  WCharType = HostTarget->getWCharType();
+  WIntType = HostTarget->getWIntType();
+  Char16Type = HostTarget->getChar16Type();
+  Char32Type = HostTarget->getChar32Type();
+  Int64Type = HostTarget->getInt64Type();
+  SigAtomicType = HostTarget->getSigAtomicType();
+  ProcessIDType = HostTarget->getProcessIDType();
+
+  UseBitFieldTypeAlignment = HostTarget->useBitFieldTypeAlignment();
+  UseZeroLengthBitfieldAlignment =
+  HostTarget->useZeroLengthBitfieldAlignment();
+  UseExplicitBitFieldAlignment = 
HostTarget->useExplicitBitFieldAlignment();
+  ZeroLengthBitfieldBoundary = HostTarget->getZeroLengthBitfieldBoundary();
+
+  // This is a bit of a lie, but it controls __GCC_ATOMIC_XXX_LOCK_FREE, 
and
+  // we need those macros to be identical on host and device, because 
(among
+  // other things) they affect which standard library classes are defined,
+  // and we need all classes to be defined on both the host and device.
+  MaxAtomicInlineWidth = HostTarget->getMaxAtomicInlineWidth();
+}
   }
 
 public:

diff  --git a/clang/test/CodeGenCUDASPIRV/cuda-types.cu 
b/clang/test/CodeGenCUDASPIRV/cuda-types.cu
new file mode 100644
index 0..fa0e0b23dc006
--- /dev/null
+++ b/clang/test/CodeGenCUDASPIRV/cuda-types.cu
@@ -0,0 +1,56 @@
+// Check that types, widths, __CLANG_ATOMIC* macros, etc. match on the host and
+// device sides of CUDA compilations. Note that we filter out long double and
+// maxwidth of _BitInt(), as this is intentionally 
diff erent on host and device.
+//
+// Also ignore __CLANG_ATOMIC_LLONG_LOCK_FREE on i386. The default host

[PATCH] D143587: [Docs] Multilib design

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 499511.
michaelplatings marked 8 inline comments as done.
michaelplatings added a comment.

Rebase and apply changes requested by @MaskRay and @peter.smith


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143587

Files:
  clang/docs/Multilib.rst
  clang/docs/index.rst

Index: clang/docs/index.rst
===
--- clang/docs/index.rst
+++ clang/docs/index.rst
@@ -100,6 +100,7 @@
CodeOwners
InternalsManual
DriverInternals
+   Multilib
OffloadingDesign
PCHInternals
ItaniumMangleAbiTags
Index: clang/docs/Multilib.rst
===
--- /dev/null
+++ clang/docs/Multilib.rst
@@ -0,0 +1,327 @@
+
+Multilib
+
+
+Introduction
+
+
+This document describes how multilib is implemented in Clang.
+
+What is multilib and why might you care?
+If you're :doc:`cross compiling` then you can't use native
+system headers and libraries. To address this, you can use a combination of
+``--sysroot``, ``-isystem`` and ``-L`` options to point Clang at suitable
+directories for your target.
+However, when there are many possible directories to choose from, it's not
+necessarily obvious which one to pick.
+Multilib allows a toolchain designer to imbue the toolchain with the ability to
+pick a suitable directory automatically, based on the options the user provides
+to Clang. For example, if the user specifies
+``--target=arm-none-eabi -mcpu=cortex-m4`` the toolchain can choose a directory
+containing headers and libraries suitable for Armv7E-M, because it knows that's
+a suitable architecture for Arm Cortex-M4.
+Multilib can also choose between libraries for the same architecture based on
+other options. For example if the user specifies ``-fno-exceptions`` then a
+toolchain could select libraries built without exception support, thereby
+reducing the size of the resulting binary.
+
+Design
+==
+
+Clang supports GCC's ``-print-multi-lib`` and ``-print-multi-directory``
+options. These are described in
+`GCC Developer Options `_.
+
+There are two ways to configure multilib in Clang: hard-coded or via a
+configuration file.
+
+Hard-coded Multilib
+===
+
+The available libraries can be hard-coded in Clang. Typically this is done
+using the ``MultilibBuilder`` interface in
+``clang/include/clang/Driver/MultilibBuilder.h``.
+There are many examples of this in ``lib/Driver/ToolChains/Gnu.cpp``.
+The remainder of this document will not focus on this type of multilib.
+
+Multilib via configuration file
+===
+
+Some Clang toolchains support loading multilib configuration from a
+``multilib.yaml`` configuration file.
+
+A ``multilib.yaml`` configuration file specifies which multilib variants are
+available, their relative location, what compilation options were used to build
+them, and the criteria by which they are selected.
+
+Multilib processing
+===
+
+Clang goes through the following steps to use multilib from a configuration
+file:
+#. Convert command line arguments to flags. Clang can accept the same
+   information via different arguments - for example,
+   ``--target=arm-none-eabi -march=armv7-m`` and
+   ``--target=armv7m-none-eabi`` are equivalent. Clang can also accept many
+   independent pieces of information within a single flag - for example
+   ``-march=armv8.1m.main+fp+mve`` specifies the architecture and two
+   extensions in a single command line argument.
+   To make it easier for the multilib system, Clang converts the command line
+   arguments into a standard set of simpler "flags". In many cases these flags
+   will look like a command line argument with the leading ``-`` stripped off,
+   but where a suitable form for the flag doesn't exist in command line
+   arguments then its form will be different. For example, an Arm architecture
+   extension is represented like ``march=+mve`` since there's no way to specify
+   it in isolation in a command line argument.
+   To see what flags are emitted for a given set of command line arguments, use
+   the ``-print-multi-selection-flags-experimental`` command line argument
+   along with the rest of the arguments you want to use.
+#. Load ``multilib.yaml`` from sysroot.
+#. Generate additional flags. ``multilib.yaml`` contains a ``flagMap`` section,
+   which specifies how to generate additional flags based on the flags derived
+   from command line arguments. Flags are matched using regular expressions.
+   These regular expressions shall use the POSIX extended regular expression
+   syntax.
+#. Match flags against multilib variants. If the generated flags are a superset
+   of the flags specified for a multilib variant then the variant is considered
+   a mat

[PATCH] D143587: [Docs] Multilib design

2023-02-22 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added inline comments.



Comment at: clang/docs/Multilib.rst:237
+
+Stable API
+--

MaskRay wrote:
> What does "API" refer to? A function defined in llvm-project/clang/lib?
Changed "API" to "interface" and reworded to hopefully make it clearer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143587

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


[PATCH] D144544: [OpenMP] Improve LIT tests on composite target constructs

2023-02-22 Thread Animesh Kumar via Phabricator via cfe-commits
animeshk-amd updated this revision to Diff 499513.
animeshk-amd added a comment.

Removed a pragma line which was not required.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144544

Files:
  clang/test/OpenMP/target_task_affinity_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_reduction_codegen.cpp

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


[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPU.cpp:545
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
   CmdArgs.push_back("-shared");

What's the test against OK_Thin for? ThinLTO is a thing but I don't know if it 
exists (/works) on amdgpu, is this that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

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


[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield accepted this revision.
JonChesterfield added a comment.
This revision is now accepted and ready to land.

NVM the above, all the other call sites to addLTOOptions have that test in them 
so it must be fine


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

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


[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPU.cpp:545
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
   CmdArgs.push_back("-shared");

JonChesterfield wrote:
> What's the test against OK_Thin for? ThinLTO is a thing but I don't know if 
> it exists (/works) on amdgpu, is this that?
AMDGPU's linker is `lld` so it works "in theory". But in practice, separate 
linking of object files isn't fully supported by the ABI. So I consider it a 
"your mileage may vary" scenario. FWIW, it functioned properly with my 
experimental libc setup
```
$ cat main.cpp
int foo();

int main() {
  return foo();
}
$ cat foo.cpp
int foo() { return 3; }
$ clang++ crt1.o main.cpp foo.cpp --target=amdgcn-amd-amdhsa -mcpu=gfx1030 
-Wl,-plugin-opt=mcpu=gfx1030 -nogpulib -o image -flto=thin
$ amdhsa_loader image; echo $?
3
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

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


[clang] c45d2df - [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-02-22T10:14:05-06:00
New Revision: c45d2df05e0e7b6f2517aa2933a24928b4942a3f

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

LOG: [Clang] Add options in LTO mode when cross compiling for AMDGPU

The AMDGPU toolchain support directly compiling GPU images using
cross-compilation such as `clang --target=amdgcn-amd-amdhsa foo.c`.
However, when attempting to link bitcode this does not work because the
`-mcpu` options are not forwarded to the linker among others. This patch
simply adds them so that `clang --target=amdgcn-amd-amdhsa foo.c -flto`
works correctly.

Reviewed By: JonChesterfield

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/test/Driver/amdgpu-toolchain.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index f30c1075eb7a3..08496c1abbc41 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -540,6 +540,9 @@ void amdgpu::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   ArgStringList CmdArgs;
   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
+  if (C.getDriver().isUsingLTO())
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");
   CmdArgs.push_back(Output.getFilename());

diff  --git a/clang/test/Driver/amdgpu-toolchain.c 
b/clang/test/Driver/amdgpu-toolchain.c
index c0a435428de60..a00c75b83f3e0 100644
--- a/clang/test/Driver/amdgpu-toolchain.c
+++ b/clang/test/Driver/amdgpu-toolchain.c
@@ -13,4 +13,4 @@
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
 // RUN:   -flto %s 2>&1 | FileCheck -check-prefix=LTO %s
 // LTO: clang{{.*}} "-flto=full"
-// LTO: ld.lld{{.*}}
+// LTO: ld.lld{{.*}}-plugin-opt=mcpu=gfx906



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


[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc45d2df05e0e: [Clang] Add options in LTO mode when cross 
compiling for AMDGPU (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

Files:
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/test/Driver/amdgpu-toolchain.c


Index: clang/test/Driver/amdgpu-toolchain.c
===
--- clang/test/Driver/amdgpu-toolchain.c
+++ clang/test/Driver/amdgpu-toolchain.c
@@ -13,4 +13,4 @@
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
 // RUN:   -flto %s 2>&1 | FileCheck -check-prefix=LTO %s
 // LTO: clang{{.*}} "-flto=full"
-// LTO: ld.lld{{.*}}
+// LTO: ld.lld{{.*}}-plugin-opt=mcpu=gfx906
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -540,6 +540,9 @@
   ArgStringList CmdArgs;
   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
+  if (C.getDriver().isUsingLTO())
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");
   CmdArgs.push_back(Output.getFilename());


Index: clang/test/Driver/amdgpu-toolchain.c
===
--- clang/test/Driver/amdgpu-toolchain.c
+++ clang/test/Driver/amdgpu-toolchain.c
@@ -13,4 +13,4 @@
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
 // RUN:   -flto %s 2>&1 | FileCheck -check-prefix=LTO %s
 // LTO: clang{{.*}} "-flto=full"
-// LTO: ld.lld{{.*}}
+// LTO: ld.lld{{.*}}-plugin-opt=mcpu=gfx906
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -540,6 +540,9 @@
   ArgStringList CmdArgs;
   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
+  if (C.getDriver().isUsingLTO())
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");
   CmdArgs.push_back(Output.getFilename());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136737: [Draft] [clang] Add builtin_unspecified_value

2023-02-22 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune abandoned this revision.
aqjune added a comment.

Closing this as D142388  added a function 
that can be used instead


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136737

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


[clang] a7b6978 - [clang][doc] Removes obsolete comment.

2023-02-22 Thread Mark de Wever via cfe-commits

Author: Mark de Wever
Date: 2023-02-22T17:17:36+01:00
New Revision: a7b6978285c1c07600d1762b206c1dcec35fe6c8

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

LOG: [clang][doc] Removes obsolete comment.

After reading about the documentation improvements on LLVM weekly this
part seems obsolete.

Reviewed By: ChuanqiXu

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

Added: 


Modified: 
clang/docs/StandardCPlusPlusModules.rst

Removed: 




diff  --git a/clang/docs/StandardCPlusPlusModules.rst 
b/clang/docs/StandardCPlusPlusModules.rst
index d4db37ea6e2e2..8447a44e3f8db 100644
--- a/clang/docs/StandardCPlusPlusModules.rst
+++ b/clang/docs/StandardCPlusPlusModules.rst
@@ -603,16 +603,6 @@ and add the label ``clang:modules`` (if you have 
permissions for that).
 
 For higher level support for proposals, you could visit 
https://clang.llvm.org/cxx_status.html.
 
-Support for clang-scan-deps
-~~~
-
-The support for clang-scan-deps may be the most urgent problem for modules now.
-Without the support for clang-scan-deps, it's hard to involve build systems.
-This means that users could only play with modules through makefiles or by 
writing a parser by hand.
-It blocks more uses for modules, which will block more defect reports or 
requirements.
-
-This is tracked in: https://github.com/llvm/llvm-project/issues/51792.
-
 Ambiguous deduction guide
 ~
 



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


[PATCH] D144497: [clang][doc] Removes obsolete comment.

2023-02-22 Thread Mark de Wever via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa7b6978285c1: [clang][doc] Removes obsolete comment. 
(authored by Mordante).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144497

Files:
  clang/docs/StandardCPlusPlusModules.rst


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -603,16 +603,6 @@
 
 For higher level support for proposals, you could visit 
https://clang.llvm.org/cxx_status.html.
 
-Support for clang-scan-deps
-~~~
-
-The support for clang-scan-deps may be the most urgent problem for modules now.
-Without the support for clang-scan-deps, it's hard to involve build systems.
-This means that users could only play with modules through makefiles or by 
writing a parser by hand.
-It blocks more uses for modules, which will block more defect reports or 
requirements.
-
-This is tracked in: https://github.com/llvm/llvm-project/issues/51792.
-
 Ambiguous deduction guide
 ~
 


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -603,16 +603,6 @@
 
 For higher level support for proposals, you could visit https://clang.llvm.org/cxx_status.html.
 
-Support for clang-scan-deps
-~~~
-
-The support for clang-scan-deps may be the most urgent problem for modules now.
-Without the support for clang-scan-deps, it's hard to involve build systems.
-This means that users could only play with modules through makefiles or by writing a parser by hand.
-It blocks more uses for modules, which will block more defect reports or requirements.
-
-This is tracked in: https://github.com/llvm/llvm-project/issues/51792.
-
 Ambiguous deduction guide
 ~
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143751: [clang][analyzer][NFC] Refactor code of StdLibraryFunctionsChecker.

2023-02-22 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:83
+  }
+
   // The universal integral type to use in value range descriptions.

This enum is moved here from other location, and `negateKind` is added.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:124-125
   // requirement would render the initialization of the Summary map infeasible.
+  // A new value constraint is created furthermore by the negate functionality
+  // of the constraint and returned as pointer.
   using ValueConstraintPtr = std::shared_ptr;

Szelethus wrote:
> Is this what you meant?
Probably this is better:
```
  // Mind that a pointer to a new value constraint can be created by negating 
an existing
  // constraint.
```
The important thing is that one reason for the shared pointer is the negate 
function that returns a pointer.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:218
+  /// Check if a single argument falls into a specific range.
+  /// The "range" can be built from sub-ranges that are closed intervals.
   class RangeConstraint : public ValueConstraint {

Szelethus wrote:
> If you want a killer doc, use examples. Not saying this is not good enough, 
> but it wouldn't hurt.
The "range" is not the best term for this object in the documentation. A 
"range" is often used when a single interval is meant, but here it often means 
a set of ranges. I plan to improve this.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:271
+
+  private:
+using RangeApplyFunction =

This new private section is the new added code.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:275
+
+/// @brief Apply a function on all intervals in the range.
+void applyOnWithinRange(

The "@brief" is probably not necessary and not used often, I plan to remove it.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:893
 
-std::string StdLibraryFunctionsChecker::NotNullConstraint::describe(
-DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
-const Summary &Summary) const {
-  SmallString<48> Result;
-  const auto Violation = ValueConstraint::DescriptionKind::Violation;
-  Result += "the ";
-  Result += getArgDesc(ArgN);
-  Result += " to '";
-  Result += getFunctionName(Call);
-  Result += DK == Violation ? "' should not be NULL" : "' is not NULL";
-  return Result.c_str();
+void StdLibraryFunctionsChecker::RangeConstraint::applyOnWithinRange(
+BasicValueFactory &BVF, QualType ArgT, const RangeApplyFunction &F) const {

This code is got from `RangeConstraint::applyAsOutOfRange`.
This becomes "within" because in the apply as out of range case all ranges are 
cut out, that is really a loop over ("within") the ranges.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:910
+void StdLibraryFunctionsChecker::RangeConstraint::applyOnOutOfRange(
+BasicValueFactory &BVF, QualType ArgT, const RangeApplyFunction &F) const {
+  if (Ranges.empty())

This code is got from `RangeConstraint::applyWithinRange`.
That was implemented by removal of all out-of-range intervals. The code here is 
a general version that calls a lambda instead of the actual assume calls, so it 
becomes reusable for other purposes when a loop over all (out-of) intervals is 
used.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1060
+  const Summary &Summary,
+  CheckerContext &C) const {
+  SValBuilder &SvalBuilder = C.getSValBuilder();

This function is just moved here from the previous (inline) location.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1143
+  if (ExplodedNode *N = C.generateErrorNode(State, NewNode))
+reportBug(Call, N, Constraint.get(), NegatedConstraint.get(), Summary, 
C);
   break;

The new argument in `reportBug` is not used but is used in the next patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143751

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


[PATCH] D143210: [PowerPC] Include vector bool and pixel when emitting lax warning

2023-02-22 Thread Kamau Bridgeman via Phabricator via cfe-commits
kamaub added a comment.

We may also need an associated test case for the changed behaviour for using 
`areCompatibleVectorTypes()` instead of `areSameVectorElemTypes()`.
The test coverage should display when warnings are emitted now that we account 
for vector bool, vector pixel and type qualifiers.




Comment at: clang/lib/Sema/SemaExpr.cpp:9861
   isLaxVectorConversion(RHSType, LHSType)) {
-if (VecType->getVectorKind() == VectorType::AltiVecVector)
+if (VecType->getVectorKind() == VectorType::AltiVecVector ||
+VecType->getVectorKind() == VectorType::AltiVecBool ||

Is there test coverage for these addition to the if condition?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143210

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


[PATCH] D135495: [clang-tidy] handle exceptions properly in `ExceptionAnalyzer`

2023-02-22 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I think at this point it is ok to merge. Any other comments can be addressed in 
follow-up commits.


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

https://reviews.llvm.org/D135495

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


[PATCH] D142569: [OpenMP] Introduce kernel environment

2023-02-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: 
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp:583
+  if (!KernelEnvOrError)
+return KernelEnvOrError.takeError();
+

tianshilei1992 wrote:
> jdoerfert wrote:
> > We used to default to SPMD w/o a _exec_mode. Unsure if this will cause 
> > problems. I am inclined to allow missing _kernel_env as well and use SPMD 
> > then.
> Now we need the global variable to call `target_init` at runtime, so missing 
> it sounds like a bug. I'm not sure if we would optimize the symbol out, but I 
> kinda doubt it.
Missing used to mean, and does, that it's not a "target region" kernel. So it 
might be a con/de-structor or a kernel coming from elsewhere, e.g., CUDA. We 
should continue that behavior I think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142569

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


[PATCH] D144569: [Clang][OpenMP] Fix accessing of aligned arrays in offloaded target regions

2023-02-22 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
doru1004 created this revision.
doru1004 added reviewers: jdoerfert, jhuber6, ronl, carlo.bertolli, arsenm, 
gregrodgers, ABataev.
doru1004 added a project: OpenMP.
Herald added subscribers: kosarev, kerbowa, guansong, yaxunl, jvesely.
Herald added a project: All.
doru1004 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, wdng.
Herald added a project: clang.

This patch fixes a memory error that occurs when we access an aligned array on 
the device:

  void write_index(int*a, int N) {
  int *aptr __attribute__ ((aligned(64))) = a; // This failed but is fixed 
by this patch.
  #pragma omp target teams distribute parallel for map(tofrom: aptr[0:N])
  for(int i=0;ihttps://reviews.llvm.org/D144569

Files:
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/amdgpu_target_with_aligned_attribute.c

Index: clang/test/OpenMP/amdgpu_target_with_aligned_attribute.c
===
--- /dev/null
+++ clang/test/OpenMP/amdgpu_target_with_aligned_attribute.c
@@ -0,0 +1,305 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _
+// REQUIRES: amdgpu-registered-target
+
+// expected-no-diagnostics
+#ifndef HEADER
+#define HEADER
+
+// RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host-amd.bc
+// RUN: %clang_cc1 -verify -fopenmp -x c -triple amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host-amd.bc -o - | FileCheck %s --check-prefix=CHECK-AMD
+
+
+void write_to_aligned_array(int *a, int N) {
+  int *aptr __attribute__ ((aligned(64))) = a;
+  #pragma omp target teams distribute parallel for map(tofrom: aptr[0:N])
+  for(int i = 0; i < N; i++) {
+aptr[i] = i;
+  }
+}
+
+#endif
+// CHECK-AMD-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_write_to_aligned_array_l14
+// CHECK-AMD-SAME: (i64 noundef [[N:%.*]], ptr noundef [[APTR:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-AMD-NEXT:  entry:
+// CHECK-AMD-NEXT:[[N_ADDR:%.*]] = alloca i64, align 8, addrspace(5)
+// CHECK-AMD-NEXT:[[APTR_ADDR:%.*]] = alloca ptr, align 8, addrspace(5)
+// CHECK-AMD-NEXT:[[N_CASTED:%.*]] = alloca i64, align 8, addrspace(5)
+// CHECK-AMD-NEXT:[[DOTZERO_ADDR:%.*]] = alloca i32, align 4, addrspace(5)
+// CHECK-AMD-NEXT:[[DOTTHREADID_TEMP_:%.*]] = alloca i32, align 4, addrspace(5)
+// CHECK-AMD-NEXT:[[N_ADDR_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[N_ADDR]] to ptr
+// CHECK-AMD-NEXT:[[APTR_ADDR_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[APTR_ADDR]] to ptr
+// CHECK-AMD-NEXT:[[N_CASTED_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[N_CASTED]] to ptr
+// CHECK-AMD-NEXT:[[DOTZERO_ADDR_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[DOTZERO_ADDR]] to ptr
+// CHECK-AMD-NEXT:[[DOTTHREADID_TEMP__ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[DOTTHREADID_TEMP_]] to ptr
+// CHECK-AMD-NEXT:store i64 [[N]], ptr [[N_ADDR_ASCAST]], align 8
+// CHECK-AMD-NEXT:store ptr [[APTR]], ptr [[APTR_ADDR_ASCAST]], align 8
+// CHECK-AMD-NEXT:[[TMP0:%.*]] = call i32 @__kmpc_target_init(ptr addrspacecast (ptr addrspace(1) @[[GLOB1:[0-9]+]] to ptr), i8 2, i1 false)
+// CHECK-AMD-NEXT:[[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1
+// CHECK-AMD-NEXT:br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]]
+// CHECK-AMD:   user_code.entry:
+// CHECK-AMD-NEXT:[[TMP1:%.*]] = call i32 @__kmpc_global_thread_num(ptr addrspacecast (ptr addrspace(1) @[[GLOB1]] to ptr))
+// CHECK-AMD-NEXT:[[TMP2:%.*]] = load i32, ptr [[N_ADDR_ASCAST]], align 4
+// CHECK-AMD-NEXT:store i32 [[TMP2]], ptr [[N_CASTED_ASCAST]], align 4
+// CHECK-AMD-NEXT:[[TMP3:%.*]] = load i64, ptr [[N_CASTED_ASCAST]], align 8
+// CHECK-AMD-NEXT:[[TMP4:%.*]] = load ptr, ptr [[APTR_ADDR_ASCAST]], align 8
+// CHECK-AMD-NEXT:store i32 0, ptr [[DOTZERO_ADDR_ASCAST]], align 4
+// CHECK-AMD-NEXT:store i32 [[TMP1]], ptr [[DOTTHREADID_TEMP__ASCAST]], align 4
+// CHECK-AMD-NEXT:call void @__omp_outlined__(ptr [[DOTTHREADID_TEMP__ASCAST]], ptr [[DOTZERO_ADDR_ASCAST]], i64 [[TMP3]], ptr [[TMP4]]) #[[ATTR2:[0-9]+]]
+// CHECK-AMD-NEXT:call void @__kmpc_target_deinit(ptr addrspacecast (ptr addrspace(1) @[[GLOB1]] to ptr), i8 2)
+// CHECK-AMD-NEXT:ret void
+// CHECK-AMD:   worker.exit:
+// CHECK-AMD-NEXT:ret void
+//
+//
+// CHECK-AMD-LABEL: define {{[^@]+}}@__omp_outlined__
+// CHECK-AMD-SAME: (ptr noalias noundef [[DOTGLOBAL_TID_:%.*]], ptr noalias noundef [[DOTBOUND_TID_:%.*]], i64 noundef [[N:%.*]], ptr noundef [[APTR:%.*]]) #[[ATTR1:[0-9]+]] {
+// CHECK-AMD-NEXT:  entry:
+// CHECK-AMD-NEXT:[[DOTGLOB

[PATCH] D144540: [Clang] [Doc] Explicitly note noreturn bug as a miscompilation

2023-02-22 Thread Sam James via Phabricator via cfe-commits
thesamesam closed this revision.
thesamesam added a comment.

Thanks! Merged.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144540

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


[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 499553.
VitaNuo marked 24 inline comments as done.
VitaNuo added a comment.

Address review comments (apart from testing).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp

Index: clang-tools-extra/include-cleaner/lib/Analysis.cpp
===
--- clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -49,8 +49,8 @@
   }
 }
 
-static std::string spellHeader(const Header &H, HeaderSearch &HS,
-   const FileEntry *Main) {
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main) {
   switch (H.kind()) {
   case Header::Physical: {
 bool IsSystem = false;
Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -73,6 +73,8 @@
 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
 const format::FormatStyle &IncludeStyle);
 
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main);
 } // namespace include_cleaner
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -9,11 +9,19 @@
 #include "Annotations.h"
 #include "Config.h"
 #include "IncludeCleaner.h"
+#include "ParsedAST.h"
 #include "SourceCode.h"
 #include "TestFS.h"
 #include "TestTU.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "support/Context.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ScopeExit.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -342,7 +350,8 @@
   auto AST = TU.build();
   EXPECT_THAT(computeUnusedIncludes(AST),
   ElementsAre(Pointee(writtenInclusion("";
-  EXPECT_THAT(computeUnusedIncludesExperimental(AST),
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
+  EXPECT_THAT(Findings.UnusedIncludes,
   ElementsAre(Pointee(writtenInclusion("";
 }
 
@@ -379,12 +388,69 @@
   computeUnusedIncludes(AST),
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
+
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
   EXPECT_THAT(
-  computeUnusedIncludesExperimental(AST),
+  Findings.UnusedIncludes,
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
+  const SourceManager &SM = AST.getSourceManager();
+  const llvm::ArrayRef &Tokens =
+  AST.getTokens().spelledTokens(

[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-22 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the comments! I should have addressed everything apart from testing.




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:523
+TransformedInc.Angled = WrittenRef.starts_with("<");
+if (auto FE = SM.getFileManager().getFile(Inc.Resolved))
+  TransformedInc.Resolved = *FE;

kadircet wrote:
> VitaNuo wrote:
> > kadircet wrote:
> > > i don't think we should convert any unresolved includes. it usually means 
> > > header wasn't found, so we can't perform any reliable analysis on them. 
> > > anything i am missing?
> > Ok I will skip unresolved includes. But I am not sure I fully understand. 
> > We do the following:
> > 1. Convert clangd includes to include-cleaner includes.
> > 2. Match include-cleaner includes with symbol providers.
> > 3. If match found, symbol reference is satisfied.
> > 
> > How does it matter in this scenario if the include is resolved? AFAIU as 
> > long as the header is spelled in the main file + it's matched with a symbol 
> > provider, we should say that the symbol reference is satisfied.
> > 
> > Otherwise, it seems like we'll say that the header is missing, although 
> > it's there in the main file and unresolved.
> > 
> > I don't know if this is in any way a realistic scenario. I am just 
> > approaching it with general logic, and in this sense having more 
> > "satisfied" symbols seems better than having less => leads to less false 
> > positives. It can lead to false negatives, too, but AFAIU false negatives 
> > are much less of a risk for missing include management. 
> > How does it matter in this scenario if the include is resolved? AFAIU as 
> > long as the header is spelled in the main file + it's matched with a symbol 
> > provider, we should say that the symbol reference is satisfied.
> 
> It doesn't matter at a high-level view. But since the implementation 
> recognizes headers based on the HeaderID and it's only defined for resolved 
> includes, if we were to have any unresolved include matches somehow (e.g. it 
> has spelling "foo/bar.h", but is unresolved, and we do a match based on 
> spelling because some IWYU pragma pointed at this header), we would hit the 
> assertion around HeaderID always having value.
Ah ok, makes sense.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:535
+  Diag D;
+  D.Message = llvm::formatv("header {0} is missing", Spelling);
+  D.Name = "missing-includes";

kadircet wrote:
> VitaNuo wrote:
> > kadircet wrote:
> > > i think the symbol name should also be part of the diagnostic. as editors 
> > > can show these diagnostics without context (e.g. you've got a big file 
> > > open, there's a diagnostic panel displaying messages/fixes for all of the 
> > > file. you should be able to reason about the diagnostics and fixes 
> > > without jumping all over the file). so maybe something like:
> > > 
> > > `formatv("{0} providing '{1}' is not directly included", Header, Symbol)`
> > Sure. The new design does this, as well as skipping the header name.
> i feel like there's actually value in keeping the header name around, i.e. 
> the user will have some idea about the action, without triggering an extra 
> interaction. this helps especially in cases where the finding is wrong, 
> they'll discover this sooner, hence we'll be more likely to receive bug 
> reports. but don't really have a strong preference, so feel free to keep it 
> that way.
Hm I'd expect we'll actually have a higher probability to receive a bug report 
if the user clicks on the "Quick fix" and gets a wrong header included, because 
that's annoying :)
Having a full message on hover, seeing that it's wrong and just ignoring it 
might not be annoying enough to file a bug ;-)

But this is a pure speculation ofc.
I think the point discussed on the design document makes sense: without 
mentioning the header name it will be a bit easier to extend this to suggesting 
multiple fixes. So if that's the general direction, I'd prefer to keep it the 
current way.




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:549
+  bool Angled = HeaderRef.starts_with("<");
+  std::optional Replacement = HeaderIncludes.insert(
+  HeaderRef.trim("\"<>"), Angled, tooling::IncludeDirective::Include);

kadircet wrote:
> VitaNuo wrote:
> > kadircet wrote:
> > > this returns nullopt only if Header is already included in the main file. 
> > > our analysis should never suggest such a header for include, unless the 
> > > include is coming from a PP-disabled region.
> > > 
> > > so i think if Replacement generation fails, we should drop the diagnostic 
> > > completely rather than just dropping the fix. WDYT?
> > Ok, sure. What's a PP-disabled region? Are you talking about #ifdef's and 
> > such?
> > What's a PP-disabled region
> 
> Yes, I was trying to say "preprocessor disabled region". e.g. in a piece of 
> code like:
> ```
> #if 0
> #include "

[PATCH] D142569: [OpenMP] Introduce kernel environment

2023-02-22 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 499555.
tianshilei1992 marked 2 inline comments as done.
tianshilei1992 added a comment.

rebase and fix comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142569

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/test/Headers/amdgcn_openmp_device_math_c.c
  clang/test/OpenMP/amdgcn_target_codegen.cpp
  clang/test/OpenMP/declare_target_codegen_globalization.cpp
  clang/test/OpenMP/nvptx_SPMD_codegen.cpp
  clang/test/OpenMP/nvptx_data_sharing.cpp
  clang/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_multi_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_nested_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_for_codegen.cpp
  clang/test/OpenMP/nvptx_target_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_num_threads_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen_tbaa_PR46146.cpp
  clang/test/OpenMP/nvptx_target_printf_codegen.c
  clang/test/OpenMP/nvptx_target_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
  
clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp
  clang/test/OpenMP/nvptx_teams_codegen.cpp
  clang/test/OpenMP/nvptx_teams_reduction_codegen.cpp
  clang/test/OpenMP/reduction_implicit_map.cpp
  clang/test/OpenMP/remarks_parallel_in_multiple_target_state_machines.c
  clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
  clang/test/OpenMP/target_parallel_debug_codegen.cpp
  clang/test/OpenMP/target_parallel_for_debug_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp
  openmp/libomptarget/DeviceRTL/CMakeLists.txt
  openmp/libomptarget/DeviceRTL/include/Debug.h
  openmp/libomptarget/DeviceRTL/include/Interface.h
  openmp/libomptarget/DeviceRTL/include/State.h
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Debug.cpp
  openmp/libomptarget/DeviceRTL/src/Kernel.cpp
  openmp/libomptarget/DeviceRTL/src/State.cpp
  openmp/libomptarget/include/DeviceEnvironment.h
  openmp/libomptarget/include/Environment.h
  openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
  openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
  openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
  openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
  openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp
  openmp/libomptarget/plugins/amdgpu/src/rtl.cpp
  openmp/libomptarget/plugins/cuda/src/rtl.cpp

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


[PATCH] D143052: [CMake] Unify llvm_check_linker_flag and llvm_check_compiler_linker_flag

2023-02-22 Thread Petr Hosek via Phabricator via cfe-commits
phosek updated this revision to Diff 499561.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143052

Files:
  clang/tools/driver/CMakeLists.txt
  cmake/Modules/LLVMCheckCompilerLinkerFlag.cmake
  compiler-rt/cmake/config-ix.cmake
  libcxx/cmake/config-ix.cmake
  libunwind/cmake/config-ix.cmake
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/HandleLLVMOptions.cmake
  llvm/cmake/modules/HandleLLVMStdlib.cmake
  llvm/cmake/modules/LLVMCheckLinkerFlag.cmake
  runtimes/CMakeLists.txt

Index: runtimes/CMakeLists.txt
===
--- runtimes/CMakeLists.txt
+++ runtimes/CMakeLists.txt
@@ -78,7 +78,7 @@
 set(LLVM_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../llvm)
 
 include(CheckLibraryExists)
-include(LLVMCheckCompilerLinkerFlag)
+include(CheckLinkerFlag)
 include(CheckCCompilerFlag)
 include(CheckCXXCompilerFlag)
 
@@ -110,7 +110,7 @@
   # --unwindlib=none is supported, and use that if possible.
   # Don't add this if not necessary to fix linking, as it can break using
   # e.g. ASAN/TSAN.
-  llvm_check_compiler_linker_flag(C "--unwindlib=none" CXX_SUPPORTS_UNWINDLIB_EQ_NONE_FLAG)
+  check_linker_flag(C "--unwindlib=none" CXX_SUPPORTS_UNWINDLIB_EQ_NONE_FLAG)
   if (CXX_SUPPORTS_UNWINDLIB_EQ_NONE_FLAG)
 set(ORIG_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}")
 set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} --unwindlib=none")
@@ -140,7 +140,7 @@
 # Check for -nostdlib++ first; if there's no C++ standard library yet,
 # all check_cxx_compiler_flag commands will fail until we add -nostdlib++
 # (or -nodefaultlibs).
-llvm_check_compiler_linker_flag(CXX "-nostdlib++" CXX_SUPPORTS_NOSTDLIBXX_FLAG)
+check_linker_flag(CXX "-nostdlib++" CXX_SUPPORTS_NOSTDLIBXX_FLAG)
 if (CXX_SUPPORTS_NOSTDLIBXX_FLAG)
   set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -nostdlib++")
 endif()
Index: llvm/cmake/modules/LLVMCheckLinkerFlag.cmake
===
--- llvm/cmake/modules/LLVMCheckLinkerFlag.cmake
+++ /dev/null
@@ -1,28 +0,0 @@
-include(CheckLinkerFlag OPTIONAL)
-
-if (COMMAND check_linker_flag)
-  macro(llvm_check_linker_flag)
-check_linker_flag(${ARGN})
-  endmacro()
-else()
-  # Until the minimum CMAKE version is 3.18
-
-  include(CheckCXXCompilerFlag)
-
-  # cmake builtin compatible, except we assume lang is C or CXX
-  function(llvm_check_linker_flag lang flag out_var)
-cmake_policy(PUSH)
-cmake_policy(SET CMP0056 NEW)
-set(_CMAKE_EXE_LINKER_FLAGS_SAVE ${CMAKE_EXE_LINKER_FLAGS})
-set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${flag}")
-if("${lang}" STREQUAL "C")
-  check_c_compiler_flag("" ${out_var})
-elseif("${lang}" STREQUAL "CXX")
-  check_cxx_compiler_flag("" ${out_var})
-else()
-  message(FATAL_ERROR "\"${lang}\" is not C or CXX")
-endif()
-set(CMAKE_EXE_LINKER_FLAGS ${_CMAKE_EXE_LINKER_FLAGS_SAVE})
-cmake_policy(POP)
-  endfunction()
-endif()
Index: llvm/cmake/modules/HandleLLVMStdlib.cmake
===
--- llvm/cmake/modules/HandleLLVMStdlib.cmake
+++ llvm/cmake/modules/HandleLLVMStdlib.cmake
@@ -13,12 +13,12 @@
   endfunction()
 
   include(CheckCXXCompilerFlag)
-  include(LLVMCheckLinkerFlag)
+  include(CheckLinkerFlag)
   set(LLVM_LIBCXX_USED 0)
   if(LLVM_ENABLE_LIBCXX)
 if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
   check_cxx_compiler_flag("-stdlib=libc++" CXX_COMPILER_SUPPORTS_STDLIB)
-  llvm_check_linker_flag(CXX "-stdlib=libc++" CXX_LINKER_SUPPORTS_STDLIB)
+  check_linker_flag(CXX "-stdlib=libc++" CXX_LINKER_SUPPORTS_STDLIB)
   if(CXX_COMPILER_SUPPORTS_STDLIB AND CXX_LINKER_SUPPORTS_STDLIB)
 append("-stdlib=libc++"
   CMAKE_CXX_FLAGS CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS
@@ -36,7 +36,7 @@
 if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
   check_cxx_compiler_flag("-static-libstdc++"
   CXX_COMPILER_SUPPORTS_STATIC_STDLIB)
-  llvm_check_linker_flag(CXX "-static-libstdc++" CXX_LINKER_SUPPORTS_STATIC_STDLIB)
+  check_linker_flag(CXX "-static-libstdc++" CXX_LINKER_SUPPORTS_STATIC_STDLIB)
   if(CXX_COMPILER_SUPPORTS_STATIC_STDLIB AND
 CXX_LINKER_SUPPORTS_STATIC_STDLIB)
 append("-static-libstdc++"
Index: llvm/cmake/modules/HandleLLVMOptions.cmake
===
--- llvm/cmake/modules/HandleLLVMOptions.cmake
+++ llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -968,8 +968,8 @@
   if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
   CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
 add_compile_options(-gsplit-dwarf)
-include(LLVMCheckLinkerFlag)
-llvm_check_linker_flag(CXX "-Wl,--gdb-index" LINKER_SUPPORTS_GDB_INDEX)
+include(CheckLinkerFlag)
+check_linker_flag(CXX "-Wl,--gdb-index" LIN

[PATCH] D144572: [C++20] Stop claiming full support for consteval (for the moment!)

2023-02-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: cor3ntin, erichkeane, royjacobson, 
clang-language-wg.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a project: clang.

During Clang 15, 3d2629dd3aab17098813c68b5b76bb864bc5e285 
 claimed 
we achieved full support for `consteval` in C++20. However, further testing 
shows that Clang doesn't correctly handle all of the examples from 
https://wg21.link/P1073R3 and has several other known issues that are 
preventing us from defining the `__cpp_consteval` macro.

I think we should only claim Partial support for the moment. Once we correct 
the major outstanding issues, then I think we should change the status back to 
full support and define `__cpp_consteval` at the same time (even if it's only 
to the `201811L` value instead of the latest value from C++2b). This helps 
users understand the support situation more clearly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144572

Files:
  clang/test/CXX/expr/expr.const/p6-2a.cpp
  clang/test/CXX/expr/expr.const/p8-2a.cpp
  clang/www/cxx_status.html


Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1120,7 +1120,14 @@
 
   Immediate functions (consteval)
   https://wg21.link/p1073r3";>P1073R3
-  Clang 15
+  
+Clang 15 (Partial)
+  Clang still incorrectly defers some consteval executions to runtime,
+  resulting in CodeGen crashes. Additionally, Clang does not properly
+  handle default arguments in consteval functions under all
+  circumstances.
+
+  
 

 https://wg21.link/p1937r2";>P1937R2
Index: clang/test/CXX/expr/expr.const/p8-2a.cpp
===
--- /dev/null
+++ clang/test/CXX/expr/expr.const/p8-2a.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+// expected-no-diagnostics
+
+namespace P1073R3 {
+struct N {
+  constexpr N() {}
+  N(N const&) = delete;
+};
+
+template constexpr void bad_assert_copyable() { T t; T t2 = t; }
+using ineffective = decltype(bad_assert_copyable());
+
+// bad_assert_copyable is not needed for constant evaluation
+// (and thus not instantiated)
+template consteval void assert_copyable() { T t; T t2 = t; }
+using check = decltype(assert_copyable());
+// FIXME: this should give an error because assert_copyable is instantiated
+// (because it is needed for constant evaluation), but the attempt to copy t is
+// ill-formed.
+} // namespace P1073R3
+
Index: clang/test/CXX/expr/expr.const/p6-2a.cpp
===
--- clang/test/CXX/expr/expr.const/p6-2a.cpp
+++ clang/test/CXX/expr/expr.const/p6-2a.cpp
@@ -41,3 +41,16 @@
   }
 };
 constexpr Temporary t = {3}; // expected-error {{must have constant 
destruction}} expected-note {{created here}} expected-note {{in call}}
+
+namespace P1073R3 {
+consteval int f() { return 42; } // expected-note 3 {{declared here}}
+consteval auto g() { return f; }
+// FIXME: there should be no diagnostics associated with either h() or r.
+consteval int h(int (*p)() = g()) { return p(); } // expected-error {{call to 
consteval function 'P1073R3::g' is not a constant expression}} \
+ expected-note {{declared 
here}} \
+ expected-note {{pointer 
to a consteval declaration is not a constant expression}}
+constexpr int r = h();   // expected-note {{in the default initalizer of 'p'}}
+constexpr auto e = g();  // expected-error {{call to consteval function 
'P1073R3::g' is not a constant expression}} \
+expected-error {{constexpr variable 'e' must be 
initialized by a constant expression}} \
+expected-note 2 {{pointer to a consteval 
declaration is not a constant expression}}
+} // namespace P1073R3


Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1120,7 +1120,14 @@
 
   Immediate functions (consteval)
   https://wg21.link/p1073r3";>P1073R3
-  Clang 15
+  
+Clang 15 (Partial)
+  Clang still incorrectly defers some consteval executions to runtime,
+  resulting in CodeGen crashes. Additionally, Clang does not properly
+  handle default arguments in consteval functions under all
+  circumstances.
+
+  
 

 https://wg21.link/p1937r2";>P1937R2
Index: clang/test/CXX/expr/expr.const/p8-2a.cpp
===
--- /dev/null
+++ clang/test/CXX/expr/expr.const/p8-2a.cpp
@@ -0,0 +1,22 @@
+// RU

[PATCH] D144149: [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Thanks for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144149

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


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think this needs additional test coverage around `_BitInt` as those can be 
arbitrarily large depending on the target. Also, C2x made changes in this area 
to how we calculate what type to represent the enumerations in; we don't have 
to implement that support as part of this patch, but we should make sure what 
we're doing doesn't conflict with that future work.

(Also, please add a release note for the changes.)




Comment at: clang/lib/Sema/SemaDecl.cpp:19571-19573
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.

h-vetinari wrote:
> That comment is still relevant AFAICT, at least partially (the ISO C 
> restrictions are still there, GCC still extends it)
Not only is it still relevant, there were changes for C2x in this area. See 
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2997.htm for more details.



Comment at: clang/lib/Sema/SemaDecl.cpp:19698-19699
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&

Consider (in C2x):
```
enum E {
  Val = 0x''''''''1wb
};
```



Comment at: clang/lib/Sema/SemaDecl.cpp:19700-19702
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL in target without "
+ "128-bit interger type support?");

Again, `_BitInt`.


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

https://reviews.llvm.org/D144157

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


[PATCH] D144509: [CMake] Bumps minimum version to 3.20.0.

2023-02-22 Thread Mark de Wever via Phabricator via cfe-commits
Mordante updated this revision to Diff 499569.
Mordante added a comment.
Herald added a subscriber: mstorsjo.

Try to fix AIX CI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144509

Files:
  bolt/runtime/CMakeLists.txt
  clang/CMakeLists.txt
  clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt
  compiler-rt/CMakeLists.txt
  compiler-rt/lib/builtins/CMakeLists.txt
  compiler-rt/lib/crt/CMakeLists.txt
  flang/CMakeLists.txt
  flang/lib/Decimal/CMakeLists.txt
  flang/runtime/CMakeLists.txt
  libc/CMakeLists.txt
  libc/examples/hello_world/CMakeLists.txt
  libclc/CMakeLists.txt
  libcxx/CMakeLists.txt
  libcxxabi/CMakeLists.txt
  libunwind/CMakeLists.txt
  libunwind/src/CMakeLists.txt
  lld/CMakeLists.txt
  lldb/CMakeLists.txt
  lldb/tools/debugserver/CMakeLists.txt
  llvm-libgcc/CMakeLists.txt
  llvm/CMakeLists.txt
  llvm/docs/CMake.rst
  llvm/docs/GettingStarted.rst
  llvm/docs/ReleaseNotes.rst
  mlir/CMakeLists.txt
  mlir/examples/standalone/CMakeLists.txt
  openmp/CMakeLists.txt
  openmp/cmake/DetectTestCompiler/CMakeLists.txt
  openmp/docs/SupportAndFAQ.rst
  openmp/libompd/src/CMakeLists.txt
  openmp/libomptarget/plugins/remote/src/CMakeLists.txt
  openmp/runtime/cmake/LibompCheckLinkerFlag.cmake
  openmp/tools/Modules/FindOpenMPTarget.cmake
  openmp/tools/Modules/README.rst
  polly/CMakeLists.txt
  pstl/CMakeLists.txt
  runtimes/CMakeLists.txt

Index: runtimes/CMakeLists.txt
===
--- runtimes/CMakeLists.txt
+++ runtimes/CMakeLists.txt
@@ -1,12 +1,5 @@
 # This file handles building LLVM runtime sub-projects.
-cmake_minimum_required(VERSION 3.13.4)
-if ("${CMAKE_VERSION}" VERSION_LESS "3.20.0")
-  message(WARNING
-"Your CMake version is ${CMAKE_VERSION}. Starting with LLVM 17.0.0, the "
-"minimum version of CMake required to build LLVM will become 3.20.0, and "
-"using an older CMake will become an error. Please upgrade your CMake to "
-"at least 3.20.0 now to avoid issues in the future!")
-endif()
+cmake_minimum_required(VERSION 3.20.0)
 project(Runtimes C CXX ASM)
 
 # Add path for custom and the LLVM build's modules to the CMake module path.
Index: pstl/CMakeLists.txt
===
--- pstl/CMakeLists.txt
+++ pstl/CMakeLists.txt
@@ -5,7 +5,7 @@
 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 #
 #===--===##
-cmake_minimum_required(VERSION 3.13.4)
+cmake_minimum_required(VERSION 3.20.0)
 
 set(PARALLELSTL_VERSION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/include/pstl/internal/pstl_config.h")
 file(STRINGS "${PARALLELSTL_VERSION_FILE}" PARALLELSTL_VERSION_SOURCE REGEX "#define _PSTL_VERSION .*$")
Index: polly/CMakeLists.txt
===
--- polly/CMakeLists.txt
+++ polly/CMakeLists.txt
@@ -1,14 +1,7 @@
 # Check if this is a in tree build.
 if (NOT DEFINED LLVM_MAIN_SRC_DIR)
   project(Polly)
-  cmake_minimum_required(VERSION 3.13.4)
-  if ("${CMAKE_VERSION}" VERSION_LESS "3.20.0")
-message(WARNING
-  "Your CMake version is ${CMAKE_VERSION}. Starting with LLVM 17.0.0, the "
-  "minimum version of CMake required to build LLVM will become 3.20.0, and "
-  "using an older CMake will become an error. Please upgrade your CMake to "
-  "at least 3.20.0 now to avoid issues in the future!")
-  endif()
+  cmake_minimum_required(VERSION 3.20.0)
   set(POLLY_STANDALONE_BUILD TRUE)
 endif()
 
Index: openmp/tools/Modules/README.rst
===
--- openmp/tools/Modules/README.rst
+++ openmp/tools/Modules/README.rst
@@ -26,7 +26,7 @@
 
 .. code-block:: cmake
 
-  cmake_minimum_required(VERSION 3.13.4)
+  cmake_minimum_required(VERSION 3.20.0)
   project(offloadTest VERSION 1.0 LANGUAGES CXX)
 
   list(APPEND CMAKE_MODULE_PATH "${PATH_TO_OPENMP_INSTALL}/lib/cmake/openmp")
@@ -37,7 +37,7 @@
   target_link_libraries(offload PRIVATE OpenMPTarget::OpenMPTarget_NVPTX)
   target_sources(offload PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/Main.cpp)
 
-Using this module requires at least CMake version 3.13.4. Supported languages
+Using this module requires at least CMake version 3.20.0. Supported languages
 are C and C++ with Fortran support planned in the future. If your application
 requires building for a specific device architecture you can set the
 ``OpenMPTarget__ARCH=`` variable. Compiler support is best for
Index: openmp/tools/Modules/FindOpenMPTarget.cmake
===
--- openmp/tools/Modules/FindOpenMPTarget.cmake
+++ openmp/tools/Modules/FindOpenMPTarget.cmake
@@ -79,7 +79,7 @@
 # TODO: Test more compilers
 
 cmake_policy(PUSH)
-cmake_policy(VERSION 3.13.4)
+cmake_policy(VERSION 3.20.0)
 
 find_package(OpenMP ${OpenMPTarget_FIND_VERSION} 

[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/test/Driver/amdgpu-toolchain.c:7
 // RUN: %clang -### -g --target=amdgcn-mesa-mesa3d -mcpu=kaveri %s 2>&1 | 
FileCheck -check-prefix=DWARF_VER %s
 
 // AS_LINK: "-cc1as"

should add a test for thinlto? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

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


[PATCH] D144505: [Clang] Add options in LTO mode when cross compiling for AMDGPU

2023-02-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/test/Driver/amdgpu-toolchain.c:7
 // RUN: %clang -### -g --target=amdgcn-mesa-mesa3d -mcpu=kaveri %s 2>&1 | 
FileCheck -check-prefix=DWARF_VER %s
 
 // AS_LINK: "-cc1as"

arsenm wrote:
> should add a test for thinlto? 
Only thing it would change is adding `-plugin-opt=thinlto`. Not sure if it's 
worth a test since it's probably checked by other uses of `addLTOOptions`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144505

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


[PATCH] D124351: [Clang] Implement Change scope of lambda trailing-return-type

2023-02-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:19113
+// parameter appertaining to the same declaration as that attribute.
+if(auto* Parm = dyn_cast(Var); Parm && Parm->getDeclContext() 
== DC)
+  return true;

Formatting nit.

I have a hazy recollection that we sometimes have a weird declaration context 
for parameters where the parameter doesn't think it's associated with a 
function DC but instead with the translation unit DC. I seem to recall this 
having something to do with PCH/AST importing, but I can't seem to find any 
open issues about it. So this might be fine, but it may have some weird edge 
cases still.



Comment at: clang/test/SemaCXX/lambda-expressions.cpp:675-676
+StringLiteral(const char (&array)[N])
+__attribute__((enable_if(__builtin_strlen(array) == 2,
+  "invalid string literal")));
+};

1) This code already compiles today without issue 
(https://godbolt.org/z/q6hPxoWq9), so are you sure this is testing what needs 
to be tested?

2) What about for non-GNU-style attributes ([[]] attributes that appertain to 
the function type)? e.g.,
```
template 
void foo(const char (&array)[N]) [[clang::annotate_type("test", array)]];
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124351

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


[PATCH] D144572: [C++20] Stop claiming full support for consteval (for the moment!)

2023-02-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

We've discussed this offline, and I think this is the right thing to do, but 
I'll let others comment before approving.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144572

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


[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-22 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis marked 4 inline comments as done.
TIFitis added a comment.

In D142914#4144475 , 
@kiranchandramohan wrote:

> Please add tests for the MLIR portion.

Can you please tell me where to add these?

> Could you also post the full LLVM IR for a construct with the map clause?

The following is a simple example, let me know if you'd like a more complex 
example with loop :)

**Flang:**

  subroutine openmp_target_data
  integer :: i
  !$omp target data map(tofrom: i)
  i = 99;
  !$omp end target data
  end subroutine openmp_target_data

**FIR:**

  func.func @_QPopenmp_target_data() {
%0 = fir.alloca i32 {bindc_name = "i", uniq_name = 
"_QFopenmp_target_dataEi"}
omp.target_data   map((tofrom -> %0 : !fir.ref)) {
  %c99_i32 = arith.constant 99 : i32
  fir.store %c99_i32 to %0 : !fir.ref
  omp.terminator
}
return
  }

**LLVMIR:**

  llvm.func @_QPopenmp_target_data() {
%0 = llvm.mlir.constant(1 : i64) : i64
%1 = llvm.alloca %0 x i32 {bindc_name = "i", in_type = i32, 
operand_segment_sizes = array, uniq_name = 
"_QFopenmp_target_dataEi"} : (i64) -> !llvm.ptr
omp.target_data   map((tofrom -> %1 : !llvm.ptr)) {
  %2 = llvm.mlir.constant(99 : i32) : i32
  llvm.store %2, %1 : !llvm.ptr
  omp.terminator
}
llvm.return
  }

**llvm IR .ll:**

  ; ModuleID = 'LLVMDialectModule'
  source_filename = "LLVMDialectModule"
  target datalayout = 
"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
  target triple = "aarch64-unknown-linux-gnu"
  
  %struct.ident_t = type { i32, i32, i32, i32, ptr }
  
  @0 = private unnamed_addr constant [26 x i8] c";test.mlir;unknown;4;10;;\00", 
align 1
  @1 = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00", 
align 1
  @2 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 
22, ptr @1 }, align 8
  @.offload_maptypes = private unnamed_addr constant [1 x i64] [i64 3]
  @.offload_mapnames = private constant [1 x ptr] [ptr @0]
  
  declare ptr @malloc(i64)
  
  declare void @free(ptr)
  
  define void @_QPopenmp_target_data() {
%1 = alloca [1 x ptr], align 8
%2 = alloca [1 x ptr], align 8
%3 = alloca [1 x i64], align 8
%4 = alloca i32, i64 1, align 4
br label %entry
  
  entry:; preds = %0
%5 = getelementptr inbounds [1 x ptr], ptr %1, i32 0, i32 0
store ptr %4, ptr %5, align 8
%6 = getelementptr inbounds [1 x ptr], ptr %2, i32 0, i32 0
store ptr %4, ptr %6, align 8
%7 = getelementptr inbounds [1 x i64], ptr %3, i32 0, i32 0
store i64 ptrtoint (ptr getelementptr (ptr, ptr null, i32 1) to i64), ptr 
%7, align 8
%8 = getelementptr inbounds [1 x ptr], ptr %1, i32 0, i32 0
%9 = getelementptr inbounds [1 x ptr], ptr %2, i32 0, i32 0
%10 = getelementptr inbounds [1 x i64], ptr %3, i32 0, i32 0
call void @__tgt_target_data_begin_mapper(ptr @2, i64 -1, i32 1, ptr %8, 
ptr %9, ptr %10, ptr @.offload_maptypes, ptr @.offload_mapnames, ptr null)
br label %omp.data.region
  
  omp.data.region:  ; preds = %entry
store i32 99, ptr %4, align 4
br label %omp.region.cont
  
  omp.region.cont:  ; preds = %omp.data.region
%11 = getelementptr inbounds [1 x ptr], ptr %1, i32 0, i32 0
%12 = getelementptr inbounds [1 x ptr], ptr %2, i32 0, i32 0
%13 = getelementptr inbounds [1 x i64], ptr %3, i32 0, i32 0
call void @__tgt_target_data_end_mapper(ptr @2, i64 -1, i32 1, ptr %11, ptr 
%12, ptr %13, ptr @.offload_maptypes, ptr @.offload_mapnames, ptr null)
ret void
  }
  
  ; Function Attrs: nounwind
  declare void @__tgt_target_data_begin_mapper(ptr, i64, i32, ptr, ptr, ptr, 
ptr, ptr, ptr) #0
  
  ; Function Attrs: nounwind
  declare void @__tgt_target_data_end_mapper(ptr, i64, i32, ptr, ptr, ptr, ptr, 
ptr, ptr) #0
  
  attributes #0 = { nounwind }
  
  !llvm.module.flags = !{!0}
  
  !0 = !{i32 2, !"Debug Info Version", i32 3}

Cheers,
Akash




Comment at: mlir/lib/Target/LLVMIR/Dialect/Utils.cpp:1
+//===- Utils.cpp - General Utils for translating MLIR dialect to LLVM 
IR---===//
+//

kiranchandramohan wrote:
> Nit: I would prefer the OpenMPCommon.cpp name suggested in 
> https://discourse.llvm.org/t/rfc-adding-new-util-file-to-mlir-dialect-translation/68221.
>  
Would you also like me to move the file inside OpenMP ( 
`mlir/lib/Target/LLVMIR/Dialect/OpenMP` ) ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-22 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis updated this revision to Diff 499583.
TIFitis marked an inline comment as done.
TIFitis added a comment.

Addressed reviewer comments, fixed error in MLIR translation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/include/mlir/Target/LLVMIR/Dialect/OpenMPCommon.h
  mlir/lib/Target/LLVMIR/CMakeLists.txt
  mlir/lib/Target/LLVMIR/Dialect/OpenACC/OpenACCToLLVMIRTranslation.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMPCommon.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMPCommon.cpp
===
--- /dev/null
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMPCommon.cpp
@@ -0,0 +1,41 @@
+//===- OpenMPCommon.cpp - Utils for translating MLIR dialect to LLVM IR===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file defines general utilities for MLIR Dialect translations to LLVM IR.
+//
+//===--===//
+
+#include "mlir/Target/LLVMIR/Dialect/OpenMPCommon.h"
+
+llvm::Constant *
+mlir::LLVM::createSourceLocStrFromLocation(Location loc,
+   llvm::OpenMPIRBuilder &builder,
+   StringRef name, uint32_t &strLen) {
+  if (auto fileLoc = loc.dyn_cast()) {
+StringRef fileName = fileLoc.getFilename();
+unsigned lineNo = fileLoc.getLine();
+unsigned colNo = fileLoc.getColumn();
+return builder.getOrCreateSrcLocStr(name, fileName, lineNo, colNo, strLen);
+  }
+  std::string locStr;
+  llvm::raw_string_ostream locOS(locStr);
+  locOS << loc;
+  return builder.getOrCreateSrcLocStr(locOS.str(), strLen);
+}
+
+llvm::Constant *
+mlir::LLVM::createMappingInformation(Location loc,
+ llvm::OpenMPIRBuilder &builder) {
+  uint32_t strLen;
+  if (auto nameLoc = loc.dyn_cast()) {
+StringRef name = nameLoc.getName();
+return createSourceLocStrFromLocation(nameLoc.getChildLoc(), builder, name,
+  strLen);
+  }
+  return createSourceLocStrFromLocation(loc, builder, "unknown", strLen);
+}
Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -15,10 +15,12 @@
 #include "mlir/IR/IRMapping.h"
 #include "mlir/IR/Operation.h"
 #include "mlir/Support/LLVM.h"
+#include "mlir/Target/LLVMIR/Dialect/OpenMPCommon.h"
 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
 
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/TypeSwitch.h"
+#include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/IRBuilder.h"
@@ -1351,6 +1353,191 @@
   return success();
 }
 
+/// Process MapOperands for Target Data directives.
+static LogicalResult processMapOperand(
+llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
+const SmallVector &mapOperands, const ArrayAttr &mapTypes,
+SmallVector &mapTypeFlags,
+SmallVectorImpl &mapNames,
+struct llvm::OpenMPIRBuilder::MapperAllocas &mapperAllocas) {
+  auto numMapOperands = mapOperands.size();
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+  llvm::PointerType *i8PtrTy = builder.getInt8PtrTy();
+  llvm::ArrayType *arrI8PtrTy = llvm::ArrayType::get(i8PtrTy, numMapOperands);
+  llvm::IntegerType *i64Ty = builder.getInt64Ty();
+  llvm::ArrayType *arrI64Ty = llvm::ArrayType::get(i64Ty, numMapOperands);
+
+  unsigned index = 0;
+  for (const auto &mapOp : mapOperands) {
+const auto &mapTypeOp = mapTypes[index];
+
+llvm::Value *mapOpValue = moduleTranslation.lookupValue(mapOp);
+llvm::Value *mapOpPtrBase;
+llvm::Value *mapOpPtr;
+llvm::Value *mapOpSize;
+
+if (mapOp.getType().isa()) {
+  mapOpPtrBase = mapOpValue;
+  mapOpPtr = mapOpValue;
+  mapOpSize = ompBuilder->getSizeInBytes(mapOpValue);
+} else {
+  return failure();
+}
+
+// Store base pointer extracted from operand into the i-th position of
+// argBase.
+llvm::Value *ptrBaseGEP = builder.CreateInBoundsGEP(
+arrI8PtrTy, mapperAllocas.ArgsBase,
+{

[PATCH] D144149: [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2893d55f8f61: [Serialization] Don't warn when a 
deserialized category is equivalent to an… (authored by vsapsai).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144149

Files:
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/Modules/compare-objc-interface.m
  clang/test/Modules/hidden-duplicates.m
  clang/test/Modules/objc-categories.m

Index: clang/test/Modules/objc-categories.m
===
--- clang/test/Modules/objc-categories.m
+++ clang/test/Modules/objc-categories.m
@@ -8,8 +8,6 @@
 
 @import category_bottom;
 
-// expected-note@Inputs/category_left.h:14 {{previous definition}}
-// expected-warning@Inputs/category_right.h:12 {{duplicate definition of category}}
 // expected-note@Inputs/category_top.h:1 {{receiver is instance of class declared here}}
 
 @interface Foo(Source)
Index: clang/test/Modules/hidden-duplicates.m
===
--- clang/test/Modules/hidden-duplicates.m
+++ clang/test/Modules/hidden-duplicates.m
@@ -32,6 +32,7 @@
 
 @interface NSObject @end
 @class ForwardDeclaredInterfaceWithoutDefinition;
+@interface NSObject(CategoryForTesting) @end
 
 NSObject *interfaceDefinition(NSObject *o);
 NSObject *forwardDeclaredInterface(NSObject *o);
Index: clang/test/Modules/compare-objc-interface.m
===
--- clang/test/Modules/compare-objc-interface.m
+++ clang/test/Modules/compare-objc-interface.m
@@ -444,3 +444,54 @@
 // expected-error@first.h:* {{'CompareLastImplAttribute' has different definitions in different modules; first difference is definition in module 'First.Hidden' found property 'lastImplAttribute' with 'direct' attribute}}
 // expected-note-re@second.h:* {{but in {{'Second'|definition here}} found property 'lastImplAttribute' with different 'direct' attribute}}
 #endif
+
+#if defined(FIRST)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+- (void)presentMethod;
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategoryFirst)
+- (void)firstMethod:(int)x;
+@end
+#elif defined(SECOND)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+- (void)presentMethod;
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategorySecond)
+- (void)secondMethod;
+@end
+#else
+CompareMatchingCategories *compareMatchingCategories; // no diagnostic
+CompareMismatchingCategories1 *compareMismatchingCategories1;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category1' on interface 'CompareMismatchingCategories1'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareMismatchingCategories2 *compareMismatchingCategories2;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category2' on interface 'CompareMismatchingCategories2'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareDifferentCategoryNames *compareDifferentCategoryNames; // no diagnostic
+#endif
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -14,6 +14,7 @@
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTStructuralEquivalence.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/AttrIterator.h"
 #include "clang/AST/Decl.h"
@@ -4181,23 +4182,22 @@
   // Check for duplicate categories.
   if (Cat->getDeclName()) {
 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
-if (Existing &&
-Reader.getOwningModuleFile(Existing)
-  != Reader.getOwningModuleFile(Cat)) {
-  // FIXME: We should not warn for duplicates in diamond:
-  //
-  //   MT //
-  //  /  \//
-  // ML  MR   //
-  //  \  ///
-  //   MB //
-  //
-

[clang] 2893d55 - [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-22 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2023-02-22T11:01:40-08:00
New Revision: 2893d55f8f61edb2c253b960cab1107ea6c163c2

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

LOG: [Serialization] Don't warn when a deserialized category is equivalent to 
an existing one.

A single class allows multiple categories to be defined for it. But if
two of such categories have the same name, we emit a warning. It's not a
hard error but a good indication of a potential mistake.

With modules, we can end up with the same category in different modules.
Diagnosing such a situation has little value as the categories in
different modules are equivalent and don't reflect the usage of the same
name for different purposes. When we deserialize a duplicate category,
compare it to an existing one and warn only when the new one is
different.

rdar://104582081

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

Added: 


Modified: 
clang/lib/Serialization/ASTReaderDecl.cpp
clang/test/Modules/compare-objc-interface.m
clang/test/Modules/hidden-duplicates.m
clang/test/Modules/objc-categories.m

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index 8cb513eff13e0..b9bbc0ec9eb28 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -14,6 +14,7 @@
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTStructuralEquivalence.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/AttrIterator.h"
 #include "clang/AST/Decl.h"
@@ -4181,23 +4182,22 @@ namespace {
   // Check for duplicate categories.
   if (Cat->getDeclName()) {
 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
-if (Existing &&
-Reader.getOwningModuleFile(Existing)
-  != Reader.getOwningModuleFile(Cat)) {
-  // FIXME: We should not warn for duplicates in diamond:
-  //
-  //   MT //
-  //  /  \//
-  // ML  MR   //
-  //  \  ///
-  //   MB //
-  //
-  // If there are duplicates in ML/MR, there will be warning when
-  // creating MB *and* when importing MB. We should not warn when
-  // importing.
-  Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
-<< Interface->getDeclName() << Cat->getDeclName();
-  Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
+if (Existing && Reader.getOwningModuleFile(Existing) !=
+Reader.getOwningModuleFile(Cat)) {
+  llvm::DenseSet> NonEquivalentDecls;
+  StructuralEquivalenceContext Ctx(
+  Cat->getASTContext(), Existing->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default,
+  /*StrictTypeSpelling =*/false,
+  /*Complain =*/false,
+  /*ErrorOnTagTypeMismatch =*/true);
+  if (!Ctx.IsEquivalent(Cat, Existing)) {
+// Warn only if the categories with the same name are 
diff erent.
+Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
+<< Interface->getDeclName() << Cat->getDeclName();
+Reader.Diag(Existing->getLocation(),
+diag::note_previous_definition);
+  }
 } else if (!Existing) {
   // Record this category.
   Existing = Cat;

diff  --git a/clang/test/Modules/compare-objc-interface.m 
b/clang/test/Modules/compare-objc-interface.m
index 17a03de3ce29b..cc3b5fe60b1f5 100644
--- a/clang/test/Modules/compare-objc-interface.m
+++ b/clang/test/Modules/compare-objc-interface.m
@@ -444,3 +444,54 @@ @interface CompareLastImplAttribute: NSObject
 // expected-error@first.h:* {{'CompareLastImplAttribute' has 
diff erent definitions in 
diff erent modules; first 
diff erence is definition in module 'First.Hidden' found property 
'lastImplAttribute' with 'direct' attribute}}
 // expected-note-re@second.h:* {{but in {{'Second'|definition here}} found 
property 'lastImplAttribute' with 
diff erent 'direct' attribute}}
 #endif
+
+#if defined(FIRST)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+- (void)presentMethod;
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategoryFirst)
+- (void)f

  1   2   >