[PATCH] D137520: [AVR][Clang] Move family names into MCU list

2022-11-11 Thread Ben Shi via Phabricator via cfe-commits
benshi001 accepted this revision.
benshi001 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/D137520/new/

https://reviews.llvm.org/D137520

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


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

2022-11-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474676.
tbaeder added a comment.

Added the int-to-float conversion tests from https://reviews.llvm.org/D137719


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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Floating.cpp
  clang/lib/AST/Interp/Floating.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Primitives.h
  clang/test/AST/Interp/const-fpfeatures.cpp
  clang/test/AST/Interp/floats.cpp
  clang/test/SemaCXX/rounding-math.cpp

Index: clang/test/SemaCXX/rounding-math.cpp
===
--- clang/test/SemaCXX/rounding-math.cpp
+++ clang/test/SemaCXX/rounding-math.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-linux -verify=norounding -Wno-unknown-pragmas %s
 // RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -Wno-unknown-pragmas
+// RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -fexperimental-new-constant-interpreter -Wno-unknown-pragmas
 // rounding-no-diagnostics
 
 #define fold(x) (__builtin_constant_p(x) ? (x) : (x))
Index: clang/test/AST/Interp/floats.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/floats.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+constexpr int i = 2;
+constexpr float f = 1.0f;
+static_assert(f == 1.0f, "");
+
+constexpr float f2 = 1u * f;
+static_assert(f2 == 1.0f, "");
+
+constexpr float f3 = 1.5;
+constexpr int i3 = f3;
+static_assert(i3 == 1);
+
+constexpr bool b3 = f3;
+static_assert(b3);
+
+
+static_assert(1.0f + 3u == 4, "");
+static_assert(4.0f / 1.0f == 4, "");
+static_assert(10.0f * false == 0, "");
+
+constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{division by zero}} \
+ // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{division by zero}}
+
+static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+   // expected-error {{invalid argument type 'float' to unary expression}}
+
+/// Initialized by a double.
+constexpr float df = 0.0;
+/// The other way around.
+constexpr double fd = 0.0f;
+
+static_assert(0.0f == -0.0f, "");
+
+const int k = 3 * (1.0f / 3.0f);
+static_assert(k == 1, "");
+
+constexpr bool b = 1.0;
+static_assert(b, "");
+
+constexpr double db = true;
+static_assert(db == 1.0, "");
+
+constexpr float fa[] = {1.0f, 2.0, 1, false};
+constexpr float da[] = {1.0f, 2.0, 1, false};
Index: clang/test/AST/Interp/const-fpfeatures.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/const-fpfeatures.cpp
@@ -0,0 +1,72 @@
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -fexperimental-new-constant-interpreter -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+float F1u = 1.0F + 0x0.02p0F;
+float F2u = 1.0F + 0x0.01p0F;
+float F3u = 0x1.01p0;
+// CHECK: @F1u = {{.*}} float 0x3FF02000
+// CHECK: @F2u = {{.*}} float 0x3FF02000
+// CHECK: @F3u = {{.*}} float 0x3FF02000
+
+float FI1u = 0xU;
+// CHECK: @FI1u = {{.*}} float 0x41F0
+
+#pragma STDC FENV_ROUND FE_DOWNWARD
+
+float F1d = 1.0F + 0x0.02p0F;
+float F2d = 1.0F + 0x0.01p0F;
+float F3d = 0x1.01p0;
+
+// CHECK: @F1d = {{.*}} float 0x3FF02000
+// CHECK: @F2d = {{.*}} float 1.00e+00
+// CHECK: @F3d = {{.*}} float 1.00e+00
+
+
+float FI1d = 0xU;
+// CHECK: @FI1d = {{.*}} float 0x41EFE000
+
+// nextUp(1.F) == 0x1.02p0F
+
+constexpr float add_round_down(float x, float y) {
+  #pragma STDC FENV_ROUND FE_DOWNWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+constexpr float add_round_up(float x, float y) {
+  #pragma STDC FENV_ROUND FE_UPWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+float V1 = add_round_down(1.0F, 0x0.01p0F);
+float V2 = add_round_up(1.0F, 0x0.01p0F);
+// CHECK: @V1 = {{.*}} float 1.00e+00
+// CHECK: @V2 = {{.*}} float 0x3FF02000
+
+constexpr float add_cast_round_down(float x, double y) {
+  #pragma STDC FENV_ROUN

[PATCH] D137521: [AVR][Clang] Implement __AVR_ARCH__ macro

2022-11-11 Thread Ben Shi via Phabricator via cfe-commits
benshi001 accepted this revision.
benshi001 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/D137521/new/

https://reviews.llvm.org/D137521

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


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

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

In D137770#3919327 , @ChuanqiXu wrote:

> And we need the compiler (clang) to parse the module file from different 
> versions.

I think it's more likely that we'll need to get clangd to build the modules 
itself (or by using a clang binary whose version matches clangd).

In scenarios where the build compiler's version matches clangd, we could have a 
mechanism for clangd to locate and reuse the modules built by the build system.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137770

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


[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-11-11 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry created this revision.
v1nh1shungry added reviewers: tom-anders, kadircet.
Herald added subscribers: arphaman, mgrang.
Herald added a project: All.
v1nh1shungry requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

If we are removing the namespace `ns1` and there are user-defined literals
declared in an inline namespace `ns2` declared in `ns1`, we can add a
`using namespace ns1::ns2;` to keep the program correct.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137817

Files:
  clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
  clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
@@ -263,6 +263,26 @@
   long double operator "" _w(long double);
   }
   
+  int main() { 1.5_w; }
+)cpp"},
+  {// Add using-directives for user-defined literals
+   // declared in an inline namespace
+   R"cpp(
+  namespace ns1 {
+  inline namespace ns2 {
+  long double operator"" _w(long double);
+  }
+  }
+  using namespace n^s1;
+  int main() { 1.5_w; }
+)cpp",
+   R"cpp(
+  namespace ns1 {
+  inline namespace ns2 {
+  long double operator"" _w(long double);
+  }
+  }
+  using namespace ns1::ns2;
   int main() { 1.5_w; }
 )cpp"}};
   for (auto C : Cases)
Index: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -54,6 +54,10 @@
   : TargetNS(Target.getNominatedNamespace()),
 TargetCtx(Target.getDeclContext()), Results(Results) {}
 
+  FindSameUsings(const NamespaceDecl *TargetNS, const DeclContext *TargetCtx,
+ std::vector &Results)
+  : TargetNS(TargetNS), TargetCtx(TargetCtx), Results(Results) {}
+
   bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
 if (D->getNominatedNamespace() != TargetNS ||
 D->getDeclContext() != TargetCtx)
@@ -101,6 +105,40 @@
   return D;
 }
 
+// If the user-defined literal is declared in an inline namespace,
+// we add a using-directive for it
+void handleUserDefinedLiteral(const DeclContext *D, const DeclContext *Ctx,
+  ASTContext &AST,
+  std::vector &UsingToAdd) {
+  if (D->isInlineNamespace()) {
+const auto *ND = cast(D);
+// Find if there is already a wanted using-directive,
+// if there is, we are done. Otherwise we collect it
+std::vector AllDirectives;
+FindSameUsings(ND, Ctx, AllDirectives).TraverseAST(AST);
+if (AllDirectives.empty()) {
+  UsingToAdd.push_back(ND->getQualifiedNameAsString());
+}
+  }
+}
+
+// Produce edit adding 'using namespace xxx::yyy;'
+// for user-defined literals declared in an inline namespace
+llvm::Optional
+addUsingDirectives(const std::vector &UsingToAdd,
+   SourceManager &SM, SourceLocation Loc) {
+  if (UsingToAdd.empty())
+return llvm::None;
+  std::string Directives;
+  for (auto &Using : UsingToAdd)
+Directives += llvm::formatv("using namespace {0};\n", Using);
+  // Remove the trailing newline
+  Directives.pop_back();
+  // For now we insert the using-directives to where the first using-directive
+  // to remove stands
+  return tooling::Replacement(SM, Loc, 0, Directives);
+}
+
 bool RemoveUsingNamespace::prepare(const Selection &Inputs) {
   // Find the 'using namespace' directive under the cursor.
   auto *CA = Inputs.ASTSelection.commonAncestor();
@@ -144,6 +182,9 @@
   // Collect all references to symbols from the namespace for which we're
   // removing the directive.
   std::vector IdentsToQualify;
+  // Collect all namespaces' name to add for user-defined literals declared
+  // in an inline namespace
+  std::vector UsingToAdd;
   for (auto &D : Inputs.AST->getLocalTopLevelDecls()) {
 findExplicitReferences(
 D,
@@ -164,15 +205,19 @@
 // Avoid adding qualifiers before user-defined literals, e.g.
 //   using namespace std;
 //   auto s = "foo"s; // Must not changed to auto s = "foo" std::s;
-// FIXME: Add a using-directive for user-defined literals
+// And add a using-directive for user-defined literals
 // declared in an inline namespace, e.g.
 //   using namespace s^td;
 //   int main() { cout << "foo"s; }
 // change to
-//   using namespace std::literals;
+//   using namespace s

[PATCH] D137818: Add support for querying SubstTemplateTypeParm types

2022-11-11 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands created this revision.
anderslanglands added reviewers: tbaeder, aaron.ballman.
Herald added subscribers: arphaman, kristof.beyls.
Herald added a project: All.
anderslanglands requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Adds CXType_SubstTemplateTypeParm and clang_Type_getReplacementType()


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137818

Files:
  clang/include/clang-c/Index.h
  clang/test/Index/print-type.cpp
  clang/tools/libclang/CXType.cpp
  clang/tools/libclang/libclang.map


Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -167,6 +167,7 @@
 clang_Type_getSizeOf;
 clang_Type_getTemplateArgumentAsType;
 clang_Type_getValueType;
+clang_Type_getReplacementType;
 clang_Type_isTransparentTagTypedef;
 clang_Type_visitFields;
 clang_VerbatimBlockLineComment_getText;
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -118,12 +118,17 @@
 TKCASE(Attributed);
 TKCASE(BTFTagAttributed);
 TKCASE(Atomic);
+TKCASE(SubstTemplateTypeParm);
 default:
   return CXType_Unexposed;
   }
 #undef TKCASE
 }
 
+static CXTypeKind GetSubstTemplateTypeParmTypeKind(const 
SubstTemplateTypeParmType* TP) {
+  const QualType RT = TP->getReplacementType();
+  return GetTypeKind(RT);
+}
 
 CXType cxtype::MakeCXType(QualType T, CXTranslationUnit TU) {
   CXTypeKind TK = CXType_Invalid;
@@ -635,6 +640,7 @@
 TKIND(OCLQueue);
 TKIND(OCLReserveID);
 TKIND(Atomic);
+TKIND(SubstTemplateTypeParm);
   }
 #undef TKIND
   return cxstring::createRef(s);
@@ -1355,3 +1361,13 @@
   const auto *AT = T->castAs();
   return MakeCXType(AT->getValueType(), GetTU(CT));
 }
+
+CXType clang_Type_getReplacementType(CXType CT) {
+  QualType T = GetQualType(CT);
+
+  if (T.isNull() || T->getTypeClass() != Type::SubstTemplateTypeParm)
+return MakeCXType(QualType(), GetTU(CT));
+
+  const auto *ST = T->castAs();
+  return MakeCXType(ST->getReplacementType(), GetTU(CT));
+}
\ No newline at end of file
Index: clang/test/Index/print-type.cpp
===
--- clang/test/Index/print-type.cpp
+++ clang/test/Index/print-type.cpp
@@ -171,7 +171,7 @@
 // CHECK: VarDecl=autoI:54:6 (Definition) [type=int] [typekind=Auto] 
[canonicaltype=int] [canonicaltypekind=Int] [isPOD=1]
 // CHECK: IntegerLiteral= [type=int] [typekind=Int] [isPOD=1]
 // CHECK: VarDecl=autoTbar:55:6 (Definition) [type=int] [typekind=Auto] 
[canonicaltype=int] [canonicaltypekind=Int] [isPOD=1]
-// CHECK: CallExpr=tbar:36:3 [type=int] [typekind=Unexposed] 
[canonicaltype=int] [canonicaltypekind=Int] [args= [int] [Int]] [isPOD=1]
+// CHECK: CallExpr=tbar:36:3 [type=int] [typekind=SubstTemplateTypeParm] 
[canonicaltype=int] [canonicaltypekind=Int] [args= [int] [Int]] [isPOD=1]
 // CHECK: UnexposedExpr=tbar:36:3 [type=int (*)(int)] [typekind=Pointer] 
[canonicaltype=int (*)(int)] [canonicaltypekind=Pointer] [isPOD=1] 
[pointeetype=int (int)] [pointeekind=FunctionProto]
 // CHECK: DeclRefExpr=tbar:36:3 RefName=[55:17 - 55:21] RefName=[55:21 - 
55:26] [type=int (int)] [typekind=FunctionProto] [canonicaltype=int (int)] 
[canonicaltypekind=FunctionProto] [isPOD=0]
 // CHECK: IntegerLiteral= [type=int] [typekind=Int] [isPOD=1]
Index: clang/include/clang-c/Index.h
===
--- clang/include/clang-c/Index.h
+++ clang/include/clang-c/Index.h
@@ -2789,7 +2789,9 @@
 
   CXType_ExtVector = 176,
   CXType_Atomic = 177,
-  CXType_BTFTagAttributed = 178
+  CXType_BTFTagAttributed = 178,
+  /* Represents a type that as been substituted for a template type parameter 
*/
+  CXType_SubstTemplateTypeParm = 179
 };
 
 /**
@@ -3447,6 +3449,13 @@
  */
 CINDEX_LINKAGE CXType clang_Type_getValueType(CXType CT);
 
+/**
+ * Gets the replacement type for a SubstTemplateTypeParm type.
+ *
+ * If any other type kind is passed in, an invalid type is returned.
+ */
+CINDEX_LINKAGE CXType clang_Type_getReplacementType(CXType CT);
+
 /**
  * Return the offset of the field represented by the Cursor.
  *


Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -167,6 +167,7 @@
 clang_Type_getSizeOf;
 clang_Type_getTemplateArgumentAsType;
 clang_Type_getValueType;
+clang_Type_getReplacementType;
 clang_Type_isTransparentTagTypedef;
 clang_Type_visitFields;
 clang_VerbatimBlockLineComment_getText;
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
++

[PATCH] D137320: [include-cleaner] Initial version for the "Location=>Header" step

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

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137320

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/Types.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -7,11 +7,14 @@
 //===--===//
 
 #include "clang-include-cleaner/Analysis.h"
+#include "AnalysisInternal.h"
+#include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -28,19 +31,39 @@
 
 TEST(WalkUsed, Basic) {
   // FIXME: Have a fixture for setting up tests.
-  llvm::Annotations HeaderCode(R"cpp(
-  void foo();
-  namespace std { class vector {}; })cpp");
   llvm::Annotations Code(R"cpp(
-  void $bar^bar() {
+  #include "header.h"
+  #include "private.h"
+
+  void $bar^bar($private^Private) {
 $foo^foo();
 std::$vector^vector $vconstructor^v;
   }
   )cpp");
   TestInputs Inputs(Code.code());
-  Inputs.ExtraFiles["header.h"] = HeaderCode.code().str();
-  Inputs.ExtraArgs.push_back("-include");
-  Inputs.ExtraArgs.push_back("header.h");
+  Inputs.ExtraFiles["header.h"] = R"cpp(
+  void foo();
+  namespace std { class vector {}; }
+  )cpp";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "path/public.h"
+class Private {};
+  )cpp";
+
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public SyntaxOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&PI);
+  };
   TestAST AST(Inputs);
 
   llvm::SmallVector TopLevelDecls;
@@ -50,7 +73,7 @@
 
   auto &SM = AST.sourceManager();
   llvm::DenseMap> OffsetToProviders;
-  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, SM,
+  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, PI, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
@@ -63,6 +86,8 @@
   OffsetToProviders,
   UnorderedElementsAre(
   Pair(Code.point("bar"), UnorderedElementsAre(MainFile)),
+  Pair(Code.point("private"),
+   UnorderedElementsAre(Header("\"path/public.h\""))),
   Pair(Code.point("foo"), UnorderedElementsAre(HeaderFile)),
   Pair(Code.point("vector"), UnorderedElementsAre(VectorSTL)),
   Pair(Code.point("vconstructor"), UnorderedElementsAre(VectorSTL;
@@ -89,10 +114,11 @@
   Symbol Answer =
   Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
   llvm::DenseMap> OffsetToProviders;
+  PragmaIncludes PI;
   walkUsed(/*ASTRoots=*/{}, /*MacroRefs=*/
{SymbolReference{SM.getComposedLoc(SM.getMainFileID(), Main.point()),
 Answer, RefType::Explicit}},
-   SM,
+   PI, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
@@ -104,5 +130,63 @@
   UnorderedElementsAre(Pair(Main.point(), UnorderedElementsAre(HdrFile;
 }
 
+TEST(FindIncludeHeaders, IWYU) {
+  TestInputs Inputs;
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public PreprocessOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&PI);
+  };
+
+  Inputs.Code = R"cpp(
+#include "header1.h"
+#include "header2.h"
+  )cpp";
+  Inputs.ExtraFiles["header1.h"] = R"cpp(
+// IWYU pragma: private, include "path/public.h"
+  )cpp";
+  Inputs.ExtraFiles["header2.h"] = R"cpp(
+#include "detail1.h" // IWYU pragma: export
+
+// IWY

[PATCH] D137320: [include-cleaner] Initial version for the "Location=>Header" step

2022-11-11 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 rG779554804813: [include-cleaner] Initial version for the 
"Location=>Header" step (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D137320?vs=474685&id=474687#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137320

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/lib/Types.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -7,11 +7,14 @@
 //===--===//
 
 #include "clang-include-cleaner/Analysis.h"
+#include "AnalysisInternal.h"
+#include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -28,19 +31,39 @@
 
 TEST(WalkUsed, Basic) {
   // FIXME: Have a fixture for setting up tests.
-  llvm::Annotations HeaderCode(R"cpp(
-  void foo();
-  namespace std { class vector {}; })cpp");
   llvm::Annotations Code(R"cpp(
-  void $bar^bar() {
+  #include "header.h"
+  #include "private.h"
+
+  void $bar^bar($private^Private) {
 $foo^foo();
 std::$vector^vector $vconstructor^v;
   }
   )cpp");
   TestInputs Inputs(Code.code());
-  Inputs.ExtraFiles["header.h"] = HeaderCode.code().str();
-  Inputs.ExtraArgs.push_back("-include");
-  Inputs.ExtraArgs.push_back("header.h");
+  Inputs.ExtraFiles["header.h"] = R"cpp(
+  void foo();
+  namespace std { class vector {}; }
+  )cpp";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "path/public.h"
+class Private {};
+  )cpp";
+
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public SyntaxOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&PI);
+  };
   TestAST AST(Inputs);
 
   llvm::SmallVector TopLevelDecls;
@@ -50,7 +73,7 @@
 
   auto &SM = AST.sourceManager();
   llvm::DenseMap> OffsetToProviders;
-  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, SM,
+  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, PI, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
@@ -63,6 +86,8 @@
   OffsetToProviders,
   UnorderedElementsAre(
   Pair(Code.point("bar"), UnorderedElementsAre(MainFile)),
+  Pair(Code.point("private"),
+   UnorderedElementsAre(Header("\"path/public.h\""))),
   Pair(Code.point("foo"), UnorderedElementsAre(HeaderFile)),
   Pair(Code.point("vector"), UnorderedElementsAre(VectorSTL)),
   Pair(Code.point("vconstructor"), UnorderedElementsAre(VectorSTL;
@@ -89,10 +114,11 @@
   Symbol Answer =
   Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
   llvm::DenseMap> OffsetToProviders;
+  PragmaIncludes PI;
   walkUsed(/*ASTRoots=*/{}, /*MacroRefs=*/
{SymbolReference{SM.getComposedLoc(SM.getMainFileID(), Main.point()),
 Answer, RefType::Explicit}},
-   SM,
+   PI, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
@@ -104,5 +130,63 @@
   UnorderedElementsAre(Pair(Main.point(), UnorderedElementsAre(HdrFile;
 }
 
+TEST(FindIncludeHeaders, IWYU) {
+  TestInputs Inputs;
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public PreprocessOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&P

[clang-tools-extra] 7795548 - [include-cleaner] Initial version for the "Location=>Header" step

2022-11-11 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-11-11T10:34:22+01:00
New Revision: 77955480481396c0e92aa1b4b99821eb21a66c0e

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

LOG: [include-cleaner] Initial version for the "Location=>Header" step

This patch implements the initial version of "Location => Header" step:

- define the interface;
- integrate into the existing workflow, and use the PragmaIncludes;

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
clang-tools-extra/include-cleaner/lib/Analysis.cpp
clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
clang-tools-extra/include-cleaner/lib/Record.cpp
clang-tools-extra/include-cleaner/lib/Types.cpp
clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
index 62277199871b8..7b8606f4a6ce4 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -11,6 +11,7 @@
 #ifndef CLANG_INCLUDE_CLEANER_ANALYSIS_H
 #define CLANG_INCLUDE_CLEANER_ANALYSIS_H
 
+#include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
@@ -42,11 +43,9 @@ using UsedSymbolCB = llvm::function_ref ASTRoots,
-  llvm::ArrayRef MacroRefs, const SourceManager &,
-  UsedSymbolCB CB);
+  llvm::ArrayRef MacroRefs,
+  const PragmaIncludes &PI, const SourceManager &, UsedSymbolCB 
CB);
 
 } // namespace include_cleaner
 } // namespace clang

diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
index 6aaf6cfa5d37d..87db0cf585a30 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
@@ -105,10 +105,14 @@ struct Header {
 Physical,
 /// A recognized standard library header, like .
 Standard,
+/// A verbatim header spelling, a string quoted with <> or "" that can be
+/// #included directly.
+VerbatimSpelling,
   };
 
   Header(const FileEntry *FE) : Storage(FE) {}
   Header(tooling::stdlib::Header H) : Storage(H) {}
+  Header(StringRef VerbatimSpelling) : Storage(VerbatimSpelling) {}
 
   Kind kind() const { return static_cast(Storage.index()); }
   bool operator==(const Header &RHS) const { return Storage == RHS.Storage; }
@@ -117,11 +121,13 @@ struct Header {
   tooling::stdlib::Header standard() const {
 return std::get(Storage);
   }
+  StringRef verbatimSpelling() const {
+return std::get(Storage);
+  }
 
 private:
-  // FIXME: Handle verbatim spellings.
   // Order must match Kind enum!
-  std::variant Storage;
+  std::variant Storage;
 };
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Header &);
 

diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index f7c8bdeee0bfe..4d66c34ce788f 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -17,20 +17,11 @@
 #include "llvm/ADT/SmallVector.h"
 
 namespace clang::include_cleaner {
-namespace {
-llvm::SmallVector
-toHeader(llvm::ArrayRef Headers) {
-  llvm::SmallVector Result;
-  llvm::for_each(Headers, [&](tooling::stdlib::Header H) {
-Result.emplace_back(Header(H));
-  });
-  return Result;
-}
-} // namespace
 
 void walkUsed(llvm::ArrayRef ASTRoots,
   llvm::ArrayRef MacroRefs,
-  const SourceManager &SM, UsedSymbolCB CB) {
+  const PragmaIncludes &PI, const SourceManager &SM,
+  UsedSymbolCB CB) {
   tooling::stdlib::Recognizer Recognizer;
   for (auto *Root : ASTRoots) {
 auto &SM = Root->getASTContext().getSourceManager();
@@ -38,23 +29,52 @@ void walkUsed(llvm::ArrayRef ASTRoots,
   if (auto SS = Recognizer(&ND)) {
 // FIXME: Also report forward decls from main-file, so that the caller
 // can decide to insert/ignore a header.
-return CB({Loc, Symbol(*SS), RT}, toHeader(SS->headers()));
+return CB({Loc, Symbol(*SS), RT}, findIncludeHeaders({*SS}, SM, PI));
   }
   // FIXME: Extract locations from redecls.
-  // FIXME: Handle IWYU pragmas, non self-contained files.
-  // FIXME: Handle macro locati

[PATCH] D137572: [AVR][Clang] Implement __AVR_HAVE_*__ macros

2022-11-11 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added inline comments.



Comment at: clang/lib/Basic/Targets/AVR.cpp:355
+.Cases("31", "51", "6", true)
+.Cases("104", "105", "106", "107", true)
+.Default(false);

ATxmega16a4 with family code 102 also supports ELPM. Could you please make a 
careful check on ELPM and all other features? 

Generally speaking I am very glad to have this patch committed, since it fixes

https://github.com/llvm/llvm-project/issues/56157



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137572

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


[PATCH] D137320: [include-cleaner] Initial version for the "Location=>Header" step

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



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h:63
+// FIXME: use a real Class!
+using SymbolLocation = std::variant;
+

hokein wrote:
> kadircet wrote:
> > let's move this to `AnalysisInternal.h`, as it isn't used in any of the 
> > public apis.
> I'm not quite sure about this --the SymbolLocation is an important concept 
> and API, even though it is not used in public APIs. Moved anyway.
> 
FWIW +1 to the idea that this belongs in Types.h even if it's not used in 
public APIs at present, as discussed offline.



Comment at: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp:33
 TEST(WalkUsed, Basic) {
   // FIXME: Have a fixture for setting up tests.
   llvm::Annotations Code(R"cpp(

@kadircet gentle reminder - you wanted to defer this, this patch adds a 
copy/paste of the test setup - want me to try to pull something out before this 
gets out of hand?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137320

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


[PATCH] D137572: [AVR][Clang] Implement __AVR_HAVE_*__ macros

2022-11-11 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added inline comments.



Comment at: clang/lib/Basic/Targets/AVR.cpp:355
+.Cases("31", "51", "6", true)
+.Cases("104", "105", "106", "107", true)
+.Default(false);

benshi001 wrote:
> ATxmega16a4 with family code 102 also supports ELPM. Could you please make a 
> careful check on ELPM and all other features? 
> 
> Generally speaking I am very glad to have this patch committed, since it fixes
> 
> https://github.com/llvm/llvm-project/issues/56157
> 
I suggest that you can make your code in accordance with 
https://github.com/llvm/llvm-project/blob/main/llvm/lib/Target/AVR/AVRDevices.td


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137572

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

2022-11-11 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 474707.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments:

- mention #import case
- rename file name
- API: FileEntry => FileID


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/CMakeLists.txt
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -0,0 +1,66 @@
+//===- unittest/Tooling/HeaderAnalysisTest.cpp ===//
+//
+// 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
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Testing/TestAST.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+TEST(HeaderAnalysisTest, IsSelfContained) {
+  TestInputs Inputs;
+  Inputs.Code = R"cpp(
+  #include "headerguard.h"
+  #include "pragmaonce.h"
+  #import "imported.h"
+
+  #include "bad.h"
+  #include "unguarded.h"
+  )cpp";
+
+  Inputs.ExtraFiles["headerguard.h"] = R"cpp(
+  #ifndef HEADER_H
+  #define HEADER_H
+
+  #endif HEADER_H
+  )cpp";
+  Inputs.ExtraFiles["pragmaonce.h"] = R"cpp(
+  #pragma once
+  )cpp";
+  Inputs.ExtraFiles["imported.h"] = "";
+
+  Inputs.ExtraFiles["unguarded.h"] = "";
+  Inputs.ExtraFiles["bad.h"] = R"cpp(
+  #pragma once
+
+  #if defined(INSIDE_H)
+  #error "Only ... can be included directly"
+  #endif
+  )cpp";
+
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+  auto &FM = SM.getFileManager();
+  auto &HI = AST.preprocessor().getHeaderSearchInfo();
+  auto getFileID = [&](llvm::StringRef FileName) {
+return SM.translateFile(FM.getFile(FileName).get());
+  };
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("headerguard.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("pragmaonce.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("imported.h"), SM, HI));
+
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("unguarded.h"), SM, HI));
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("bad.h"), SM, HI));
+}
+
+} // namespace
+} // namespace tooling
+} // namespace clang
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -16,6 +16,7 @@
   DiagnosticsYamlTest.cpp
   ExecutionTest.cpp
   FixItTest.cpp
+  HeaderAnalysisTest.cpp
   HeaderIncludesTest.cpp
   StandardLibraryTest.cpp
   LexicallyOrderedRecursiveASTVisitorTest.cpp
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -0,0 +1,66 @@
+//===--- HeaderAnalysis.cpp -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/HeaderSearch.h"
+
+namespace clang::tooling {
+namespace {
+
+// Is Line an #if or #ifdef directive?
+// FIXME: This makes headers with #ifdef LINUX/WINDOWS/MACOS marked as non
+// self-contained and is probably not what we want.
+bool isIf(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  return Line.startswith("if");
+}
+
+// Is Line an #error directive mentioning includes?
+bool isErrorAboutInclude(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  if (!Line.startswith("error"))
+return false;
+  return Line.contains_insensitive(
+  "includ"); // Matches "include" or "including".
+}
+
+// Heuristically headers that only want to be included via an umbrella.
+bool isDontIncludeMeHeader(llvm::StringRef Content) {
+  llvm::StringRef Line;
+  // Only sniff up to 100 lines or 10KB.
+  Content = Content.

[PATCH] D134445: [PR57881][OpenCL] Fix incorrect diagnostics with templated types in kernel arguments

2022-11-11 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D134445#3920448 , @rjmccall wrote:

> In D134445#3920257 , @Anastasia 
> wrote:
>
>> In D134445#3920188 , @rjmccall 
>> wrote:
>>
>>> You really can't ask whether a class template pattern is standard layout; 
>>> it's not meaningful.
>>
>> Well the templates have to be instantiated with concrete types as kernels 
>> can't be called from the host code. But if the concrete type is a reference 
>> or pointer there is no full instantiation apparently as AST dumps in the 
>> review description show.
>
> My objection here is to the code that does `CXXRec = 
> CXXRec->getTemplateInstantiationPattern()`.  That is the unsubstituted 
> template pattern.  You then ask if it has standard layout.  I do not think 
> this is the right thing to do.

Yes this only works if the type doesn't depend on the template parameter like 
in the reported test case. But it is not a universal solution.

>>> How are pointers and references passed to kernels?  Does the pointee get 
>>> copied or something?  If so, you may have a requirement that pointee types 
>>> be complete, in which case the only problem is probably that you're doing 
>>> this check too soon, or doing them on declarations rather than on 
>>> definition/use.
>>
>> Ok, the kernel function actually already contains the instantiated templates 
>> since they can't be templated themselves.
>
> Yes, I understand that.
>
>> My understanding is that references and pointers to templated types are not 
>> required to be fully instantiated as they are not ODR-used?
>
> It's not the ODR, but yes, in standard C++, declaring a parameter of pointer 
> type does not require the pointee type to be complete, and if the pointee 
> type is a template type, the compiler is not permitted to immediately try to 
> instantiate it.  Of course, OpenCL `kernel` declarations are not standard C++ 
> and can use different rules, and I think the fact that OpenCL has this 
> semantic restriction on pointer arguments to kernels is pretty good license 
> to do so.  There are some places in C++ (e.g. initialization) that do 
> instantiate templates if a definition is available, and you can request this 
> by calling `Sema::isCompleteType` instead of `hasDefinition()`.

Ok, thanks! I will look into this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134445

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


[clang-tools-extra] 61c2276 - [include-cleaner] verbatimSpelling->verbatim, clean up some silly init-lists. NFC

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

Author: Sam McCall
Date: 2022-11-11T12:10:12+01:00
New Revision: 61c2276cb231f5cc5698c0bdd2e92d9ecfdefa16

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

LOG: [include-cleaner] verbatimSpelling->verbatim, clean up some silly 
init-lists. NFC

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
clang-tools-extra/include-cleaner/lib/Analysis.cpp
clang-tools-extra/include-cleaner/lib/Record.cpp
clang-tools-extra/include-cleaner/lib/Types.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
index 87db0cf585a3..78e61b81166a 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
@@ -107,7 +107,7 @@ struct Header {
 Standard,
 /// A verbatim header spelling, a string quoted with <> or "" that can be
 /// #included directly.
-VerbatimSpelling,
+Verbatim,
   };
 
   Header(const FileEntry *FE) : Storage(FE) {}
@@ -121,8 +121,8 @@ struct Header {
   tooling::stdlib::Header standard() const {
 return std::get(Storage);
   }
-  StringRef verbatimSpelling() const {
-return std::get(Storage);
+  StringRef verbatim() const {
+return std::get(Storage);
   }
 
 private:

diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index 4d66c34ce788..b3238e93bcc9 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -13,7 +13,6 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 
 namespace clang::include_cleaner {
@@ -29,11 +28,11 @@ void walkUsed(llvm::ArrayRef ASTRoots,
   if (auto SS = Recognizer(&ND)) {
 // FIXME: Also report forward decls from main-file, so that the caller
 // can decide to insert/ignore a header.
-return CB({Loc, Symbol(*SS), RT}, findIncludeHeaders({*SS}, SM, PI));
+return CB({Loc, Symbol(*SS), RT}, findIncludeHeaders(*SS, SM, PI));
   }
   // FIXME: Extract locations from redecls.
   return CB({Loc, Symbol(ND), RT},
-findIncludeHeaders({ND.getLocation()}, SM, PI));
+findIncludeHeaders(ND.getLocation(), SM, PI));
 });
   }
   for (const SymbolReference &MacroRef : MacroRefs) {
@@ -61,9 +60,9 @@ llvm::SmallVector findIncludeHeaders(const 
SymbolLocation &SLoc,
 // header.
 llvm::StringRef VerbatimSpelling = PI.getPublic(FE);
 if (!VerbatimSpelling.empty())
-  return {{VerbatimSpelling}};
+  return {Header(VerbatimSpelling)};
 
-Results = {{FE}};
+Results = {Header(FE)};
 // FIXME: compute transitive exporter headers.
 for (const auto *Export : PI.getExporters(FE, SM.getFileManager()))
   Results.push_back(Export);

diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index d824e5d06bad..4dabd4aa6d07 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -332,8 +332,8 @@ RecordedPP::RecordedIncludes::match(Header H) const {
 for (unsigned I : BySpelling.lookup(H.standard().name().trim("<>")))
   Result.push_back(&All[I]);
 break;
-  case Header::VerbatimSpelling:
-for (unsigned I : BySpelling.lookup(H.verbatimSpelling().trim("\"<>")))
+  case Header::Verbatim:
+for (unsigned I : BySpelling.lookup(H.verbatim().trim("\"<>")))
   Result.push_back(&All[I]);
 break;
   }

diff  --git a/clang-tools-extra/include-cleaner/lib/Types.cpp 
b/clang-tools-extra/include-cleaner/lib/Types.cpp
index 340843e6bdf9..a3b2731401ae 100644
--- a/clang-tools-extra/include-cleaner/lib/Types.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Types.cpp
@@ -34,8 +34,8 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const 
Header &H) {
 return OS << H.physical()->getName();
   case Header::Standard:
 return OS << H.standard().name();
-  case Header::VerbatimSpelling:
-return OS << H.verbatimSpelling();
+  case Header::Verbatim:
+return OS << H.verbatim();
   }
   llvm_unreachable("Unhandled Header kind");
 }



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


[PATCH] D137320: [include-cleaner] Initial version for the "Location=>Header" step

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



Comment at: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp:33
 TEST(WalkUsed, Basic) {
   // FIXME: Have a fixture for setting up tests.
   llvm::Annotations Code(R"cpp(

sammccall wrote:
> @kadircet gentle reminder - you wanted to defer this, this patch adds a 
> copy/paste of the test setup - want me to try to pull something out before 
> this gets out of hand?
disregard, I misread this, the new test isn't calling walkUsed at all so 
belongs somewhere else


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137320

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


[PATCH] D137825: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

2022-11-11 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

- replace SymbolLocation std::variant with enum-exposing version similar to 
those in types.cpp. There's no appropriate implementation file, added 
LocateSymbol.cpp in anticipation of locateDecl/locateMacro.
- FindHeaders is not part of the public Analysis interface, so should not be 
implemented/tested there (just code organization)
- rename findIncludeHeaders->findHeaders to avoid confusion with Include concept


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137825

Files:
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/CMakeLists.txt
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- /dev/null
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -0,0 +1,79 @@
+//===--- FindHeadersTest.cpp --===//
+//
+// 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
+//
+//===--===//
+
+#include "AnalysisInternal.h"
+#include "clang-include-cleaner/Record.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Testing/TestAST.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang::include_cleaner {
+namespace {
+using testing::UnorderedElementsAre;
+
+TEST(FindIncludeHeaders, IWYU) {
+  TestInputs Inputs;
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public PreprocessOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&PI);
+  };
+
+  Inputs.Code = R"cpp(
+#include "header1.h"
+#include "header2.h"
+  )cpp";
+  Inputs.ExtraFiles["header1.h"] = R"cpp(
+// IWYU pragma: private, include "path/public.h"
+  )cpp";
+  Inputs.ExtraFiles["header2.h"] = R"cpp(
+#include "detail1.h" // IWYU pragma: export
+
+// IWYU pragma: begin_exports
+#include "detail2.h"
+// IWYU pragma: end_exports
+
+#include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["normal.h"] = Inputs.ExtraFiles["detail1.h"] =
+  Inputs.ExtraFiles["detail2.h"] = "";
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+  auto &FM = SM.getFileManager();
+  // Returns the source location for the start of the file.
+  auto SourceLocFromFile = [&](llvm::StringRef FileName) {
+return SM.translateFileLineCol(FM.getFile(FileName).get(),
+   /*Line=*/1, /*Col=*/1);
+  };
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("header1.h"), SM, PI),
+  UnorderedElementsAre(Header("\"path/public.h\"")));
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail1.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
+   Header(FM.getFile("detail1.h").get(;
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail2.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
+   Header(FM.getFile("detail2.h").get(;
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("normal.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("normal.h").get(;
+}
+
+} // namespace
+} // namespace clang::include_cleaner
\ No newline at end of file
Index: clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
===
--- clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
+++ clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
@@ -6,6 +6,7 @@
 add_custom_target(ClangIncludeCleanerUnitTests)
 add_unittest(ClangIncludeCleanerUnitTests ClangIncludeCleanerTests
   AnalysisTest.cpp
+  FindHeadersTest.cpp
   RecordTest.cpp
   WalkASTTest.cpp
 )
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -7,7 +7,6 @@
 //==

[PATCH] D137826: [clang] Allow comparing pointers to string literals

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

This fixes https://github.com/llvm/llvm-project/issues/58754


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137826

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


Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1274,3 +1274,12 @@
 (dbt2.wp = nullptr, 0)
   };
 }
+
+
+constexpr auto name1() { return "name1"; }
+constexpr auto name2() { return "name2"; }
+
+constexpr auto b3 = name1() == name1();
+static_assert(b3, "");
+constexpr auto b4 = name1() == name2();
+static_assert(!b4, "");
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -358,12 +358,29 @@
 
 extern char externalvar[];
 constexpr bool constaddress = (void *)externalvar == (void *)0x4000UL; // 
expected-error {{must be initialized by a constant expression}} expected-note 
{{reinterpret_cast}}
-constexpr bool litaddress = "foo" == "foo"; // expected-error {{must be 
initialized by a constant expression}}
-// cxx20_2b-warning@-1 {{comparison between two arrays is deprecated}}
+constexpr bool litaddress = "foo" == "foo"; // cxx20_2b-warning {{comparison 
between two arrays is deprecated}}
 static_assert(0 != "foo", "");
 
 }
 
+constexpr const char *foo(const char *p) { return p; }
+constexpr const char *p1 = "test1";
+constexpr const char *p2 = "test2";
+
+constexpr bool b1 = foo(p1) == foo(p1);
+static_assert(b1, "");
+
+constexpr bool b2 = foo(p1) == foo(p2);
+static_assert(!b2, "");
+
+constexpr const char *name1() { return "name1"; }
+constexpr const char *name2() { return "name2"; }
+
+constexpr auto b3 = name1() == name1();
+static_assert(b3, "");
+constexpr auto b4 = name1() == name2();
+static_assert(!b4, "");
+
 namespace MaterializeTemporary {
 
 constexpr int f(const int &r) { return r; }
Index: clang/test/SemaCXX/builtins.cpp
===
--- clang/test/SemaCXX/builtins.cpp
+++ clang/test/SemaCXX/builtins.cpp
@@ -47,7 +47,7 @@
 void a(void) {}
 int n;
 void *p = __builtin_function_start(n);   // expected-error 
{{argument must be a function}}
-static_assert(__builtin_function_start(a) == a, ""); // expected-error 
{{static assertion expression is not an integral constant expression}}
+static_assert(__builtin_function_start(a) == a, ""); // expected-error 
{{static assertion failed}}
 } // namespace function_start
 
 void no_ms_builtins() {
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -12947,13 +12947,12 @@
   if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
   (!RHSValue.Base && !RHSValue.Offset.isZero()))
 return Error(E);
-  // It's implementation-defined whether distinct literals will have
-  // distinct addresses. In clang, the result of such a comparison is
-  // unspecified, so it is not a constant expression. However, we do know
-  // that the address of a literal will be non-null.
-  if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
-  LHSValue.Base && RHSValue.Base)
+
+  // ObjC's @encode()
+  if (isa(E->getLHS()->IgnoreParenImpCasts()) ||
+  isa(E->getRHS()->IgnoreParenImpCasts()))
 return Error(E);
+
   // We can't tell whether weak symbols will end up pointing to the same
   // object.
   if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))


Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1274,3 +1274,12 @@
 (dbt2.wp = nullptr, 0)
   };
 }
+
+
+constexpr auto name1() { return "name1"; }
+constexpr auto name2() { return "name2"; }
+
+constexpr auto b3 = name1() == name1();
+static_assert(b3, "");
+constexpr auto b4 = name1() == name2();
+static_assert(!b4, "");
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -358,12 +358,29 @@
 
 extern char externalvar[];
 constexpr bool constaddress = (void *)externalvar == (void *)0x4000UL

[PATCH] D137712: Correctly handle Substitution failure in concept specialization.

2022-11-11 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 474716.
usaxena95 added a comment.

Moving closer to show diagnostic of entity for which SFNIAE occurred.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137712

Files:
  clang/include/clang/AST/ASTConcept.h
  clang/include/clang/AST/ExprConcepts.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTConcept.cpp
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/AST/ExprConcepts.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/SemaTemplate/concepts.cpp

Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -764,3 +764,53 @@
   __iterator_traits_member_pointer_or_arrow_or_void> f;
 }
 }// namespace InheritedFromPartialSpec
+
+namespace nested_requirements {
+template  concept True = true;
+
+struct S { double value; };
+
+template 
+concept Pipes = requires (T x) {
+   requires True || True;
+   requires True || True;
+};
+template 
+concept Amps1 = requires (T x) {
+   requires True && True;
+   // expected-note@-1{{because 'todo fill me' would be invalid: member reference base type 'int' is not a structure or union}}
+};
+template 
+concept Amps2 = requires (T x) {
+   requires True && True;
+};
+
+static_assert(Pipes);
+static_assert(Pipes);
+
+static_assert(Amps1);
+static_assert(!Amps1);
+
+static_assert(Amps2);
+static_assert(!Amps2);
+
+template
+void foo1() requires requires (T x) { // expected-note {{candidate template ignored: constraints not satisfied [with T = int]}}
+  requires 
+  True // expected-note {{because 'todo fill me' would be invalid: member reference base type 'int' is not a structure or union}}
+  && True;
+} {}
+template void fooPipes() requires Pipes {}
+template void fooAmps1() requires Amps1 {}
+// expected-note@-1 {{candidate template ignored: constraints not satisfied [with T = int]}} \
+// expected-note@-1 {{because 'int' does not satisfy 'Amps1'}}
+
+void foo() {
+  foo1();
+  foo1(); // expected-error {{no matching function for call to 'foo1'}}
+  fooPipes();
+  fooPipes();
+  fooAmps1();
+  fooAmps1(); // expected-error {{no matching function for call to 'fooAmps1'}}
+}
+}
\ No newline at end of file
Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -11,6 +11,7 @@
 ///
 //===--===//
 
+#include "clang/AST/ASTConcept.h"
 #include "clang/AST/ExprOpenMP.h"
 #include "clang/Serialization/ASTRecordWriter.h"
 #include "clang/Sema/DeclSpec.h"
@@ -412,19 +413,18 @@
   if (E)
 Record.AddStmt(E);
   else {
-auto *Diag = DetailRecord.second.get *>();
-Record.AddSourceLocation(Diag->first);
-Record.AddString(Diag->second);
+auto *Diag =
+DetailRecord.second.get();
+Record.AddSourceLocation(Diag->DiagLoc);
+Record.AddString(Diag->DiagMessage);
   }
 }
   }
 }
 
 static void
-addSubstitutionDiagnostic(
-ASTRecordWriter &Record,
-const concepts::Requirement::SubstitutionDiagnostic *D) {
+addSubstitutionDiagnostic(ASTRecordWriter &Record,
+  const concepts::SubstitutionDiagnostic *D) {
   Record.AddString(D->SubstitutedEntity);
   Record.AddSourceLocation(D->DiagLoc);
   Record.AddString(D->DiagMessage);
@@ -467,8 +467,8 @@
   Record.push_back(ExprReq->getKind());
   Record.push_back(ExprReq->Status);
   if (ExprReq->isExprSubstitutionFailure()) {
-addSubstitutionDiagnostic(Record,
- ExprReq->Value.get());
+addSubstitutionDiagnostic(
+Record, ExprReq->Value.get());
   } else
 Record.AddStmt(ExprReq->Value.get());
   if (ExprReq->getKind() == concepts::Requirement::RK_Compound) {
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -781,9 +781,9 @@
 SourceLocation DiagLocation = Record.readSourceLocation();
 std::string DiagMessage = Record.readString();
 Satisfaction.Details.emplace_back(
-ConstraintExpr, new (Record.getContext())
-ConstraintSatisfaction::SubstitutionDiagnostic{
-DiagLocation, DiagMessage});
+ConstraintExpr,
+new (Record.getContext()) concepts::SubstitutionDiagnostic{
+"todo: fill 

[PATCH] D136809: [CMake] Make sure all headers are installed into `CLANG_RESOURCE_DIR`

2022-11-11 Thread LJC via Phabricator via cfe-commits
paperchalice updated this revision to Diff 474715.
paperchalice added a comment.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Add cmake module to handle clang resource dir.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136809

Files:
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Tooling/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  cmake/Modules/GetClangResourceDir.cmake
  compiler-rt/cmake/base-config-ix.cmake
  lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
  lldb/unittests/Expression/ClangParserTest.cpp
  llvm/cmake/modules/LLVMExternalProjectUtils.cmake
  openmp/CMakeLists.txt

Index: openmp/CMakeLists.txt
===
--- openmp/CMakeLists.txt
+++ openmp/CMakeLists.txt
@@ -79,8 +79,8 @@
 if(${OPENMP_STANDALONE_BUILD})
   set(LIBOMP_HEADERS_INSTALL_PATH "${CMAKE_INSTALL_INCLUDEDIR}")
 else()
-  string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION ${PACKAGE_VERSION})
-  set(LIBOMP_HEADERS_INSTALL_PATH "${OPENMP_INSTALL_LIBDIR}/clang/${CLANG_VERSION}/include")
+  include(GetClangResourceDir)
+  get_clang_resource_dir(LIBOMP_HEADERS_INSTALL_PATH SUBDIR include)
 endif()
 
 # Build host runtime library, after LIBOMPTARGET variables are set since they are needed
Index: llvm/cmake/modules/LLVMExternalProjectUtils.cmake
===
--- llvm/cmake/modules/LLVMExternalProjectUtils.cmake
+++ llvm/cmake/modules/LLVMExternalProjectUtils.cmake
@@ -257,7 +257,11 @@
 if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
   string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR
  ${PACKAGE_VERSION})
-  set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  if(DEFINED CLANG_RESOURCE_DIR AND NOT CLANG_RESOURCE_DIR STREQUAL "")
+set(resource_dir ${LLVM_TOOLS_BINARY_DIR}/${CLANG_RESOURCE_DIR})
+  else()
+set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  endif()
   set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
   foreach(type ${flag_types})
 set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
Index: lldb/unittests/Expression/ClangParserTest.cpp
===
--- lldb/unittests/Expression/ClangParserTest.cpp
+++ lldb/unittests/Expression/ClangParserTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
 
 #include "Plugins/ExpressionParser/Clang/ClangHost.h"
 #include "TestingSupport/SubsystemRAII.h"
@@ -37,12 +38,16 @@
 TEST_F(ClangHostTest, ComputeClangResourceDirectory) {
 #if !defined(_WIN32)
   std::string path_to_liblldb = "/foo/bar/lib/";
-  std::string path_to_clang_dir =
-  "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING;
+  std::string path_to_clang_dir = CLANG_RESOURCE_DIR[0]
+  ? "/foo/bar/bin/" CLANG_RESOURCE_DIR
+  : "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME
+"/clang/" CLANG_VERSION_MAJOR_STRING;
 #else
   std::string path_to_liblldb = "C:\\foo\\bar\\lib";
   std::string path_to_clang_dir =
-  "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
+  CLANG_RESOURCE_DIR[0]
+  ? "C:\\foo\\bar\\bin\\" CLANG_RESOURCE_DIR
+  : "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
 #endif
   EXPECT_EQ(ComputeClangResourceDir(path_to_liblldb), path_to_clang_dir);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
@@ -54,8 +54,11 @@
 
   static const llvm::StringRef kResourceDirSuffixes[] = {
   // LLVM.org's build of LLDB uses the clang resource directory placed
-  // in $install_dir/lib{,64}/clang/$clang_version.
-  CLANG_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING,
+  // in $install_dir/lib{,64}/clang/$clang_version or
+  // $install_dir/bin/$CLANG_RESOURCE_DIR
+  CLANG_RESOURCE_DIR[0] ? "bin/" CLANG_RESOURCE_DIR
+: CLANG_INSTALL_LIBDIR_BASENAME
+  "/clang/" CLANG_VERSION_MAJOR_STRING,
   // swift-lldb uses the clang resource directory copied from swift, which
   // by default is placed in $install_dir/lib{,64}/lldb/clang. LLDB places
   // it there, so we use LLDB_INSTALL_LIBDIR_BASENAME.
Index: compiler-rt/cmake/base-config-ix.cmake
===
--- compiler-rt/cmake/base-config-ix.cmake
+++ compiler-rt/cmake/base-config-ix.cmake
@@ -7,6 +7,7 @@
 include(Check

[PATCH] D136936: [clang][Interp] Handle undefined functions better

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



Comment at: clang/lib/AST/Interp/ByteCodeEmitter.cpp:24-31
+  bool HasBody = true;
+
+  // Function is not defined at all or not yet. We will
+  // create a Function instance but not compile the body. That
+  // will (maybe) happen later.
   if (!FuncDecl->isDefined(FuncDecl) ||
   (!FuncDecl->hasBody() && FuncDecl->willHaveBody()))

aaron.ballman wrote:
> tbaeder wrote:
> > aaron.ballman wrote:
> > > tbaeder wrote:
> > > > aaron.ballman wrote:
> > > > >  negating the Boolean calculation and applying deMorgan's law did 
> > > > > not make that code more clear, did it (assuming I did everything 
> > > > > right)? If you agree, then I'm fine with the more complicated form 
> > > > > and letting the optimizer make it faster.
> > > > I can see that going either way. I think your version is a more 
> > > > confusing though because the two body conditions are coupled with the 
> > > > `isDefined` condition. E.g. `HasBody` is `true` if `isDefined() && 
> > > > !willHaveBody()`, which doesn't make sense to me I think.
> > > > 
> > > > I think I just read this code too many times now.  How does being 
> > > > defined even relate to the function having a body? Should that code 
> > > > just be `HasBody = hasBody() || willHaveBody()`?
> > > > I can see that going either way. I think your version is a more 
> > > > confusing though because the two body conditions are coupled with the 
> > > > isDefined condition. E.g. HasBody is true if isDefined() && 
> > > > !willHaveBody(), which doesn't make sense to me I think.
> > > 
> > > I'm glad we both are confused about the same thing!
> > > 
> > > > I think I just read this code too many times now. How does being 
> > > > defined even relate to the function having a body? Should that code 
> > > > just be HasBody = hasBody() || willHaveBody()?
> > > 
> > > I've not dug back in time to see how we got to that predicate in the 
> > > first place, but my *hunch* is that this may have to do with implicit 
> > > function definitions for things like special member functions. That's a 
> > > case where you can have a function definition without a body. e.g.,
> > > ```
> > > struct S {
> > >   S();
> > > };
> > > 
> > > S::S() = default;
> > > ```
> > Well, any sort of digging usually just gets you to the //one// commit that 
> > introduced all of the new constant interpreter :P 
> > 
> > `willHaveBody()` isn't even relevant here, is it?
> > I think simply
> > 
> > ``` 
> > bool hasBody = FuncDecl->isDefined() || FuncDecl->hasBody();
> > 
> > ```
> > makes the most sense.
> I think it's one or the other?
> 
> `isDefined` searches for a function that's been defined by looking for 
> something in the redecl chain that: is deleted as written, is defaulted, has 
> a body, will have a body, has a body that's skipped, or has an attribute that 
> causes the declaration to be a definition. 
> 
> By contrast, `hasBody` searches the redecl chain looking for a declaration 
> that has not been defaulted and has a body or is template late parsed.
> 
> So I *think* what you want is `FuncDecl->hasBody(FuncDecl)` to do the check 
> and get the specific declaration with the body.
`FuncDecl->hasBody(FuncDecl)` sounds like it makes sense. None of the 
variations break any of the existing tests, so I will trust you. :) Thanks


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

https://reviews.llvm.org/D136936

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


[PATCH] D136809: [CMake] Make sure all headers are installed into `CLANG_RESOURCE_DIR`

2022-11-11 Thread LJC via Phabricator via cfe-commits
paperchalice added inline comments.
Herald added subscribers: Michael137, JDevlieghere.



Comment at: clang/lib/Headers/CMakeLists.txt:285
+include(GetClangResourceDir)
+get_clang_resource_dir(output_dir PREFIX ${LLVM_BINARY_DIR}/$ SUBDIR 
include)
 set(out_files)

Another choice is `${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}`, but the variable 
`CMAKE_CFG_INTDIR` is [[ 
https://cmake.org/cmake/help/latest/variable/CMAKE_CFG_INTDIR.html | deprecated 
]] since 3.21



Comment at: cmake/Modules/GetClangResourceDir.cmake:13
+  else()
+string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR ${PACKAGE_VERSION})
+set(ret_dir lib${LLVM_LIBDIR_SUFFIX}/clang/${CLANG_VERSION_MAJOR})

Can I always rely on `PACKAGE_VERSION`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136809

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-11 Thread Sam James via cfe-commits


> On 10 Nov 2022, at 17:16, Zack Weinberg  wrote:
> 
> I’m the closest thing Autoconf has to a lead maintainer at present.
> 
> It’s come to my attention (via https://lwn.net/Articles/913505/ and
> https://fedoraproject.org/wiki/Changes/PortingToModernC) that GCC and
> Clang both plan to disable several “legacy” C language features by
> default in a near-future release (GCC 14, Clang 16) (see the Fedora
> wiki link for a list).  I understand that this change potentially
> breaks a lot of old dusty code, and in particular that
> Autoconf-generated configure scripts use constructs that may *silently
> give the wrong answer to a probe* when a stricter compiler is in use.

Thank you for asking. The fixes in git get us there, I think, as far
as you can, with the exception of the stuff you (and I) mention below.

> 
> [...]
> 
> The biggest remaining (potential) problem, that I’m aware of, is that
> AC_CHECK_FUNC unconditionally declares the function we’re probing for
> as ‘char NAME (void)’, and asks the compiler to call it with no
> arguments, regardless of what its prototype actually is.  It is not
> clear to me whether this will still work with the planned changes to
> the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
> triggered by ‘extern char memcpy(void);’ (or any other standard
> library function whose prototype is coded into the compiler) and this
> already causes problems for people who run configure scripts with
> CC='cc -Werror'.  Unfortunately this is very hard to fix — we would
> have to build a comprehensive list of library functions into Autoconf,
> mapping each to either its documented prototype or to a header where
> it ought to be declared; in the latter case we would also have to make
> e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
> sys/socket.h netdb.h]) which might mess up configure scripts that
> aren’t expecting headers to be probed at that point.
> 
> How important do you think it is for this to be fixed?
> 
> Are there any other changes you would like to see in a near-future
> Autoconf 2.72 in order to make this transition easier?

This might be a WONTFIX but let me mention it just for
the record:
1. AC_CHECK_FUNCS is, as you've noticed, very noisy.

I would support having a hardcoded list for certain CHOSTs
as Rich suggests to reduce noise, but I don't think we can
do this accurately very quickly.

I think for Gentoo's efforts, I might just build up a set
of cache variables for glibc/musl on each arch to
reduce the noise in logs. But that's time consuming
and brittle still, so I'm not sure.

(Note that Gentoo and Fedora are taking two complementary
but different approaches here:
we're diffing config.logs and other compiler
output, in addition to build logs, while Florian for Fedora
Is building a list of functions which *we know* are available
In a specific environment and patching gcc to spit out
logs when something in said list is missing. This mitigates
noise for things like functions in libbsd, which I'm finding
a bit of a pain.)

I'll see what others say.

2. I often have to set the following cache variables to
reduce noise in logs:
* ac_cv_c_undeclared_builtin_options="none needed"
* ac_cv_header_sys_types_h_makedev=no
* gl_cv_compiler_check_decl_option="-Werror=implicit-function-declaration" 
(obviously this is gnulib)
* gl_cv_minmax_in_limits_h=no

I don't know if we can do anything to make these tests smarter
or just leave it as-is. It's fine if we can't, as exporting the cache
vars is not a bad workaround for us when doing testing.

> 
> zw
> 
> p.s. GCC and Clang folks: As long as you’re changing the defaults out
> from under people, can you please also remove the last few predefined
> user-namespace macros (-Dlinux, -Dunix, -Darm, etc) from all the
> -std=gnuXX modes?

I support this as well. This kind of thing has led to endless
bugs in userland, see https://reviews.llvm.org/D137511.



signature.asc
Description: Message signed with OpenPGP
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137232: [clang][Interp] Support inc/dec operators on pointers

2022-11-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474724.
tbaeder marked 2 inline comments as done.

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

https://reviews.llvm.org/D137232

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

Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -215,9 +215,6 @@
 static_assert(b.a[1].a == 12, "");
 
 namespace IncDec {
-  // FIXME: Pointer arithmethic needs to be supported in inc/dec
-  //   unary operators
-#if 0
   constexpr int getNextElem(const int *A, int I) {
 const int *B = (A + I);
 ++B;
@@ -225,6 +222,91 @@
   }
   constexpr int E[] = {1,2,3,4};
 
-  static_assert(getNextElem(E, 1) == 3);
-#endif
+  static_assert(getNextElem(E, 1) == 3, "");
+
+  constexpr int getFirst() {
+const int *e = E;
+return *(e++);
+  }
+  static_assert(getFirst() == 1, "");
+
+  constexpr int getFirst2() {
+const int *e = E;
+e++;
+return *e;
+  }
+  static_assert(getFirst2() == 2, "");
+
+  constexpr int getSecond() {
+const int *e = E;
+return *(++e);
+  }
+  static_assert(getSecond() == 2, "");
+
+  constexpr int getSecond2() {
+const int *e = E;
+++e;
+return *e;
+  }
+  static_assert(getSecond2() == 2, "");
+
+  constexpr int getLast() {
+const int *e = E + 3;
+return *(e--);
+  }
+  static_assert(getLast() == 4, "");
+
+  constexpr int getLast2() {
+const int *e = E + 3;
+e--;
+return *e;
+  }
+  static_assert(getLast2() == 3, "");
+
+  constexpr int getSecondToLast() {
+const int *e = E + 3;
+return *(--e);
+  }
+  static_assert(getSecondToLast() == 3, "");
+
+  constexpr int getSecondToLast2() {
+const int *e = E + 3;
+--e;
+return *e;
+  }
+  static_assert(getSecondToLast2() == 3, "");
+
+  constexpr int bad1() { // ref-error {{never produces a constant expression}}
+const int *e =  E + 3;
+e++; // This is fine because it's a one-past-the-end pointer
+return *e; // expected-note {{read of dereferenced one-past-the-end pointer}} \
+   // ref-note 2{{read of dereferenced one-past-the-end pointer}}
+  }
+  static_assert(bad1() == 0, ""); // expected-error {{not an integral constant expression}} \
+  // expected-note {{in call to}} \
+  // ref-error {{not an integral constant expression}} \
+  // ref-note {{in call to}}
+
+  constexpr int bad2() { // ref-error {{never produces a constant expression}}
+const int *e = E + 4;
+e++; // expected-note {{cannot refer to element 5 of array of 4 elements}} \
+ // ref-note 2{{cannot refer to element 5 of array of 4 elements}}
+return *e; // This is UB as well
+  }
+  static_assert(bad2() == 0, ""); // expected-error {{not an integral constant expression}} \
+  // expected-note {{in call to}} \
+  // ref-error {{not an integral constant expression}} \
+  // ref-note {{in call to}}
+
+
+  constexpr int bad3() { // ref-error {{never produces a constant expression}}
+const int *e = E;
+e--; // expected-note {{cannot refer to element -1 of array of 4 elements}} \
+ // ref-note 2{{cannot refer to element -1 of array of 4 elements}}
+return *e; // This is UB as well
+  }
+   static_assert(bad3() == 0, ""); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to}} \
+   // ref-error {{not an integral constant expression}} \
+  // ref-note {{in call to}}
 };
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -395,12 +395,21 @@
 // [Pointer, Integral] -> [Pointer]
 def SubOffset : AluOpcode;
 
-// Pointer, Pointer] - [Integral]
+// [Pointer, Pointer] -> [Integral]
 def SubPtr : Opcode {
   let Types = [IntegerTypeClass];
   let HasGroup = 1;
 }
 
+// [Pointer] -> [Pointer]
+def IncPtr : Opcode {
+  let HasGroup = 0;
+}
+// [Pointer] -> [Pointer]
+def DecPtr : Opcode {
+  let HasGroup = 0;
+}
+
 //===--===//
 // Binary operators.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -105,6 +105,8 @@
 /// Interpreter entry point.
 bool Interpret(InterpState &S, APValue &Result);
 
+enum class ArithOp { Add, Sub };
+
 //===--

[PATCH] D137232: [clang][Interp] Support inc/dec operators on pointers

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



Comment at: clang/test/AST/Interp/arrays.cpp:216
 
-  static_assert(getNextElem(E, 1) == 3);
-#endif
+  static_assert(getNextElem(E, 1) == 3, "");
+

aaron.ballman wrote:
> aaron.ballman wrote:
> > I'd like test cases where the pointer arithmetic has run off the 
> > beginning/end of the object (forming the invalid pointer is UB per 
> > http://eel.is/c++draft/expr.add#4.3 even if you never dereference the 
> > pointer).
> ```
> constexpr int bad1() {
>   const int *e =  E + 3;
>   e++; // This is fine because it's a one-past-the-end pointer
>   return *e; // This is UB
> }
> 
> constexpr int bad2() {
>   const int *e = E + 4;
>   e++; // This is UB
>   return *e; // This is UB as well
> }
> 
> constexpr int bad3() {
>   const int *e = E;
>   --e; // This is UB
>   return *e; // This is UB as well
> }
> ```
Interesting side-effect of removing the `Run` call in 
`isPotentialConstantExpression()`: The new constant interpreter doesn't 
diagnose the "never produces a constant expression` case. The function must be 
called for any diagnostics to be printed.


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

https://reviews.llvm.org/D137232

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


[PATCH] D136815: [clang][Interp] Unify visiting variable declarations

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

Ping


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

https://reviews.llvm.org/D136815

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/lib/Tooling/Inclusions/Header.cpp:64
+  // particular preprocessor state, usually set up by another header.
+  return !isDontIncludeMeHeader(SM.getBufferData(SM.translateFile(FE)));
+}

kadircet wrote:
> `translateFile` actually does a linear scan over all the slocentries, so i 
> think it's better for this API to be based on FileID. (later on we can easily 
> get fileentry from fileid in constant time)
You can get content through the fileentry directly, no?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[clang-tools-extra] 8dfaf99 - [include-cleaner] Provide public to_string of RefType (for HTMLReport), clean up includes. NFC

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

Author: Sam McCall
Date: 2022-11-11T13:25:22+01:00
New Revision: 8dfaf9940abe029e4fd35c63e3d7f2df66306a06

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

LOG: [include-cleaner] Provide public to_string of RefType (for HTMLReport), 
clean up includes. NFC

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
clang-tools-extra/include-cleaner/lib/Types.cpp
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
index 78e61b81166a..85e3fe4d7827 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h
@@ -85,6 +85,7 @@ enum class RefType {
   /// Target's use can't be proven, e.g. a candidate for an unresolved 
overload.
   Ambiguous,
 };
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, RefType);
 
 /// Indicates that a piece of code refers to a symbol.
 struct SymbolReference {

diff  --git a/clang-tools-extra/include-cleaner/lib/Types.cpp 
b/clang-tools-extra/include-cleaner/lib/Types.cpp
index a3b2731401ae..d7b17376d131 100644
--- a/clang-tools-extra/include-cleaner/lib/Types.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Types.cpp
@@ -54,4 +54,16 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const 
SymbolReference &R) {
/*Width=*/CHAR_BIT * sizeof(SourceLocation::UIntTy));
 }
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, RefType T) {
+  switch (T) {
+  case RefType::Explicit:
+return OS << "explicit";
+  case RefType::Implicit:
+return OS << "implicit";
+  case RefType::Ambiguous:
+return OS << "ambiguous";
+  }
+  llvm_unreachable("Unexpected RefType");
+}
+
 } // namespace clang::include_cleaner

diff  --git a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp 
b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
index fd6fcee7e457..3d338cd59b28 100644
--- a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -7,7 +7,6 @@
 
//===--===//
 
 #include "AnalysisInternal.h"
-#include "clang-include-cleaner/Analysis.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"

diff  --git a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
index c4e5af21f20c..17d13018d152 100644
--- a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -14,9 +14,8 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Testing/Support/Annotations.h"
-#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 #include 
@@ -25,20 +24,6 @@
 
 namespace clang::include_cleaner {
 namespace {
-using testing::Pair;
-using testing::UnorderedElementsAre;
-
-llvm::StringLiteral to_string(RefType RT) {
-  switch (RT) {
-  case RefType::Explicit:
-return "explicit";
-  case RefType::Implicit:
-return "implicit";
-  case RefType::Ambiguous:
-return "ambiguous";
-  }
-  llvm_unreachable("Unexpected RefType");
-}
 
 // Specifies a test of which symbols are referenced by a piece of code.
 // If `// c++-header` is present, treats referencing code as a header file.
@@ -100,14 +85,14 @@ void testWalk(llvm::StringRef TargetCode, llvm::StringRef 
ReferencingCode) {
 DiagnosticsEngine::Note, Message, {}, {});
   };
   for (auto RT : {RefType::Explicit, RefType::Implicit, RefType::Ambiguous}) {
-auto RTStr = to_string(RT);
+auto RTStr = llvm::to_string(RT);
 for (auto Expected : Target.points(RTStr))
   if (!llvm::is_contained(ReferencedOffsets[RT], Expected))
-DiagnosePoint(("location not marked used with type " + RTStr).str(),
+DiagnosePoint("location not marked used with type " + RTStr,
   Expected);
 for (auto Actual : ReferencedOffsets[RT])
   if (!llvm::is_contained(Target.points(RTStr), Actual))
-DiagnosePoint(("location unexpectedly used with type " + RTStr).str(),
+DiagnosePoint("location unexpectedly used with type " + RTStr,
   Actual);
   }
 



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


[PATCH] D136457: [clang][Interp] Fix discarding non-primitive function call return values

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

Ping


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

https://reviews.llvm.org/D136457

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


[PATCH] D136694: [clang][Interp] Check that constructor calls initialize all record fields

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

Ping


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

https://reviews.llvm.org/D136694

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


[PATCH] D136751: [clang][Interp] This pointers are writable in constructors

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136751

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


[PATCH] D137070: [clang][Interp] Support destructors

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

Ping


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

https://reviews.llvm.org/D137070

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


[PATCH] D137235: [clang][Interp] Fix ImplicitValueInitExprs for pointer types

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137235

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


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

2022-11-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474726.
tbaeder marked an inline comment as done.

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

https://reviews.llvm.org/D137386

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


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -84,3 +84,18 @@
   return 5;
 }
 static_assert(a() == 5, "");
+
+constexpr int invalid() {
+  // Invalid expression in visit().
+  while(huh) {} // expected-error {{use of undeclared identifier}} \
+// ref-error {{use of undeclared identifier}}
+
+  return 0;
+}
+
+constexpr void invalid2() {
+  int i = 0;
+  // Invalid expression in discard().
+  huh(); // expected-error {{use of undeclared identifier}} \
+ // ref-error {{use of undeclared identifier}}
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -654,12 +654,18 @@
 }
 
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
 }
 
 template 
 bool ByteCodeExprGen::visit(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/false);
   return this->Visit(E);
 }
@@ -1227,8 +1233,8 @@
 /// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
+  assert(!VD->isInvalidDecl());
   Optional VarT = classify(VD->getType());
-
   // Create and initialize the variable.
   if (!this->visitVarDecl(VD))
 return false;


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -84,3 +84,18 @@
   return 5;
 }
 static_assert(a() == 5, "");
+
+constexpr int invalid() {
+  // Invalid expression in visit().
+  while(huh) {} // expected-error {{use of undeclared identifier}} \
+// ref-error {{use of undeclared identifier}}
+
+  return 0;
+}
+
+constexpr void invalid2() {
+  int i = 0;
+  // Invalid expression in discard().
+  huh(); // expected-error {{use of undeclared identifier}} \
+ // ref-error {{use of undeclared identifier}}
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -654,12 +654,18 @@
 }
 
 template  bool ByteCodeExprGen::discard(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
 }
 
 template 
 bool ByteCodeExprGen::visit(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/false);
   return this->Visit(E);
 }
@@ -1227,8 +1233,8 @@
 /// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
+  assert(!VD->isInvalidDecl());
   Optional VarT = classify(VD->getType());
-
   // Create and initialize the variable.
   if (!this->visitVarDecl(VD))
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2022-11-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474727.
tbaeder marked an inline comment as done.

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

https://reviews.llvm.org/D137386

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


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -84,3 +84,18 @@
   return 5;
 }
 static_assert(a() == 5, "");
+
+constexpr int invalid() {
+  // Invalid expression in visit().
+  while(huh) {} // expected-error {{use of undeclared identifier}} \
+// ref-error {{use of undeclared identifier}}
+
+  return 0;
+}
+
+constexpr void invalid2() {
+  int i = 0;
+  // Invalid expression in discard().
+  huh(); // expected-error {{use of undeclared identifier}} \
+ // ref-error {{use of undeclared identifier}}
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -654,12 +654,18 @@
 }
 
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
 }
 
 template 
 bool ByteCodeExprGen::visit(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/false);
   return this->Visit(E);
 }
@@ -1227,8 +1233,8 @@
 /// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
+  assert(!VD->isInvalidDecl() && "Trying to constant evaluate an invalid 
decl");
   Optional VarT = classify(VD->getType());
-
   // Create and initialize the variable.
   if (!this->visitVarDecl(VD))
 return false;


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -84,3 +84,18 @@
   return 5;
 }
 static_assert(a() == 5, "");
+
+constexpr int invalid() {
+  // Invalid expression in visit().
+  while(huh) {} // expected-error {{use of undeclared identifier}} \
+// ref-error {{use of undeclared identifier}}
+
+  return 0;
+}
+
+constexpr void invalid2() {
+  int i = 0;
+  // Invalid expression in discard().
+  huh(); // expected-error {{use of undeclared identifier}} \
+ // ref-error {{use of undeclared identifier}}
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -654,12 +654,18 @@
 }
 
 template  bool ByteCodeExprGen::discard(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
 }
 
 template 
 bool ByteCodeExprGen::visit(const Expr *E) {
+  if (E->containsErrors())
+return false;
+
   OptionScope Scope(this, /*NewDiscardResult=*/false);
   return this->Visit(E);
 }
@@ -1227,8 +1233,8 @@
 /// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
+  assert(!VD->isInvalidDecl() && "Trying to constant evaluate an invalid decl");
   Optional VarT = classify(VD->getType());
-
   // Create and initialize the variable.
   if (!this->visitVarDecl(VD))
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137825: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

2022-11-11 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

You could:

  static_assert(std::variant_size_v<> == 2);
  
  Kind kind() const { if (std::holds_alternative(Storage))  
return Kind::Physical; return Kind::Standard; }

and Kind could become `enum class Kind`. => You would get rid of the order on 
the variant and the `static_cast`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137825

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/include/clang/Tooling/Inclusions/Header.h:21
+///
+/// A header is considered self-contained if either it has a proper header 
guard
+/// or it doesn't has dont-include-me-similar pattern.

kadircet wrote:
> let's mention being `#import`d as well
again comment seems to be the same.



Comment at: clang/lib/Tooling/Inclusions/Header.cpp:64
+  // particular preprocessor state, usually set up by another header.
+  return !isDontIncludeMeHeader(SM.getBufferData(SM.translateFile(FE)));
+}

sammccall wrote:
> kadircet wrote:
> > `translateFile` actually does a linear scan over all the slocentries, so i 
> > think it's better for this API to be based on FileID. (later on we can 
> > easily get fileentry from fileid in constant time)
> You can get content through the fileentry directly, no?
oh thanks for reminding that i forgot to mention it here, yes we can get that, 
but that would misbehave in the case of virtual/remapped files. so can you 
actually add a comment here about why we should get the contents from source 
manager?



Comment at: clang/unittests/Tooling/HeaderTest.cpp:21
+  Inputs.Code = R"cpp(
+  #include "headerguard.h"
+  #include "pragmaonce.h"

kadircet wrote:
> can you also add a test case for `#import` ?
this is marked as done, but i can't see any #import statements here. am i 
missing something?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[PATCH] D137825: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

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

In D137825#3921273 , @tschuett wrote:

> You could:
>
>   static_assert(std::variant_size_v<> == 2);
>   
>   Kind kind() const { if (std::holds_alternative(Storage))  
> return Kind::Physical; return Kind::Standard; }
>
> and Kind could become `enum class Kind`. => You would get rid of the order on 
> the variant and the `static_cast`.

Sure, but that's IMO less regular, harder to understand, and easier to get 
wrong when updating.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137825

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


[clang] 1da74ee - [Clang][LoongArch] Remove duplicate declaration. NFC

2022-11-11 Thread via cfe-commits

Author: wanglei
Date: 2022-11-11T20:36:18+08:00
New Revision: 1da74eeb0e1b6cb0d427148d9ed05afb3a1e01bc

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

LOG: [Clang][LoongArch] Remove duplicate declaration. NFC

Added: 


Modified: 
clang/lib/Driver/ToolChains/Arch/LoongArch.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.h 
b/clang/lib/Driver/ToolChains/Arch/LoongArch.h
index 2f85dd0e0e88f..0084474e7ed3f 100644
--- a/clang/lib/Driver/ToolChains/Arch/LoongArch.h
+++ b/clang/lib/Driver/ToolChains/Arch/LoongArch.h
@@ -20,12 +20,9 @@ namespace loongarch {
 void getLoongArchTargetFeatures(const Driver &D, const llvm::Triple &Triple,
 const llvm::opt::ArgList &Args,
 std::vector &Features);
+
 StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args,
   const llvm::Triple &Triple);
-
-void getLoongArchTargetFeatures(const Driver &D, const llvm::Triple &Triple,
-const llvm::opt::ArgList &Args,
-std::vector &Features);
 } // end namespace loongarch
 } // end namespace tools
 } // end namespace driver



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


[PATCH] D137825: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

2022-11-11 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/D137825/new/

https://reviews.llvm.org/D137825

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/lib/Tooling/Inclusions/Header.cpp:64
+  // particular preprocessor state, usually set up by another header.
+  return !isDontIncludeMeHeader(SM.getBufferData(SM.translateFile(FE)));
+}

kadircet wrote:
> sammccall wrote:
> > kadircet wrote:
> > > `translateFile` actually does a linear scan over all the slocentries, so 
> > > i think it's better for this API to be based on FileID. (later on we can 
> > > easily get fileentry from fileid in constant time)
> > You can get content through the fileentry directly, no?
> oh thanks for reminding that i forgot to mention it here, yes we can get 
> that, but that would misbehave in the case of virtual/remapped files. so can 
> you actually add a comment here about why we should get the contents from 
> source manager?
But even when that remapping happens at the sourcemanager level, it happens on 
fileentries, not FileIDs (how would the latter even work?)

So SM.getMemoryBufferForFileOrNone(FileEntry)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[clang-tools-extra] 7943169 - [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

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

Author: Sam McCall
Date: 2022-11-11T13:41:54+01:00
New Revision: 7943169273b22f61a0322cb2d38ff75845e52628

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

LOG: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

- replace SymbolLocation std::variant with enum-exposing version similar to
  those in types.cpp. There's no appropriate implementation file, added
  LocateSymbol.cpp in anticipation of locateDecl/locateMacro.
- FindHeaders is not part of the public Analysis interface, so should not
  be implemented/tested there (just code organization)
- rename findIncludeHeaders->findHeaders to avoid confusion with Include concept

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

Added: 
clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Modified: 
clang-tools-extra/include-cleaner/lib/Analysis.cpp
clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
clang-tools-extra/include-cleaner/lib/CMakeLists.txt
clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
clang-tools-extra/include-cleaner/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index b3238e93bcc9..d20e5b162907 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -28,52 +28,18 @@ void walkUsed(llvm::ArrayRef ASTRoots,
   if (auto SS = Recognizer(&ND)) {
 // FIXME: Also report forward decls from main-file, so that the caller
 // can decide to insert/ignore a header.
-return CB({Loc, Symbol(*SS), RT}, findIncludeHeaders(*SS, SM, PI));
+return CB({Loc, Symbol(*SS), RT}, findHeaders(*SS, SM, PI));
   }
   // FIXME: Extract locations from redecls.
-  return CB({Loc, Symbol(ND), RT},
-findIncludeHeaders(ND.getLocation(), SM, PI));
+  return CB({Loc, Symbol(ND), RT}, findHeaders(ND.getLocation(), SM, PI));
 });
   }
   for (const SymbolReference &MacroRef : MacroRefs) {
 assert(MacroRef.Target.kind() == Symbol::Macro);
 // FIXME: Handle macro locations.
 return CB(MacroRef,
-  findIncludeHeaders(MacroRef.Target.macro().Definition, SM, PI));
+  findHeaders(MacroRef.Target.macro().Definition, SM, PI));
   }
 }
 
-llvm::SmallVector findIncludeHeaders(const SymbolLocation &SLoc,
- const SourceManager &SM,
- const PragmaIncludes &PI) {
-  llvm::SmallVector Results;
-  if (auto *Loc = std::get_if(&SLoc)) {
-// FIXME: Handle non self-contained files.
-FileID FID = SM.getFileID(*Loc);
-const auto *FE = SM.getFileEntryForID(FID);
-if (!FE)
-  return {};
-
-// We treat the spelling header in the IWYU pragma as the final public
-// header.
-// FIXME: look for exporters if the public header is exported by another
-// header.
-llvm::StringRef VerbatimSpelling = PI.getPublic(FE);
-if (!VerbatimSpelling.empty())
-  return {Header(VerbatimSpelling)};
-
-Results = {Header(FE)};
-// FIXME: compute transitive exporter headers.
-for (const auto *Export : PI.getExporters(FE, SM.getFileManager()))
-  Results.push_back(Export);
-return Results;
-  }
-  if (auto *Sym = std::get_if(&SLoc)) {
-for (const auto &H : Sym->headers())
-  Results.push_back(H);
-return Results;
-  }
-  llvm_unreachable("unhandled SymbolLocation kind!");
-}
-
 } // namespace clang::include_cleaner

diff  --git a/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h 
b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
index 18bcedde1a2e..17c11c1218dd 100644
--- a/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
+++ b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
@@ -47,17 +47,41 @@ namespace include_cleaner {
 void walkAST(Decl &Root,
  llvm::function_ref);
 
-/// A location where a symbol can be provided.
+/// A place where a symbol can be provided.
 /// It is either a physical file of the TU (SourceLocation) or a logical
 /// location in the standard library (stdlib::Symbol).
-// FIXME: use a real Class!
-using SymbolLocation = std::variant;
+struct SymbolLocation {
+  enum Kind {
+/// A position within a source file (or macro expansion) parsed by clang.
+Physical,
+/// A recognized standard library symbol, like std::string.
+Standard,
+  };
+
+  SymbolLocation(SourceLocation S) : Storage(S) {}
+  SymbolLocation(tooling::stdlib::Symbol S) : Storage(S) {}
+
+  Kind kind() const { return stati

[PATCH] D137825: [clang-include-cleaner] make SymbolLocation a real class, move FindHeaders

2022-11-11 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7943169273b2: [clang-include-cleaner] make SymbolLocation a 
real class, move FindHeaders (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137825

Files:
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/CMakeLists.txt
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- /dev/null
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -0,0 +1,79 @@
+//===--- FindHeadersTest.cpp --===//
+//
+// 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
+//
+//===--===//
+
+#include "AnalysisInternal.h"
+#include "clang-include-cleaner/Record.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Testing/TestAST.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang::include_cleaner {
+namespace {
+using testing::UnorderedElementsAre;
+
+TEST(FindIncludeHeaders, IWYU) {
+  TestInputs Inputs;
+  PragmaIncludes PI;
+  Inputs.MakeAction = [&PI] {
+struct Hook : public PreprocessOnlyAction {
+public:
+  Hook(PragmaIncludes *Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+Out->record(CI);
+return true;
+  }
+
+  PragmaIncludes *Out;
+};
+return std::make_unique(&PI);
+  };
+
+  Inputs.Code = R"cpp(
+#include "header1.h"
+#include "header2.h"
+  )cpp";
+  Inputs.ExtraFiles["header1.h"] = R"cpp(
+// IWYU pragma: private, include "path/public.h"
+  )cpp";
+  Inputs.ExtraFiles["header2.h"] = R"cpp(
+#include "detail1.h" // IWYU pragma: export
+
+// IWYU pragma: begin_exports
+#include "detail2.h"
+// IWYU pragma: end_exports
+
+#include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["normal.h"] = Inputs.ExtraFiles["detail1.h"] =
+  Inputs.ExtraFiles["detail2.h"] = "";
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+  auto &FM = SM.getFileManager();
+  // Returns the source location for the start of the file.
+  auto SourceLocFromFile = [&](llvm::StringRef FileName) {
+return SM.translateFileLineCol(FM.getFile(FileName).get(),
+   /*Line=*/1, /*Col=*/1);
+  };
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("header1.h"), SM, PI),
+  UnorderedElementsAre(Header("\"path/public.h\"")));
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail1.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
+   Header(FM.getFile("detail1.h").get(;
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail2.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
+   Header(FM.getFile("detail2.h").get(;
+
+  EXPECT_THAT(findHeaders(SourceLocFromFile("normal.h"), SM, PI),
+  UnorderedElementsAre(Header(FM.getFile("normal.h").get(;
+}
+
+} // namespace
+} // namespace clang::include_cleaner
\ No newline at end of file
Index: clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
===
--- clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
+++ clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
@@ -6,6 +6,7 @@
 add_custom_target(ClangIncludeCleanerUnitTests)
 add_unittest(ClangIncludeCleanerUnitTests ClangIncludeCleanerTests
   AnalysisTest.cpp
+  FindHeadersTest.cpp
   RecordTest.cpp
   WalkASTTest.cpp
 )
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -7,7 +7,6 @@
 //===--===//
 
 #include "clang-include-cleaner/Analysis.h"
-#include "AnalysisInternal.h"
 #include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/AST/ASTContext.h"
@@ -130,63 +129,6 @@
   UnorderedElem

[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/lib/Tooling/Inclusions/Header.cpp:64
+  // particular preprocessor state, usually set up by another header.
+  return !isDontIncludeMeHeader(SM.getBufferData(SM.translateFile(FE)));
+}

sammccall wrote:
> kadircet wrote:
> > sammccall wrote:
> > > kadircet wrote:
> > > > `translateFile` actually does a linear scan over all the slocentries, 
> > > > so i think it's better for this API to be based on FileID. (later on we 
> > > > can easily get fileentry from fileid in constant time)
> > > You can get content through the fileentry directly, no?
> > oh thanks for reminding that i forgot to mention it here, yes we can get 
> > that, but that would misbehave in the case of virtual/remapped files. so 
> > can you actually add a comment here about why we should get the contents 
> > from source manager?
> But even when that remapping happens at the sourcemanager level, it happens 
> on fileentries, not FileIDs (how would the latter even work?)
> 
> So SM.getMemoryBufferForFileOrNone(FileEntry)?
oh i didn't know about `getMemoryBufferForFileOrNone`, looks like it should do.

> But even when that remapping happens at the sourcemanager level, it happens 
> on fileentries, not FileIDs (how would the latter even work?)

i was just looking at contentcache, which is a 1:1 mapping for each FileID and 
has fileentries, one for the original file and the other for providing the 
contents (or a virtual buffer). i didn't notice the overrideinfo map was also 
exposed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[PATCH] D137531: [clang] Add the check of decltype in derived templates for issue #58674

2022-11-11 Thread Liming Liu via Phabricator via cfe-commits
lime updated this revision to Diff 474731.

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

https://reviews.llvm.org/D137531

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExpr.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/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -2693,19 +2693,28 @@
   // spuriously dependent expression if we're inside a dependent
   // instance method.
   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())) {
+if (auto Class = dyn_cast_if_present(
+(*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)))
+break;
+}
+  }
+}
+  } else if (IsAddressOfOperand)
+MightBeImplicitMember = false;
+}
 
 if (MightBeImplicitMember)
   return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -298,6 +298,9 @@
   and Clang 15 accidentally stopped predeclaring those functions in that
   language mode. Clang 16 now predeclares those functions again. This fixes
   `Issue 56607 `_.
+- Fix an issue about ``decltype`` in the members of class templates derived from
+  templates with related parameters.
+  `Issue 58674 `_
 
 Improvements to Clang's diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137823: [clang-format][NFC] Moved configuration parsing tests in own file

2022-11-11 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel added inline comments.



Comment at: clang/unittests/Format/ConfigParseTest.cpp:1
+//===- unittest/Format/ConfiParseTest.cpp - Config parsing unit tests 
-===//
+//

typo (Confi) :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137823

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


[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

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

This seems reasonable to me, but I'll leave the final sign-off to Erich.




Comment at: clang/lib/Sema/SemaStmtAttr.cpp:331-332
 const LoopHintAttr *NumericAttr;
-  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}};
+  } HintAttrs[CategoryType::NumberOfCategories];
+  memset(HintAttrs, 0, sizeof(HintAttrs));
 

Might as well rely on value initalization instead of a runtime call to memset.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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

getBufferData => getMemoryBufferForFileOrNone


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/CMakeLists.txt
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -0,0 +1,66 @@
+//===- unittest/Tooling/HeaderAnalysisTest.cpp ===//
+//
+// 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
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Testing/TestAST.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+TEST(HeaderAnalysisTest, IsSelfContained) {
+  TestInputs Inputs;
+  Inputs.Code = R"cpp(
+  #include "headerguard.h"
+  #include "pragmaonce.h"
+  #import "imported.h"
+
+  #include "bad.h"
+  #include "unguarded.h"
+  )cpp";
+
+  Inputs.ExtraFiles["headerguard.h"] = R"cpp(
+  #ifndef HEADER_H
+  #define HEADER_H
+
+  #endif HEADER_H
+  )cpp";
+  Inputs.ExtraFiles["pragmaonce.h"] = R"cpp(
+  #pragma once
+  )cpp";
+  Inputs.ExtraFiles["imported.h"] = "";
+
+  Inputs.ExtraFiles["unguarded.h"] = "";
+  Inputs.ExtraFiles["bad.h"] = R"cpp(
+  #pragma once
+
+  #if defined(INSIDE_H)
+  #error "Only ... can be included directly"
+  #endif
+  )cpp";
+
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+  auto &FM = SM.getFileManager();
+  auto &HI = AST.preprocessor().getHeaderSearchInfo();
+  auto getFileID = [&](llvm::StringRef FileName) {
+return SM.translateFile(FM.getFile(FileName).get());
+  };
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("headerguard.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("pragmaonce.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("imported.h"), SM, HI));
+
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("unguarded.h"), SM, HI));
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("bad.h"), SM, HI));
+}
+
+} // namespace
+} // namespace tooling
+} // namespace clang
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -16,6 +16,7 @@
   DiagnosticsYamlTest.cpp
   ExecutionTest.cpp
   FixItTest.cpp
+  HeaderAnalysisTest.cpp
   HeaderIncludesTest.cpp
   StandardLibraryTest.cpp
   LexicallyOrderedRecursiveASTVisitorTest.cpp
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -0,0 +1,69 @@
+//===--- HeaderAnalysis.cpp -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/HeaderSearch.h"
+
+namespace clang::tooling {
+namespace {
+
+// Is Line an #if or #ifdef directive?
+// FIXME: This makes headers with #ifdef LINUX/WINDOWS/MACOS marked as non
+// self-contained and is probably not what we want.
+bool isIf(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  return Line.startswith("if");
+}
+
+// Is Line an #error directive mentioning includes?
+bool isErrorAboutInclude(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  if (!Line.startswith("error"))
+return false;
+  return Line.contains_insensitive(
+  "includ"); // Matches "include" or "including".
+}
+
+// Heuristically headers that only want to be included via an umbrella.
+bool isDontIncludeMeHeader(llvm::MemoryBufferRef Buffer) {
+  StringRef Content = Buffer.getBuffer();
+  llvm::StringRef Line;
+  // Only sniff up to 100 lines or 10KB.
+  Content = Content.take_front(100 * 100);
+  for (unsi

[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/include/clang/Tooling/Inclusions/Header.h:21
+///
+/// A header is considered self-contained if either it has a proper header 
guard
+/// or it doesn't has dont-include-me-similar pattern.

kadircet wrote:
> kadircet wrote:
> > let's mention being `#import`d as well
> again comment seems to be the same.
you're looking at the old version, this file has been renamed, please see the 
https://reviews.llvm.org/D137697.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[clang-tools-extra] 15b2702 - [include-cleaner] NFC, correct a comment in

2022-11-11 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-11-11T14:40:08+01:00
New Revision: 15b2702e83fa1e99e56b51a4254e8dc4f331ca9d

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

LOG: [include-cleaner] NFC, correct a comment in
PragmaIncludes::RecordPragma.

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/Record.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index 4dabd4aa6d07..72db299114da 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -225,9 +225,9 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
   // 2. handleCommentInMainFile("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // This code stores the last location of "IWYU pragma: keep" (or export)
-  // comment in the main file, so that when next InclusionDirective is
-  // called, it will know that the next inclusion is behind the IWYU 
pragma.
+  // This code stores the last location of "IWYU pragma: keep" comment in
+  // the main file, so that when next InclusionDirective is called, it will
+  // know that the next inclusion is behind the IWYU pragma.
   LastPragmaKeepInMainFileLine = CommentLine;
 }
 return false;



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


[clang-tools-extra] e000c2b - [include-cleaner] NFC, move the macro location fixme to findHeaders.

2022-11-11 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-11-11T14:55:29+01:00
New Revision: e000c2bce75ec59782e1a2459c4db6d7a996590c

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

LOG: [include-cleaner] NFC, move the macro location fixme to findHeaders.

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/Analysis.cpp
clang-tools-extra/include-cleaner/lib/FindHeaders.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index d20e5b162907..9e04ab7dd566 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -36,7 +36,6 @@ void walkUsed(llvm::ArrayRef ASTRoots,
   }
   for (const SymbolReference &MacroRef : MacroRefs) {
 assert(MacroRef.Target.kind() == Symbol::Macro);
-// FIXME: Handle macro locations.
 return CB(MacroRef,
   findHeaders(MacroRef.Target.macro().Definition, SM, PI));
   }

diff  --git a/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp 
b/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
index e9e5126da114..093cba8b769a 100644
--- a/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
+++ b/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
@@ -18,6 +18,7 @@ llvm::SmallVector findHeaders(const SymbolLocation 
&Loc,
   llvm::SmallVector Results;
   switch (Loc.kind()) {
   case SymbolLocation::Physical: {
+// FIXME: Handle macro locations.
 // FIXME: Handle non self-contained files.
 FileID FID = SM.getFileID(Loc.physical());
 const auto *FE = SM.getFileEntryForID(FID);



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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

2022-11-11 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, lgtm!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

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



Comment at: clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h:28
+/// dont-include-me pattern heuristically.
+bool isSelfContainedHeader(FileID FID, const SourceManager &SM,
+   HeaderSearch &HeaderInfo);

oops sorry, missed this part. the idea with using getmemorybuffer was to use 
fileentries here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[PATCH] D137677: [include-cleaner] add macro symbols and implicit refs to HTML report

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

- hover card follows the internal data model: symbol -> location -> header 
(->include, later)
- don't use public API, so we can get at internal details


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137677

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/lib/Types.cpp
  clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -61,19 +61,19 @@
/*Line=*/1, /*Col=*/1);
   };
 
-  EXPECT_THAT(findHeaders(SourceLocFromFile("header1.h"), SM, PI),
+  EXPECT_THAT(findHeaders(SourceLocFromFile("header1.h"), SM, &PI),
   UnorderedElementsAre(Header("\"path/public.h\"")));
 
-  EXPECT_THAT(findHeaders(SourceLocFromFile("detail1.h"), SM, PI),
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail1.h"), SM, &PI),
   UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
Header(FM.getFile("detail1.h").get(;
-  EXPECT_THAT(findHeaders(SourceLocFromFile("detail2.h"), SM, PI),
+  EXPECT_THAT(findHeaders(SourceLocFromFile("detail2.h"), SM, &PI),
   UnorderedElementsAre(Header(FM.getFile("header2.h").get()),
Header(FM.getFile("detail2.h").get(;
 
-  EXPECT_THAT(findHeaders(SourceLocFromFile("normal.h"), SM, PI),
+  EXPECT_THAT(findHeaders(SourceLocFromFile("normal.h"), SM, &PI),
   UnorderedElementsAre(Header(FM.getFile("normal.h").get(;
 }
 
 } // namespace
 } // namespace clang::include_cleaner
\ No newline at end of file
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -72,7 +72,7 @@
 
   auto &SM = AST.sourceManager();
   llvm::DenseMap> OffsetToProviders;
-  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, PI, SM,
+  walkUsed(TopLevelDecls, /*MacroRefs=*/{}, &PI, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
@@ -113,11 +113,10 @@
   Symbol Answer =
   Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
   llvm::DenseMap> OffsetToProviders;
-  PragmaIncludes PI;
   walkUsed(/*ASTRoots=*/{}, /*MacroRefs=*/
{SymbolReference{SM.getComposedLoc(SM.getMainFileID(), Main.point()),
 Answer, RefType::Explicit}},
-   PI, SM,
+   /*PI=*/nullptr, SM,
[&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
  auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
  EXPECT_EQ(FID, SM.getMainFileID());
Index: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
===
--- clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -47,6 +47,15 @@
 
 class HTMLReportAction : public clang::ASTFrontendAction {
   RecordedAST AST;
+  RecordedPP PP;
+  PragmaIncludes PI;
+
+  void ExecuteAction() override {
+auto &P = getCompilerInstance().getPreprocessor();
+P.addPPCallbacks(PP.record(P));
+PI.record(getCompilerInstance());
+ASTFrontendAction::ExecuteAction();
+  }
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef File) override {
@@ -62,7 +71,7 @@
   exit(1);
 }
 writeHTMLReport(AST.Ctx->getSourceManager().getMainFileID(), AST.Roots,
-*AST.Ctx, OS);
+PP.MacroReferences, *AST.Ctx, &PI, OS);
   }
 };
 
Index: clang-tools-extra/include-cleaner/lib/Types.cpp
===
--- clang-tools-extra/include-cleaner/lib/Types.cpp
+++ clang-tools-extra/include-cleaner/lib/Types.cpp
@@ -18,10 +18,10 @@
   switch (S.kind()) {
   case Symbol::Declaration:
 if (const auto *ND = llvm::dyn_cast(&S.declaration()))
-  return OS << ND->getN

[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2022-11-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked an inline comment as done.
tbaeder added a comment.

Can't push this without https://reviews.llvm.org/D135750, since the variables 
in the test functions are used without being initialized.


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

https://reviews.llvm.org/D137071

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


[PATCH] D137835: [ARM] Move ARM::parseBranchProtection into ARMTargetParser

2022-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary created this revision.
Herald added subscribers: hiraditya, kristof.beyls.
Herald added a project: All.
lenary requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay.
Herald added projects: clang, LLVM.

This should live with the Arm targets, given they have target-specific
target parsers.

Depends on D137834 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137835

Files:
  clang/lib/Basic/Targets/AArch64.h
  clang/lib/Basic/Targets/ARM.h
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/include/llvm/Support/ARMTargetParser.h
  llvm/include/llvm/Support/TargetParser.h
  llvm/lib/Support/ARMTargetParser.cpp
  llvm/lib/Support/TargetParser.cpp

Index: llvm/lib/Support/TargetParser.cpp
===
--- llvm/lib/Support/TargetParser.cpp
+++ llvm/lib/Support/TargetParser.cpp
@@ -337,51 +337,3 @@
 
 } // namespace RISCV
 } // namespace llvm
-
-// Parse a branch protection specification, which has the form
-//   standard | none | [bti,pac-ret[+b-key,+leaf]*]
-// Returns true on success, with individual elements of the specification
-// returned in `PBP`. Returns false in error, with `Err` containing
-// an erroneous part of the spec.
-bool ARM::parseBranchProtection(StringRef Spec, ParsedBranchProtection &PBP,
-StringRef &Err) {
-  PBP = {"none", "a_key", false};
-  if (Spec == "none")
-return true; // defaults are ok
-
-  if (Spec == "standard") {
-PBP.Scope = "non-leaf";
-PBP.BranchTargetEnforcement = true;
-return true;
-  }
-
-  SmallVector Opts;
-  Spec.split(Opts, "+");
-  for (int I = 0, E = Opts.size(); I != E; ++I) {
-StringRef Opt = Opts[I].trim();
-if (Opt == "bti") {
-  PBP.BranchTargetEnforcement = true;
-  continue;
-}
-if (Opt == "pac-ret") {
-  PBP.Scope = "non-leaf";
-  for (; I + 1 != E; ++I) {
-StringRef PACOpt = Opts[I + 1].trim();
-if (PACOpt == "leaf")
-  PBP.Scope = "all";
-else if (PACOpt == "b-key")
-  PBP.Key = "b_key";
-else
-  break;
-  }
-  continue;
-}
-if (Opt == "")
-  Err = "";
-else
-  Err = Opt;
-return false;
-  }
-
-  return true;
-}
Index: llvm/lib/Support/ARMTargetParser.cpp
===
--- llvm/lib/Support/ARMTargetParser.cpp
+++ llvm/lib/Support/ARMTargetParser.cpp
@@ -712,3 +712,51 @@
 
   llvm_unreachable("invalid arch name");
 }
+
+// Parse a branch protection specification, which has the form
+//   standard | none | [bti,pac-ret[+b-key,+leaf]*]
+// Returns true on success, with individual elements of the specification
+// returned in `PBP`. Returns false in error, with `Err` containing
+// an erroneous part of the spec.
+bool ARM::parseBranchProtection(StringRef Spec, ParsedBranchProtection &PBP,
+StringRef &Err) {
+  PBP = {"none", "a_key", false};
+  if (Spec == "none")
+return true; // defaults are ok
+
+  if (Spec == "standard") {
+PBP.Scope = "non-leaf";
+PBP.BranchTargetEnforcement = true;
+return true;
+  }
+
+  SmallVector Opts;
+  Spec.split(Opts, "+");
+  for (int I = 0, E = Opts.size(); I != E; ++I) {
+StringRef Opt = Opts[I].trim();
+if (Opt == "bti") {
+  PBP.BranchTargetEnforcement = true;
+  continue;
+}
+if (Opt == "pac-ret") {
+  PBP.Scope = "non-leaf";
+  for (; I + 1 != E; ++I) {
+StringRef PACOpt = Opts[I + 1].trim();
+if (PACOpt == "leaf")
+  PBP.Scope = "all";
+else if (PACOpt == "b-key")
+  PBP.Key = "b_key";
+else
+  break;
+  }
+  continue;
+}
+if (Opt == "")
+  Err = "";
+else
+  Err = Opt;
+return false;
+  }
+
+  return true;
+}
Index: llvm/include/llvm/Support/TargetParser.h
===
--- llvm/include/llvm/Support/TargetParser.h
+++ llvm/include/llvm/Support/TargetParser.h
@@ -182,19 +182,6 @@
 bool getCPUFeaturesExceptStdExt(CPUKind Kind, std::vector &Features);
 
 } // namespace RISCV
-
-namespace ARM {
-struct ParsedBranchProtection {
-  StringRef Scope;
-  StringRef Key;
-  bool BranchTargetEnforcement;
-};
-
-bool parseBranchProtection(StringRef Spec, ParsedBranchProtection &PBP,
-   StringRef &Err);
-
-} // namespace ARM
-
 } // namespace llvm
 
 #endif
Index: llvm/include/llvm/Support/ARMTargetParser.h
===
--- llvm/include/llvm/Support/ARMTargetParser.h
+++ llvm/include/llvm/Support/ARMTargetParser.h
@@ -302,6 +302,15 @@
 /// string then the triple's arch name is used.
 StringRef getARMCPUForArch(const llvm::Triple &Triple, StringRef MArch = {});
 
+struct ParsedBranchProtection {
+  StringRef Scope;
+  StringRef Key;
+  bool BranchTargetEnforcement;
+};
+

[PATCH] D137836: [Support] Move getHostNumPhysicalCores to Threading.h

2022-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary created this revision.
Herald added subscribers: kadircet, arphaman, hiraditya, krytarowski.
Herald added a project: All.
lenary requested review of this revision.
Herald added projects: LLVM, clang-tools-extra.
Herald added subscribers: cfe-commits, llvm-commits.

This change is focussed on simplifying `Support/Host.h` to only do
target detection. In this case, this function is close in usage to
existing functions in `Support/Threading.h`, so I moved it into there.
The function is also renamed to `llvm::get_physical_cores()` to match
the style of threading's functions.

Depends on D137835 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137836

Files:
  clang-tools-extra/clangd/test/Inputs/BenchmarkHeader.h
  llvm/include/llvm/Support/Host.h
  llvm/include/llvm/Support/Threading.h
  llvm/lib/Support/Host.cpp
  llvm/lib/Support/Threading.cpp
  llvm/unittests/Support/Host.cpp
  llvm/unittests/Support/Threading.cpp

Index: llvm/unittests/Support/Threading.cpp
===
--- llvm/unittests/Support/Threading.cpp
+++ llvm/unittests/Support/Threading.cpp
@@ -7,6 +7,8 @@
 //===--===//
 
 #include "llvm/Support/Threading.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/Host.h"
 #include "llvm/Support/thread.h"
 #include "gtest/gtest.h"
 
@@ -25,6 +27,37 @@
 hardware_concurrency().compute_thread_count());
 }
 
+class ThreadingTest : public testing::Test {
+  Triple Host;
+
+protected:
+  bool isSupportedArchAndOS() {
+// Initially this is only testing detection of the number of
+// physical cores, which is currently only supported/tested on
+// some systems.
+return (Host.isOSWindows() && llvm_is_multithreaded()) ||
+   Host.isOSDarwin() || (Host.isX86() && Host.isOSLinux()) ||
+   (Host.isOSLinux() && !Host.isAndroid()) ||
+   (Host.isSystemZ() && Host.isOSzOS());
+  }
+
+  ThreadingTest() : Host(Triple::normalize(sys::getProcessTriple())) {}
+};
+
+TEST_F(ThreadingTest, NumPhysicalCoresSupported) {
+  if (!isSupportedArchAndOS())
+GTEST_SKIP();
+  int Num = get_physical_cores();
+  ASSERT_GT(Num, 0);
+}
+
+TEST_F(ThreadingTest, NumPhysicalCoresUnsupported) {
+  if (isSupportedArchAndOS())
+GTEST_SKIP();
+  int Num = get_physical_cores();
+  ASSERT_EQ(Num, -1);
+}
+
 #if LLVM_ENABLE_THREADS
 
 class Notification {
Index: llvm/unittests/Support/Host.cpp
===
--- llvm/unittests/Support/Host.cpp
+++ llvm/unittests/Support/Host.cpp
@@ -30,36 +30,7 @@
 
 using namespace llvm;
 
-class HostTest : public testing::Test {
-  Triple Host;
-
-protected:
-  bool isSupportedArchAndOS() {
-// Initially this is only testing detection of the number of
-// physical cores, which is currently only supported/tested on
-// some systems.
-return (Host.isOSWindows() && llvm_is_multithreaded()) ||
-   Host.isOSDarwin() || (Host.isX86() && Host.isOSLinux()) ||
-   (Host.isOSLinux() && !Host.isAndroid()) ||
-   (Host.isSystemZ() && Host.isOSzOS());
-  }
-
-  HostTest() : Host(Triple::normalize(sys::getProcessTriple())) {}
-};
-
-TEST_F(HostTest, NumPhysicalCoresSupported) {
-  if (!isSupportedArchAndOS())
-GTEST_SKIP();
-  int Num = sys::getHostNumPhysicalCores();
-  ASSERT_GT(Num, 0);
-}
-
-TEST_F(HostTest, NumPhysicalCoresUnsupported) {
-  if (isSupportedArchAndOS())
-GTEST_SKIP();
-  int Num = sys::getHostNumPhysicalCores();
-  ASSERT_EQ(Num, -1);
-}
+class HostTest : public testing::Test {};
 
 TEST(getLinuxHostCPUName, ARM) {
   StringRef CortexA9ProcCpuinfo = R"(
Index: llvm/lib/Support/Threading.cpp
===
--- llvm/lib/Support/Threading.cpp
+++ llvm/lib/Support/Threading.cpp
@@ -13,8 +13,12 @@
 
 #include "llvm/Support/Threading.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Config/config.h"
-#include "llvm/Support/Host.h"
+#include "llvm/Config/llvm-config.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/raw_ostream.h"
 
 #include 
 #include 
@@ -50,8 +54,8 @@
 int computeHostNumHardwareThreads();
 
 unsigned llvm::ThreadPoolStrategy::compute_thread_count() const {
-  int MaxThreadCount = UseHyperThreads ? computeHostNumHardwareThreads()
-   : sys::getHostNumPhysicalCores();
+  int MaxThreadCount =
+  UseHyperThreads ? computeHostNumHardwareThreads() : get_physical_cores();
   if (MaxThreadCount <= 0)
 MaxThreadCount = 1;
   if (ThreadsRequested == 0)
@@ -106,3 +110,123 @@
   S.ThreadsRequested = V;
   return S;
 }
+
+#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
+// On Linux, the number of physical cores can be computed from /proc/cpuinfo,
+// using the number

[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

2022-11-11 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 474751.
hokein marked an inline comment as done.
hokein added a comment.

use FileEntry in the API.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/CMakeLists.txt
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -0,0 +1,66 @@
+//===- unittest/Tooling/HeaderAnalysisTest.cpp ===//
+//
+// 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
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Testing/TestAST.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+TEST(HeaderAnalysisTest, IsSelfContained) {
+  TestInputs Inputs;
+  Inputs.Code = R"cpp(
+  #include "headerguard.h"
+  #include "pragmaonce.h"
+  #import "imported.h"
+
+  #include "bad.h"
+  #include "unguarded.h"
+  )cpp";
+
+  Inputs.ExtraFiles["headerguard.h"] = R"cpp(
+  #ifndef HEADER_H
+  #define HEADER_H
+
+  #endif HEADER_H
+  )cpp";
+  Inputs.ExtraFiles["pragmaonce.h"] = R"cpp(
+  #pragma once
+  )cpp";
+  Inputs.ExtraFiles["imported.h"] = "";
+
+  Inputs.ExtraFiles["unguarded.h"] = "";
+  Inputs.ExtraFiles["bad.h"] = R"cpp(
+  #pragma once
+
+  #if defined(INSIDE_H)
+  #error "Only ... can be included directly"
+  #endif
+  )cpp";
+
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+  auto &FM = SM.getFileManager();
+  auto &HI = AST.preprocessor().getHeaderSearchInfo();
+  auto getFileID = [&](llvm::StringRef FileName) {
+return SM.translateFile(FM.getFile(FileName).get());
+  };
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("headerguard.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("pragmaonce.h"), SM, HI));
+  EXPECT_TRUE(isSelfContainedHeader(getFileID("imported.h"), SM, HI));
+
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("unguarded.h"), SM, HI));
+  EXPECT_FALSE(isSelfContainedHeader(getFileID("bad.h"), SM, HI));
+}
+
+} // namespace
+} // namespace tooling
+} // namespace clang
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -16,6 +16,7 @@
   DiagnosticsYamlTest.cpp
   ExecutionTest.cpp
   FixItTest.cpp
+  HeaderAnalysisTest.cpp
   HeaderIncludesTest.cpp
   StandardLibraryTest.cpp
   LexicallyOrderedRecursiveASTVisitorTest.cpp
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -0,0 +1,67 @@
+//===--- HeaderAnalysis.cpp -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/HeaderSearch.h"
+
+namespace clang::tooling {
+namespace {
+
+// Is Line an #if or #ifdef directive?
+// FIXME: This makes headers with #ifdef LINUX/WINDOWS/MACOS marked as non
+// self-contained and is probably not what we want.
+bool isIf(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  return Line.startswith("if");
+}
+
+// Is Line an #error directive mentioning includes?
+bool isErrorAboutInclude(llvm::StringRef Line) {
+  Line = Line.ltrim();
+  if (!Line.consume_front("#"))
+return false;
+  Line = Line.ltrim();
+  if (!Line.startswith("error"))
+return false;
+  return Line.contains_insensitive(
+  "includ"); // Matches "include" or "including".
+}
+
+// Heuristically headers that only want to be included via an umbrella.
+bool isDontIncludeMeHeader(llvm::MemoryBufferRef Buffer) {
+  StringRef Content = Buffer.getBuffer();
+  llvm::StringRef Line;
+  // Only sniff up to 100 lines or 10KB.
+  Content = Content.take_front(100

[PATCH] D137839: [Sema] check InitListExpr format strings like {"foo"}

2022-11-11 Thread Yingchi Long via Phabricator via cfe-commits
inclyc created this revision.
Herald added a project: All.
inclyc added a reviewer: aaron.ballman.
inclyc published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Adds InitListExpr case in format string checks.

e.g.

  int sprintf(char *__restrict, const char * __restrict, ...);
  
  int foo()
  {
  char data[100];
  constexpr const char* fmt2{"%d"};  // no-warning
  sprintf(data, fmt2, 123);
  }

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137839

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/SemaCXX/format-strings.cpp


Index: clang/test/SemaCXX/format-strings.cpp
===
--- clang/test/SemaCXX/format-strings.cpp
+++ clang/test/SemaCXX/format-strings.cpp
@@ -203,6 +203,9 @@
   printf(string_linebreak(), 1, 2, 3, 4); // expected-warning {{format 
specifies type 'char *' but the argument has type 'int'}}
   printf(not_literal(), 1, 2, 3, 4); // expected-warning {{format string is 
not a string literal}}
   printf(wrap_constexpr(), 1, 2); // expected-warning {{format specifies type 
'char *' but the argument has type 'int'}}
+
+  constexpr const char *fmt {"%d%d"};
+  printf(fmt, 1, 1); // no-warning
 }
 
 
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -8554,6 +8554,15 @@
 return SLCT_UncheckedLiteral;
 
   switch (E->getStmtClass()) {
+  case Stmt::InitListExprClass:
+// Handle expressions like {"foobar"}.
+if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
+  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
+   Type, CallType, /*InFunctionCall*/ false,
+   CheckedVarArgs, UncoveredArg, Offset,
+   IgnoreStringsWithoutSpecifiers);
+}
+return SLCT_NotALiteral;
   case Stmt::BinaryConditionalOperatorClass:
   case Stmt::ConditionalOperatorClass: {
 // The expression is a literal if both sub-expressions were, and it was


Index: clang/test/SemaCXX/format-strings.cpp
===
--- clang/test/SemaCXX/format-strings.cpp
+++ clang/test/SemaCXX/format-strings.cpp
@@ -203,6 +203,9 @@
   printf(string_linebreak(), 1, 2, 3, 4); // expected-warning {{format specifies type 'char *' but the argument has type 'int'}}
   printf(not_literal(), 1, 2, 3, 4); // expected-warning {{format string is not a string literal}}
   printf(wrap_constexpr(), 1, 2); // expected-warning {{format specifies type 'char *' but the argument has type 'int'}}
+
+  constexpr const char *fmt {"%d%d"};
+  printf(fmt, 1, 1); // no-warning
 }
 
 
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -8554,6 +8554,15 @@
 return SLCT_UncheckedLiteral;
 
   switch (E->getStmtClass()) {
+  case Stmt::InitListExprClass:
+// Handle expressions like {"foobar"}.
+if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
+  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
+   Type, CallType, /*InFunctionCall*/ false,
+   CheckedVarArgs, UncoveredArg, Offset,
+   IgnoreStringsWithoutSpecifiers);
+}
+return SLCT_NotALiteral;
   case Stmt::BinaryConditionalOperatorClass:
   case Stmt::ConditionalOperatorClass: {
 // The expression is a literal if both sub-expressions were, and it was
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

2022-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.
Herald added a subscriber: Michael137.

Apologies to everyone who has automatically been marked as a reviewer for this 
change. There is more context for it here: 
https://discourse.llvm.org/t/targetparser-auto-generation-of-riscv-cpu-definitions/66419/4?u=lenary


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137838

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

2022-11-11 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/D137697/new/

https://reviews.llvm.org/D137697

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-11 Thread Aaron Ballman via cfe-commits
On Thu, Nov 10, 2022 at 4:05 PM Paul Eggert  wrote:
>
> On 2022-11-10 10:19, Aaron Ballman wrote:
> > In terms of the Clang side of things, I don't think we've formed any
> > sort of official stance on how to handle that yet. It's UB (you can
> > declare the C standard library interface without UB but calling any
> > function with a mismatched signature is UB)
>
> The Autoconf-generated code is never executed, so this is not a runtime
> issue; it's merely an issue of undefined behavior during translation.

FWIW, the only thing the (Clang) compiler is aware of is translation.
So from the frontend perspective, we can't tell the difference between
"trust me this is safe because it never gets executed" and "this is a
CVE". We believe the runtime behavior is sufficiently dangerous to
warrant a conservative view that any call to a function will be a call
that gets executed at runtime, hence a definitive signature mismatch
is something we feel comfortable diagnosing (in some form) by default.

> A
> problem could occur with a picky compiler or linker that rejects modules
> with mismatched function type declarations. Does Clang do that, or
> require or use such a linker? If not, there's no practical problem here.
> If so, it'd be helpful if Clang continued to support its traditional
> behavior that doesn't reject Autoconf's test cases, and for this to be
> the default.

Clang doesn't require such a linker (we work with various system linkers).

> Autoconf arose because one cannot ask something like "Can I call the
> renameat2 function with its usual signature?" in standard C code and one
> must escape into something like the shell to handle such questions. C23
> and GCC and Clang have added a few features to answer such questions,
> such as __has_include. But these features don't go nearly far enough.
> For example, __has_include tells me only whether the include file
>  exists; it won't tell me whether I can successfully include
> , or whether  will declare the function 'bar', or whether
> 'bar' will have a signature compatible with my code's calls to 'bar'.
>
> If I could request a single thing from the C23/GCC/Clang side, I'd ask
> for better facilities to be able to ask such questions within C code,
> without using the shell. Then a good chunk of Autoconf could dry up and
> blow away.
>
> I realize that I'm asking for a lot. For example, a traditional
> implementation cannot answer the renameat2 question without consulting
> the linker. That being said, this ability is essential for modular
> programming at the low level, and if compilers don't provide this
> ability Autoconf will simply have to do the best it can, regardless of
> whether it generates source code that relies on undefined behavior.

This would be challenging for an implementation like Clang where we
work with an arbitrary C runtime library (which may be dynamically
loaded on the target machine) and an arbitrary linker.

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


[PATCH] D137516: [TargetSupport] Move TargetParser API in a separate LLVM component.

2022-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.

In D137516#3912900 , @fpetrogalli 
wrote:

> In D137516#3912842 , @lenary wrote:
>
>> In D137516#3912751 , @fpetrogalli 
>> wrote:
>>
>>> @arsenm @frasercrmck @lenary - thank you for the feedback
>>>
>>> 1. The library could host anything that needs to be auto-generated with 
>>> tablegen. If we add `MVT`s, the name `TargetSupport` becomes obsolete.
>>
>> I am in favour of splitting parts of Support that could be table-gen'd out 
>> of Support, and into supplemental libraries.
>
> +1
>
>>> 2. Therefore we could use a name like `AutoGenSupport` (or similar, I am 
>>> open to suggestions).
>>
>> I actually think this is an awful name, even worse than "Support". One of 
>> the big issues with "Support" is that it's a junk-drawer that anyone throws 
>> stuff in when they need it anywhere in LLVM, when their layering questions 
>> become more difficult. This then becomes very hard to undo, because 
>> everything at this layer depends on everything else. "AutoGenSupport" to me 
>> says "we now have two bits, the junk drawer, and the junk drawer that's auto 
>> generated" and so I feel this is is worse, as you cannot differentiate which 
>> you need based on what you're doing.
>>
>> I think we need to name things after what they're for, not how they're made.
>
> Agree.
>
>>> 3. @lenary is saying that components like `Support/Host` needs to be moved 
>>> together with the AArch64/ARM bits of the target parser. Do people see an 
>>> issue if we add files that do not need auto-generated content in a library 
>>> called `AutoGenSupport`?
>>
>> The reason I'm in favour of "TargetParser" is because we already call the 
>> classes and related files "target parsers", and most of them contain 
>> target-related parsers. I don't know why this is a bad name.
>
> I'd be very happy to use the name `TargetParser`. I initially used that 
> because I knew that moving the RSCV bits of it meant  we needed to move the 
> other parsers too, together with `Support/Host`. Therefore I was trying to 
> create a name that would have covered for both the target parser any other 
> pieces that would have been moved in it. However...
>
>> Edited to add: Once I've split out Support/Host, I'm likely to give it a 
>> less generic name, something like "HostDetection", which is more clearly 
>> what it is doing.
>
> ... you seem to imply that you want to create a second component that is 
> independent of `[TargetParser|TargetSUpport]`. If that's the case, I am even 
> more convinced that `TargetParser` is the best name for the component 
> introduced in this patch.

The patch that outlines my proposal for TargetParser is here: 
https://reviews.llvm.org/D137838 (it has dependent patches). I also added a 
comment to your RFC thread explaining the dependent patches.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137516

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


[PATCH] D137578: Fix 'unsafe-math-optimizations' flag dependencies

2022-11-11 Thread Zahira Ammarguellat 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 rG91628f0616ca: The handling of 
'funsafe-math-optimizations' doesn't update the 
'MathErrno' (authored by zahiraam).

Changed prior to commit:
  https://reviews.llvm.org/D137578?vs=474515&id=474762#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137578

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGenOpenCL/relaxed-fpmath.cl
  clang/test/Driver/fp-contract.c

Index: clang/test/Driver/fp-contract.c
===
--- clang/test/Driver/fp-contract.c
+++ clang/test/Driver/fp-contract.c
@@ -1,6 +1,8 @@
 // Test that -ffp-contract is set to the right value when combined with
-// the options -ffast-math and -fno-fast-math.
+// the options -ffast-math, -fno-fast-math, funsafe-math-optimizations,
+// fno-unsafe-math-optimizations.
 
+// ffast-math, fno-fast-math
 // RUN: %clang -### -ffast-math -c %s 2>&1  \
 // RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
 // CHECK-FPC-FAST: "-ffp-contract=fast"
@@ -112,3 +114,123 @@
 // RUN: %clang -### -fno-fast-math -ffast-math -ffp-contract=off \
 // RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-OFF %s
 
+// funsafe-math-optimizations, fno-unsafe-math-optimizations
+// RUN: %clang -### -funsafe-math-optimizations -c %s 2>&1  \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -ffp-contract=fast -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=on -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=off -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -ffp-contract=fast -fno-unsafe-math-optimizations -c \
+// RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=on -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+// RUN: %clang -### -ffp-contract=off -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast \
+// RUN: -ffp-contract=on -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -ffp-contract=off -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -ffp-contract=on -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -ffp-contract=fast \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -fno-unsafe-math-optimizations \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -funsafe-math-optimizations \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s

[clang] 91628f0 - The handling of 'funsafe-math-optimizations' doesn't update the 'MathErrno'

2022-11-11 Thread Zahira Ammarguellat via cfe-commits

Author: Zahira Ammarguellat
Date: 2022-11-11T10:24:12-05:00
New Revision: 91628f0616ca5203945afb56b3d8a27522b99808

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

LOG: The handling of 'funsafe-math-optimizations' doesn't update the 'MathErrno'
flag. But the driver checks for 'fno-math-errno' before passing
'funsafe-math-optimizations' to the FE. In GCC, the option
'funsafe-math-optimizations' doesn't affect the 'fmath-errno' flag.
This patch aligns clang with GCC.

'-ffast-math' sets the FPContract to 'fast'. But 'funsafe-math-optimizations'
the driver doesn't consider the FPContract when handling the option.
Unfortunately there are places in the BE that interpret unsafe math
mode as allowing FMA. This patch makes -ffast-math' and
'funsafe-math-optimizations' behave similarly in regard to the setting of the
FPContract.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/CodeGenOpenCL/relaxed-fpmath.cl
clang/test/Driver/fp-contract.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 06336189d870..217a277b1f2d 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2787,7 +2787,7 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   // If one wasn't given by the user, don't pass it here.
   StringRef FPContract;
   StringRef LastSeenFfpContractOption;
-  bool SeenFfastMathOption = false;
+  bool SeenUnsafeMathModeOption = false;
   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
   !JA.isOffloading(Action::OFK_HIP))
 FPContract = "on";
@@ -3003,6 +3003,8 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   ApproxFunc = true;
   TrappingMath = false;
   FPExceptionBehavior = "";
+  FPContract = "fast";
+  SeenUnsafeMathModeOption = true;
   break;
 case options::OPT_fno_unsafe_math_optimizations:
   AssociativeMath = false;
@@ -3015,6 +3017,13 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   // The target may have opted to flush by default, so force IEEE.
   DenormalFPMath = llvm::DenormalMode::getIEEE();
   DenormalFP32Math = llvm::DenormalMode::getIEEE();
+  if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
+  !JA.isOffloading(Action::OFK_HIP)) {
+if (LastSeenFfpContractOption != "") {
+  FPContract = LastSeenFfpContractOption;
+} else if (SeenUnsafeMathModeOption)
+  FPContract = "on";
+  }
   break;
 
 case options::OPT_Ofast:
@@ -3034,7 +3043,7 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   RoundingFPMath = false;
   // If fast-math is set then set the fp-contract mode to fast.
   FPContract = "fast";
-  SeenFfastMathOption = true;
+  SeenUnsafeMathModeOption = true;
   break;
 case options::OPT_fno_fast_math:
   HonorINFs = true;
@@ -3054,7 +3063,7 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   !JA.isOffloading(Action::OFK_HIP)) {
 if (LastSeenFfpContractOption != "") {
   FPContract = LastSeenFfpContractOption;
-} else if (SeenFfastMathOption)
+} else if (SeenUnsafeMathModeOption)
   FPContract = "on";
   }
   break;
@@ -3095,8 +3104,8 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
   if (MathErrno)
 CmdArgs.push_back("-fmath-errno");
 
-  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
-  ApproxFunc && !TrappingMath)
+ if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
+ !TrappingMath)
 CmdArgs.push_back("-funsafe-math-optimizations");
 
   if (!SignedZeros)

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 088e83b148ac..40d556fb931f 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3799,7 +3799,7 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
 else
   Opts.LongDoubleSize = 0;
   }
-  if (Opts.FastRelaxedMath)
+  if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
 
   llvm::sort(Opts.ModuleFeatures);

diff  --git a/clang/test/CodeGenOpenCL/relaxed-fpmath.cl 
b/clang/test/CodeGenOpenCL/relaxed-fpmath.cl
index 69cfd82d2d71..2751caa97307 100644
--- a/clang/test/CodeGenOpenCL/relaxed-fpmath.cl
+++ b/clang/test/CodeGenOpenCL/relaxed-fpmath.cl
@@ -22,7 +22,7 @@ float spscalardiv(float a, floa

[PATCH] D127855: [OpenMP] Basic parse and sema support for modifiers in order clause

2022-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


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

https://reviews.llvm.org/D127855

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


[PATCH] D137787: [CodeGen] Relax assertion on generating destructor call

2022-11-11 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

I've trimmed the failing code down to

  #include 
  #include 
  #include 
  
  template 
  struct SO {
void a() {
  struct SI {
std::vector v;
  };
  SI s;
  SI m(std::move(s));
}
  
void g() {
  std::vector v{"a"};
}
  };

in a header / module and

  SO s;
  s.a();
  s.g();

in the calling code. Sadly this works fine in standalone Clang...

All of the above code seems to be important, starting from the outer 
`template`, having two functions, moving a `std::vector` from a default 
generated move constructor and then constructing a 
`std::vector` with at least one element. If this rings a bell 
for anybody or anybody has an idea where to go from here, please let me know. 
I'm out of depth how to produce the exact failing conditions in a test. I would 
argue that relaxing the `assert` is fine regardless because it still tests that 
the `DtorDecl` belongs to this type, but I can't articulate why an exact 
pointer comparison fails in very rare circumstances...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137787

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


[PATCH] D137244: [Clang] Correctly capture bindings in dependent lambdas.

2022-11-11 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 474770.
cor3ntin added a comment.

Address Shafik's comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137244

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/SemaLambda.h
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/ScopeInfo.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/SemaCXX/cxx20-decomposition.cpp

Index: clang/test/SemaCXX/cxx20-decomposition.cpp
===
--- clang/test/SemaCXX/cxx20-decomposition.cpp
+++ clang/test/SemaCXX/cxx20-decomposition.cpp
@@ -1,5 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
-// expected-no-diagnostics
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify -Wunused-variable %s
 
 template 
 constexpr bool is_same = false;
@@ -80,10 +79,21 @@
 namespace std {
 
 template 
-struct tuple_size {
+struct tuple_size;
+
+template 
+struct tuple_size : tuple_size{};
+
+template 
+requires requires { tuple_size::value; }
+struct tuple_size : tuple_size{};
+
+template <>
+struct tuple_size {
   static constexpr unsigned long value = 2;
 };
 
+
 template 
 struct tuple_element;
 
@@ -139,3 +149,37 @@
 };
   }
 }
+
+namespace ODRUseTests {
+  struct P { int a; int b; };
+  void GH57826() {
+const auto [a, b] = P{1, 2}; //expected-note 2{{'b' declared here}} \
+ //expected-note 3{{'a' declared here}}
+(void)[&](auto c) { return b + [&a] {
+return a;
+}() ; }(0);
+(void)[&](auto c) { return b + [&a](auto) {
+return a;
+}(0) ; }(0);
+(void)[=](auto c) { return b + [&a](auto) {
+return a;
+}(0) ; }(0);
+(void)[&a,&b](auto c) { return b + [&a](auto) {
+return a;
+}(0) ; }(0);
+(void)[&a,&b](auto c) { return b + [a](auto) {
+return a;
+}(0) ; }(0);
+(void)[&a](auto c) { return b + [&a](auto) { // expected-error 2{{variable 'b' cannot be implicitly captured}} \
+ // expected-note 2{{lambda expression begins here}} \
+ // expected-note 4{{capture 'b'}}
+return a;
+}(0) ; }(0); // expected-note {{in instantiation}}
+(void)[&b](auto c) { return b + [](auto) {   // expected-note 3{{lambda expression begins here}} \
+ // expected-note 6{{capture 'a'}} \
+ // expected-note 6{{default capture}} \
+ // expected-note {{in instantiation}}
+return a;  // expected-error 3{{variable 'a' cannot be implicitly captured}}
+}(0) ; }(0); // expected-note 2{{in instantiation}}
+  }
+}
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -13323,9 +13323,8 @@
 }
 
 // Transform the captured variable.
-VarDecl *CapturedVar
-  = cast_or_null(getDerived().TransformDecl(C->getLocation(),
- C->getCapturedVar()));
+ValueDecl *CapturedVar = cast_or_null(
+getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
   Invalid = true;
   continue;
Index: clang/lib/Sema/SemaLambda.cpp
===
--- clang/lib/Sema/SemaLambda.cpp
+++ clang/lib/Sema/SemaLambda.cpp
@@ -62,7 +62,7 @@
 static inline Optional
 getStackIndexOfNearestEnclosingCaptureReadyLambda(
 ArrayRef FunctionScopes,
-VarDecl *VarToCapture) {
+ValueDecl *VarToCapture) {
   // Label failure to capture.
   const Optional NoLambdaIsCaptureReady;
 
@@ -172,7 +172,7 @@
 
 Optional clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
 ArrayRef FunctionScopes,
-VarDecl *VarToCapture, Sema &S) {
+ValueDecl *VarToCapture, Sema &S) {
 
   const Optional NoLambdaIsCaptureCapable;
 
@@ -1231,11 +1231,7 @@
 if (Var->isInvalidDecl())
   continue;
 
-VarDecl *Underlying;
-if (auto *BD = dyn_cast(Var))
-  Underlying = dyn_cast(BD->getDecomposedDecl());
-else
-  Underlying = cast(Var);
+VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
 
 if (!Underlying->hasLocalStorage()) {
   Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -8223,7 +8223,7 @@
   // All the potenti

[PATCH] D137724: [CMake] Warn when the version is older than 3.20.0.

2022-11-11 Thread Guillot Tony via Phabricator via cfe-commits
to268 accepted this revision.
to268 added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137724

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


[PATCH] D137835: [ARM] Move ARM::parseBranchProtection into ARMTargetParser

2022-11-11 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson accepted this revision.
tmatheson added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:47
 #include "llvm/Option/ArgList.h"
+#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/CodeGen.h"

For consistency this could just come via ARM.h


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137835

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


[PATCH] D137836: [Support] Move getHostNumPhysicalCores to Threading.h

2022-11-11 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson added a comment.

Makes sense since it is so similar to `get_cpus()` and is only used in 
Threading.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137836

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


[PATCH] D137350: [RISCV] Implement assembler support for XVentanaCondOps

2022-11-11 Thread Philip Reames via Phabricator via cfe-commits
reames updated this revision to Diff 474782.
reames added a comment.

Address comments from @craig.topper


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

https://reviews.llvm.org/D137350

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/lib/Target/RISCV/RISCVInstrInfoXVentana.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/XVentanaCondOps-valid.s

Index: llvm/test/MC/RISCV/XVentanaCondOps-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/XVentanaCondOps-valid.s
@@ -0,0 +1,22 @@
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+xventanacondops -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+xventanacondops < %s \
+# RUN: | llvm-objdump --mattr=+xventanacondops -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+
+# CHECK-ASM-AND-OBJ: vt.maskc zero, zero, zero
+# CHECK-ASM: encoding: [0x7b,0x60,0x00,0x00]
+vt.maskc x0, x0, x0
+
+# CHECK-ASM-AND-OBJ: vt.maskcn zero, zero, zero
+# CHECK-ASM: encoding: [0x7b,0x70,0x00,0x00]
+vt.maskcn x0, x0, x0
+
+# CHECK-ASM-AND-OBJ: vt.maskc ra, sp, gp
+# CHECK-ASM: encoding: [0xfb,0x60,0x31,0x00]
+vt.maskc x1, x2, x3
+
+# CHECK-ASM-AND-OBJ: vt.maskcn ra, sp, gp
+# CHECK-ASM: encoding: [0xfb,0x70,0x31,0x00]
+vt.maskcn x1, x2, x3
+
Index: llvm/test/CodeGen/RISCV/attributes.ll
===
--- llvm/test/CodeGen/RISCV/attributes.ll
+++ llvm/test/CodeGen/RISCV/attributes.ll
@@ -76,6 +76,7 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+zicbop %s -o - | FileCheck --check-prefix=RV64ZICBOP %s
 ; RUN: llc -mtriple=riscv64 -mattr=+svnapot %s -o - | FileCheck --check-prefix=RV64SVNAPOT %s
 ; RUN: llc -mtriple=riscv64 -mattr=+svinval %s -o - | FileCheck --check-prefix=RV64SVINVAL %s
+; RUN: llc -mtriple=riscv64 -mattr=+xventanacondops %s -o - | FileCheck --check-prefix=RV64XVENTANACONDOPS %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zawrs %s -o - | FileCheck --check-prefix=RV64ZAWRS %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-ztso %s -o - | FileCheck --check-prefix=RV64ZTSO %s
 
@@ -157,6 +158,7 @@
 ; RV64ZICBOP: .attribute 5, "rv64i2p0_zicbop1p0"
 ; RV64SVNAPOT: .attribute 5, "rv64i2p0_svnapot1p0"
 ; RV64SVINVAL: .attribute 5, "rv64i2p0_svinval1p0"
+; RV64XVENTANACONDOPS: .attribute 5, "rv64i2p0_xventanacondops1p0"
 ; RV64ZTSO: .attribute 5, "rv64i2p0_ztso0p1"
 
 define i32 @addi(i32 %a) {
Index: llvm/lib/Target/RISCV/RISCVSubtarget.h
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.h
+++ llvm/lib/Target/RISCV/RISCVSubtarget.h
@@ -90,6 +90,7 @@
   bool HasStdExtZmmul = false;
   bool HasStdExtZawrs = false;
   bool HasStdExtZtso = false;
+  bool HasVendorXVentanaCondOps = false;
   bool HasRV32 = false;
   bool HasRV64 = false;
   bool IsRV32E = false;
@@ -189,6 +190,7 @@
   bool hasStdExtZawrs() const { return HasStdExtZawrs; }
   bool hasStdExtZmmul() const { return HasStdExtZmmul; }
   bool hasStdExtZtso() const { return HasStdExtZtso; }
+  bool hasVendorXVentanaCondOps() const { return HasVendorXVentanaCondOps; }
   bool is64Bit() const { return HasRV64; }
   bool isRV32E() const { return IsRV32E; }
   bool enableLinkerRelax() const { return EnableLinkerRelax; }
Index: llvm/lib/Target/RISCV/RISCVInstrInfoXVentana.td
===
--- /dev/null
+++ llvm/lib/Target/RISCV/RISCVInstrInfoXVentana.td
@@ -0,0 +1,29 @@
+//===-- RISCVInstrInfoXVentana.td --*- tablegen -*-===//
+//
+// 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 describes the vendor extensions defined by Ventana Micro Systems.
+//
+//===--===//
+
+//===--===//
+// XVentanaCondOps
+//===--===//
+
+let Predicates = [IsRV64, HasVendorXVentanaCondOps], hasSideEffects = 0,
+  mayLoad = 0, mayStore = 0, isCodeGenOnly = 0, DecoderNamespace = "Ventana" in
+class VTMaskedMove funct3, string opcodestr>
+: RVInstR<0b000, funct3, OPC_CUSTOM_3, (outs GPR:$rd),
+  (ins GPR:$rs1, GPR:$rs2), opcodestr,
+  "$rd, $rs1, $rs2"> {
+}
+
+def VT_MASKC : VTMaskedMove<0b110, "v

[PATCH] D137154: Adding nvvm_reflect clang builtin

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

In D137154#3918949 , @bader wrote:

> Is binary size a concern here? NVIDIA, AMD and Intel GPUs are already have ~ 
> 20 different architectures each, so I want my app/library to run on any GPU 
> from these vendors (which is quite reasonable expectation), I'll need to 
> have/distribute ~ 60 different binaries. libdevice, libm, libc are quite 
> small, but other apps (e.g. ML frameworks) might be quite large, so that 
> distributed binary size is important to consider.

Yes, this probably would become untenable with really large sizes. Compression 
is always an option considering that these would be highly similar, we'd just 
need some way to check if the data stored at the `LLVM_OFFLOADING` section is 
some compressed format and extract it to a new buffer before doing linking. A 
more esoteric option would be to make a tool that takes in the LLVM-IR 
generated for each architecture and tries to unify it, adding branches where 
they differ and guard these with some flags that make the machine translator 
ignore them. Generally I don't think that manually searching for compatibility 
is a good longterm solution for libraries so we could look into alternative 
means (it's required for executables however).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137154

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


[PATCH] D137823: [clang-format][NFC] Moved configuration parsing tests in own file

2022-11-11 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks marked an inline comment as done.
HazardyKnusperkeks added inline comments.



Comment at: clang/unittests/Format/ConfigParseTest.cpp:1
+//===- unittest/Format/ConfiParseTest.cpp - Config parsing unit tests 
-===//
+//

rymiel wrote:
> typo (Confi) :)
Will be correct on push.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137823

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


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

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

This is a gigantic diff. I'd recommend keeping the .h files in the old place 
for v0 and make them just forwarding headers that include the header at the new 
location. That way, you don't have to update oodles of include lines in this 
patch, and it makes it a bit easier to see what's going on. (You can then 
update all the include lines in a trivial follow-up if this change goes 
through, and then remove the forwarding headers in Support, to cut the 
dependency you want to remove.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137838

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


[PATCH] D137851: [OPENMP]Initial support for at clause

2022-11-11 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 created this revision.
jyu2 added reviewers: ABataev, mikerice, jdoerfert.
jyu2 added a project: OpenMP.
Herald added subscribers: arphaman, guansong, yaxunl.
Herald added a project: All.
jyu2 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

Initial support for at clause.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137851

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Basic/OpenMPKinds.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/error_ast_print.cpp
  clang/test/OpenMP/error_message.cpp
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -301,6 +301,9 @@
   let clangClass = "OMPAtomicDefaultMemOrderClause";
   let flangClass = "OmpAtomicDefaultMemOrderClause";
 }
+def OMPC_At : Clause<"at"> {
+  let clangClass = "OMPAtClause";
+}
 def OMPC_Allocate : Clause<"allocate"> {
   let clangClass = "OMPAllocateClause";
   let flangClass = "OmpAllocateClause";
@@ -527,7 +530,11 @@
 }
 def OMP_TaskYield : Directive<"taskyield"> {}
 def OMP_Barrier : Directive<"barrier"> {}
-def OMP_Error : Directive<"error"> {}
+def OMP_Error : Directive<"error"> {
+  let allowedClauses = [
+VersionedClause
+  ];
+}
 def OMP_TaskWait : Directive<"taskwait"> {
   let allowedClauses = [
 VersionedClause
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2443,6 +2443,8 @@
 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
 const OMPAtomicDefaultMemOrderClause *) {}
 
+void OMPClauseEnqueue::VisitOMPAtClause(const OMPAtClause *) {}
+
 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
   Visitor->AddStmt(C->getDevice());
 }
Index: clang/test/OpenMP/error_message.cpp
===
--- clang/test/OpenMP/error_message.cpp
+++ clang/test/OpenMP/error_message.cpp
@@ -7,19 +7,19 @@
   if (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 if (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
   while (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 while (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
   do
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 while (argc)
   ;
   do {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   } while (argc);
   switch (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
@@ -28,47 +28,75 @@
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
   switch (argc)
   case 1: {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   }
   switch (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   case 1:
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 break;
   default: {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   } break;
   }
   for (;;)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 for (;;) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
 label:
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 label1 : {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
 if (1)
   label2:
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 
+// expected-error@+1 {{ERROR}}
+#pragma omp error at() // expected-error {{expected 'compilation' or 'execution' in OpenMP clause 'at'}}
+
+// expected-error@+1 {{ERROR}}
+#pragma omp error at(up) // expected-error {{expected 'compilation' or 'execution' in OpenMP clause 'at'}}
+
+// expected-error@+3 {{ERROR}}
+// expected-error@+2 {{expected ')'}}
+// expected-note@+1 {{to match this '('}}
+#pragma omp error at(up(a)) // expected-error {{expected 'compilation' or 'execution' in OpenMP clause 'at'}}
+
+#pr

[PATCH] D135636: [clang][modules][deps] Serialize inputs into PCMs using the "as requested" name

2022-11-11 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:447
+SmallString<128> CanonicalPath = FE.getNameAsRequested();
+ModMapInfo.canonicalizeModuleMapPath(CanonicalPath);
+MD.ModuleMapFileDeps.emplace_back(CanonicalPath);

Was this canonicalization necessary? If this is needed can we do it in the 
implicit module build so that it is serialized with the correct path? That 
seems better for both stability of the implicit module build and avoids 
re-canonicalizing the path every time it is scanned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135636

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


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

2022-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.

In D137838#3921828 , @thakis wrote:

> This is a gigantic diff. I'd recommend keeping the .h files in the old place 
> for v0 and make them just forwarding headers that include the header at the 
> new location. That way, you don't have to update oodles of include lines in 
> this patch, and it makes it a bit easier to see what's going on. (You can 
> then update all the include lines in a trivial follow-up if this change goes 
> through, and then remove the forwarding headers in Support, to cut the 
> dependency you want to remove.)

Thanks for the suggestion. I do agree this patch is too big to land as-is. I 
think this patch is useful as "this shows the full effect of this change", even 
if we find ways to make how we land this patch less invasive. One other thought 
I had was to move the unittests first, but that doesn't make as big a 
difference as the fact that `llvm/ADT/Triple.h` is referenced everywhere.

I would like more comments (either here or on Discourse, link in a prior 
comment) on whether this split is reasonable before I post a v2 of this patch, 
though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137838

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


[PATCH] D137851: [OPENMP]Initial support for at clause

2022-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/AST/OpenMPClause.h:1613-1615
+  /// Sets the location of '('.
+  void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+

Make it private



Comment at: clang/include/clang/Parse/Parser.h:3296-3304
+  /// Parses clauses for directive.
+  ///
+  /// \param DKind Kind of current directive.
+  /// \param clauses for current directive.
+  /// \param start location for clauses of current directive
+  void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
+  SmallVector *Clauses,

Could you make it in a separate NFC patch?



Comment at: clang/lib/Sema/SemaOpenMP.cpp:11034-11037
+  for (const OMPClause *CNew : Clauses) {
+if (auto *AtCl = cast(CNew))
+  AtC = AtCl;
+  }

`find_first_of`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137851

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


[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

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



Comment at: clang/lib/Sema/SemaStmtAttr.cpp:319
+  };
+  // There are 7 categories of loop hints attributes: vectorize, interleave,
+  // unroll, unroll_and_jam, pipeline, distribute, and vectorize predicate.

Can you break up this comment, I think it should go above the enum and each one 
that is specific to an enumerator should go above that enumerator. 



Comment at: clang/lib/Sema/SemaStmtAttr.cpp:331-332
 const LoopHintAttr *NumericAttr;
-  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}};
+  } HintAttrs[CategoryType::NumberOfCategories];
+  memset(HintAttrs, 0, sizeof(HintAttrs));
 

You can use `{}` to initialize the array. This will value-initialize each 
element, which for pointers will set it to zero.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

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


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

2022-11-11 Thread Francesco Petrogalli via Phabricator via cfe-commits
fpetrogalli added a comment.

Hi @lenary  - thank you for working on this!

The patch is reasonable to me.

I agree on the suggestion of using forwarding headers or the first iteration of 
the change, it will make it easier to review.

I'll adapt the auto-get patch at D137517  on 
D137838 .

As for the name `TargetParser`. @arsenm came up with the name 
`SubtargetRegistry`. I am fine with either names.

Francesco


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137838

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


[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

2022-11-11 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I haven't dealt much with the loop hint attributes, but two of my coworkers 
have done extensive work in our downstream (@jyu2 and @mikerice), and likely 
have feedback about how this affects downstream feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

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


[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-11-11 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders added a comment.

This looks really cool :)




Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:133
+  std::string Directives;
+  for (auto &Using : UsingToAdd)
+Directives += llvm::formatv("using namespace {0};\n", Using);

nit: `const auto`



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:249
 
+  llvm::sort(UsingToAdd);
+  UsingToAdd.erase(std::unique(UsingToAdd.begin(), UsingToAdd.end()),

If you're sorting and removing duplicates in the end anyway, maybe [[ 
https://llvm.org/doxygen/classllvm_1_1StringSet.html | llvm::StringSet ]] would 
be a better fit instead of `vector`?



Comment at: 
clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp:286
+  using namespace ns1::ns2;
   int main() { 1.5_w; }
 )cpp"}};

Your code also handles cases where there are multiple inline namespaces 
involved, right? If so, it would be a good idea also test this here (i.e. add 
ns3 with another user-defined literal)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

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


[PATCH] D135128: [clang][cli] Simplify repetitive macro invocations

2022-11-11 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

@stella.stamenova Any updates?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135128

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


[clang] 33d848b - Fix typo; NFC

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

Author: Aaron Ballman
Date: 2022-11-11T13:02:41-05:00
New Revision: 33d848b992ee1d3a6b39b3b6f1a42b46d583bf72

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

LOG: Fix typo; NFC

Co-authored-by: Guillot Tony 

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 3b441e757fae8..40e1dd9cca5c1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5768,7 +5768,7 @@ by showing the control-flow statement where the path 
diverges.
 if (somePredicate()) {
   ...
   callback();
-} esle {
+} else {
   callback(); // OK: callback is called on every path
 }
   }



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


[PATCH] D102107: [OpenMP] Codegen aggregate for outlined function captures

2022-11-11 Thread Fabio Luporini via Phabricator via cfe-commits
FabioLuporini added a comment.

Hi, any chance this will be completed any time soon? We are very keen to 
resurrect our clang-based OpenMP offloading pipeline at 
https://github.com/devitocodes/devito :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102107

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


[PATCH] D102107: [OpenMP] Codegen aggregate for outlined function captures

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

@dhruvachak Do you still need help updating the LLVM tests?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102107

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


[PATCH] D137154: Adding nvvm_reflect clang builtin

2022-11-11 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

> Yes, this probably would become untenable with really large sizes.

I think that horse had left the barn long ago. Vast majority of NVIDIA GPU 
cycles these days spent in libraries shipped by NVIDIA and those are huge 
(O(1GB)), numerous (cuDNN, TensorRT, cuBLAS, cuSPARSE, cuFFT) and contain 
binaries for all major GPU variants NVIDIA supports (sm3x,5x,6x,7x,8x,9x). 
AMD's ROCm stack is comparable in size, too, I think.
Yes, it does cause issues when one links in everything statically. E.g. we 
sometimes end up causing overflows of 32-bit signed ELF relocations, but 
typically users do link with shared libraries and avoid that particular issue.

Distributing large binaries does end up being a challenge, mostly due to the 
storage and transfer costs. Tensorflow had been forced to split GPU support 
bits into a separate package and limit the set of the supported GPUs official 
packages are compiled for. I think we also considered per-GPU variant packages, 
but that would multiply storage costs.

However, most of the users and libraries are either nowhere near cuDNN/ROCm in 
terms of size and the size increase will likely be manageable, or already have 
to deal with the size issues and the size increase will be insignificant 
compared to existing size.
JIT would be another option, but it has its own challenges at that scale.

Overall I think there's enough existing use cases to consider compiling for 
all/most supported GPUs to be a practical solution, even for large projects. It 
does not mean it will work for everyone, but I think specifically for `libclc` 
compiling for all GPUs would be the right thing to do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137154

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


[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-11-11 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry updated this revision to Diff 474808.
v1nh1shungry added a comment.

Apply the review suggestions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

Files:
  clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
  clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
@@ -264,6 +264,39 @@
   }
   
   int main() { 1.5_w; }
+)cpp"},
+  {// Add using-directives for user-defined literals
+   // declared in an inline namespace
+   R"cpp(
+namespace ns1 {
+inline namespace ns2 {
+long double operator "" _w(long double);
+}
+inline namespace ns3 {
+long double operator "" _h(long double);
+}
+}
+using namespace n^s1;
+int main() {
+  1.5_h;
+  1.5_w;
+}
+)cpp",
+   R"cpp(
+namespace ns1 {
+inline namespace ns2 {
+long double operator "" _w(long double);
+}
+inline namespace ns3 {
+long double operator "" _h(long double);
+}
+}
+using namespace ns1::ns2;
+using namespace ns1::ns3;
+int main() {
+  1.5_h;
+  1.5_w;
+}
 )cpp"}};
   for (auto C : Cases)
 EXPECT_EQ(C.second, apply(C.first)) << C.first;
Index: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -54,6 +54,10 @@
   : TargetNS(Target.getNominatedNamespace()),
 TargetCtx(Target.getDeclContext()), Results(Results) {}
 
+  FindSameUsings(const NamespaceDecl *TargetNS, const DeclContext *TargetCtx,
+ std::vector &Results)
+  : TargetNS(TargetNS), TargetCtx(TargetCtx), Results(Results) {}
+
   bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
 if (D->getNominatedNamespace() != TargetNS ||
 D->getDeclContext() != TargetCtx)
@@ -101,6 +105,43 @@
   return D;
 }
 
+// If the user-defined literal is declared in an inline namespace,
+// we add a using-directive for it
+void handleUserDefinedLiteral(const DeclContext *D, const DeclContext *Ctx,
+  ASTContext &AST, llvm::StringSet<> &UsingToAdd) {
+  if (D->isInlineNamespace()) {
+const auto *ND = cast(D);
+// Find if there is already a wanted using-directive,
+// if there is, we are done. Otherwise we collect it
+std::vector AllDirectives;
+FindSameUsings(ND, Ctx, AllDirectives).TraverseAST(AST);
+if (AllDirectives.empty()) {
+  UsingToAdd.insert(ND->getQualifiedNameAsString());
+}
+  }
+}
+
+// Produce edit adding 'using namespace xxx::yyy;'
+// for user-defined literals declared in an inline namespace
+llvm::Optional
+addUsingDirectives(const llvm::StringSet<> &UsingToAdd, SourceManager &SM,
+   SourceLocation Loc) {
+  if (UsingToAdd.empty())
+return llvm::None;
+  // FIXME: We simply join all the using-directives with newline,
+  //so it can't handle indent. For now this is correct
+  //because the code action only runs on the using-directive
+  //declared in the top level
+  std::string Directives;
+  for (const auto &Using : UsingToAdd)
+Directives += llvm::formatv("using namespace {0};\n", Using.getKey());
+  // Remove the trailing newline
+  Directives.pop_back();
+  // For now we insert the using-directives to where the first using-directive
+  // to remove stands
+  return tooling::Replacement(SM, Loc, 0, Directives);
+}
+
 bool RemoveUsingNamespace::prepare(const Selection &Inputs) {
   // Find the 'using namespace' directive under the cursor.
   auto *CA = Inputs.ASTSelection.commonAncestor();
@@ -144,6 +185,9 @@
   // Collect all references to symbols from the namespace for which we're
   // removing the directive.
   std::vector IdentsToQualify;
+  // Collect all namespaces' name to add for user-defined literals declared
+  // in an inline namespace
+  llvm::StringSet<> UsingToAdd;
   for (auto &D : Inputs.AST->getLocalTopLevelDecls()) {
 findExplicitReferences(
 D,
@@ -164,15 +208,19 @@
 // Avoid adding qualifiers before user-defined literals, e.g.
 //   using namespace std;
 //   auto s = "foo"s; // Must not changed to auto s = "foo" std::s;
-// FIXME: Add a using-directive for user-defined literals
+// And add a using-directive for user-defined literals
 // declared in an inline namespace, e.g.
 //   using namespace s^td;
 //   int main() { cout << "foo"s; }
 // change to
-//   using namespace std::literals;
+//   us

[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-11-11 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry added a comment.

@tom-anders Thank you for reviewing and giving suggestions!

Hope I use the `llvm::StringSet` correctly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

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


[PATCH] D137714: Do not merge traps in functions annotated optnone

2022-11-11 Thread Henrik G Olsson via Phabricator via cfe-commits
hnrklssn updated this revision to Diff 474811.
hnrklssn added a comment.

No longer reorders annotations to occur before codegen. Instead EmitTrapCheck 
checks the function declaration for OptimizeNoneAttr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137714

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGen/ubsan-trap-debugloc.c


Index: clang/test/CodeGen/ubsan-trap-debugloc.c
===
--- clang/test/CodeGen/ubsan-trap-debugloc.c
+++ clang/test/CodeGen/ubsan-trap-debugloc.c
@@ -7,4 +7,16 @@
   a = a + 1;
 }
 
+void bar(volatile int a) __attribute__((optnone)) {
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC2:![0-9]+]]
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC3:![0-9]+]]
+  a = a + 1;
+  a = a + 1;
+}
+
+// With optimisations enabled the traps are merged and need to share a debug 
location
 // CHECK: [[LOC]] = !DILocation(line: 0
+
+// With optimisations disabled the traps are not merged and retain accurate 
debug locations
+// CHECK: [[LOC2]] = !DILocation(line: 13, column: 9
+// CHECK: [[LOC3]] = !DILocation(line: 14, column: 9
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -3545,7 +3545,8 @@
 TrapBBs.resize(CheckHandlerID + 1);
   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
 
-  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
+  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
+  (CurCodeDecl && CurCodeDecl->hasAttr())) {
 TrapBB = createBasicBlock("trap");
 Builder.CreateCondBr(Checked, Cont, TrapBB);
 EmitBlock(TrapBB);


Index: clang/test/CodeGen/ubsan-trap-debugloc.c
===
--- clang/test/CodeGen/ubsan-trap-debugloc.c
+++ clang/test/CodeGen/ubsan-trap-debugloc.c
@@ -7,4 +7,16 @@
   a = a + 1;
 }
 
+void bar(volatile int a) __attribute__((optnone)) {
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC2:![0-9]+]]
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC3:![0-9]+]]
+  a = a + 1;
+  a = a + 1;
+}
+
+// With optimisations enabled the traps are merged and need to share a debug location
 // CHECK: [[LOC]] = !DILocation(line: 0
+
+// With optimisations disabled the traps are not merged and retain accurate debug locations
+// CHECK: [[LOC2]] = !DILocation(line: 13, column: 9
+// CHECK: [[LOC3]] = !DILocation(line: 14, column: 9
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -3545,7 +3545,8 @@
 TrapBBs.resize(CheckHandlerID + 1);
   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
 
-  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
+  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
+  (CurCodeDecl && CurCodeDecl->hasAttr())) {
 TrapBB = createBasicBlock("trap");
 Builder.CreateCondBr(Checked, Cont, TrapBB);
 EmitBlock(TrapBB);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137714: Do not merge traps in functions annotated optnone

2022-11-11 Thread Henrik G Olsson via Phabricator via cfe-commits
hnrklssn marked 2 inline comments as done.
hnrklssn added a comment.

Made changes in line with what @fcloutier suggested.




Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5321
 
+  SetLLVMFunctionAttributesForDefinition(D, Fn);
   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);

fcloutier wrote:
> hnrklssn wrote:
> > delcypher wrote:
> > > I'm a little worried about this ordering change here. Could this have 
> > > some unintended consequences?
> > Yeah I was also a bit worried about that when making the change, since the 
> > functions are both quite broad and I'm not familiar with them from before. 
> > However it doesn't break any test cases, so I'm not sure what the 
> > consequences would be exactly.
> > 
> > For reference, also moving the call to setNonAliasAttributes so that it is 
> > still before the call to SetLLVMFunctionAttributesForDefinition breaks a 
> > ton of test cases so I'm somewhat hopeful that we have good test coverage 
> > for this type of change.
> Could you get it from `CurCodeDecl->hasAttr()` in CGExpr 
> instead? Then you wouldn't have to change this.
> 
> Caveat: am not sure that `CurCodeDecl` is always set. For instance, do you 
> have a `CurCodeDecl` when you generate a C++ static initializer? On the 
> upside, if it's NULL, you can just bail out.
Indeed that approach works as well. There are some test cases that result in 
CurCodeDecl being NULL, like you suspected.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137714

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


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

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

Moving target-specific parsers outside LLVMSupport LGTM. I even objected a bit 
when more stuff of this kind was introduced into LLVMSupport.

+1 for adding temporary forwarding headers for now to avoid update all 
`#include` users.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137838

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


[PATCH] D137762: [clang-format] avoid breaking )( with BlockIndent

2022-11-11 Thread Gedare Bloom via Phabricator via cfe-commits
gedare updated this revision to Diff 474812.
gedare added a comment.

Run tests and fix bad breaks. Fix comment style.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137762

Files:
  clang/lib/Format/TokenAnnotator.cpp


Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -5001,10 +5001,13 @@
   return false;
 }
 const FormatToken *Previous = Right.MatchingParen->Previous;
-// Avoid breaking when there is an opening parens immediately following
+// Avoid breaking when there is another parens immediately following
 // a closing parens, such as in cast operators and indirect function calls.
 return !((Previous && (Previous->is(tok::kw_for) || Previous->isIf())) ||
- (Right.Next && Right.Next->isOneOf(tok::l_paren, tok::r_paren)));
+ (Right.Next &&
+  (Right.Next->is(tok::l_paren) ||
+   (Right.Next->is(tok::r_paren) &&
+(Right.NestingLevel == 0 || Previous->is(tok::star));
   }
 
   // Allow breaking after a trailing annotation, e.g. after a method


Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -5001,10 +5001,13 @@
   return false;
 }
 const FormatToken *Previous = Right.MatchingParen->Previous;
-// Avoid breaking when there is an opening parens immediately following
+// Avoid breaking when there is another parens immediately following
 // a closing parens, such as in cast operators and indirect function calls.
 return !((Previous && (Previous->is(tok::kw_for) || Previous->isIf())) ||
- (Right.Next && Right.Next->isOneOf(tok::l_paren, tok::r_paren)));
+ (Right.Next &&
+  (Right.Next->is(tok::l_paren) ||
+   (Right.Next->is(tok::r_paren) &&
+(Right.NestingLevel == 0 || Previous->is(tok::star));
   }
 
   // Allow breaking after a trailing annotation, e.g. after a method
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137762: [clang-format] avoid breaking )( with BlockIndent

2022-11-11 Thread Gedare Bloom via Phabricator via cfe-commits
gedare updated this revision to Diff 474814.
gedare added a comment.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137762

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/TokenAnnotator.cpp


Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -5001,7 +5001,13 @@
   return false;
 }
 const FormatToken *Previous = Right.MatchingParen->Previous;
-return !(Previous && (Previous->is(tok::kw_for) || Previous->isIf()));
+// Avoid breaking when there is another parens immediately following
+// a closing parens, such as in cast operators and indirect function calls.
+return !((Previous && (Previous->is(tok::kw_for) || Previous->isIf())) ||
+ (Right.Next &&
+  (Right.Next->is(tok::l_paren) ||
+   (Right.Next->is(tok::r_paren) &&
+(Right.NestingLevel == 0 || Previous->is(tok::star));
   }
 
   // Allow breaking after a trailing annotation, e.g. after a method
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -716,8 +716,9 @@
(Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
 Style.Cpp11BracedListStyle)) &&
   State.Column > getNewLineColumn(State) &&
-  (!Previous.Previous || !Previous.Previous->isOneOf(
- tok::kw_for, tok::kw_while, tok::kw_switch)) 
&&
+  (!Previous.Previous ||
+   !Previous.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
+   tok::kw_switch)) &&
   // Don't do this for simple (no expressions) one-argument function calls
   // as that feels like needlessly wasting whitespace, e.g.:
   //


Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -5001,7 +5001,13 @@
   return false;
 }
 const FormatToken *Previous = Right.MatchingParen->Previous;
-return !(Previous && (Previous->is(tok::kw_for) || Previous->isIf()));
+// Avoid breaking when there is another parens immediately following
+// a closing parens, such as in cast operators and indirect function calls.
+return !((Previous && (Previous->is(tok::kw_for) || Previous->isIf())) ||
+ (Right.Next &&
+  (Right.Next->is(tok::l_paren) ||
+   (Right.Next->is(tok::r_paren) &&
+(Right.NestingLevel == 0 || Previous->is(tok::star));
   }
 
   // Allow breaking after a trailing annotation, e.g. after a method
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -716,8 +716,9 @@
(Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
 Style.Cpp11BracedListStyle)) &&
   State.Column > getNewLineColumn(State) &&
-  (!Previous.Previous || !Previous.Previous->isOneOf(
- tok::kw_for, tok::kw_while, tok::kw_switch)) &&
+  (!Previous.Previous ||
+   !Previous.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
+   tok::kw_switch)) &&
   // Don't do this for simple (no expressions) one-argument function calls
   // as that feels like needlessly wasting whitespace, e.g.:
   //
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137517: [TargetSupport] Generate the defs for RISCV CPUs using llvm-tblgen.

2022-11-11 Thread Francesco Petrogalli via Phabricator via cfe-commits
fpetrogalli updated this revision to Diff 474817.
fpetrogalli added a comment.

I have applied the chaged suggested by @jrtc27:

1. The classes `RISCVProcessorModelPROC` and `RISCVProcessorModelTUNE_PROC` now 
are derived from `ProcessorModel`;
2. The `Enum` field is removed from both classes. What was read from `Enum` is 
now read from the `NAME` of the tablegen record.

I also updated some of the `CmakeLists.txt` as the header of 
`llvm/include/llvm/TargetSupport/TargetParser.h` was missing the include of the 
generated file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137517

Files:
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Driver/CMakeLists.txt
  llvm/include/llvm/TargetSupport/RISCVTargetParser.def
  llvm/include/llvm/TargetSupport/TargetParser.h
  llvm/include/llvm/module.modulemap
  llvm/lib/Target/AArch64/AsmParser/CMakeLists.txt
  llvm/lib/Target/AArch64/CMakeLists.txt
  llvm/lib/Target/AMDGPU/AsmParser/CMakeLists.txt
  llvm/lib/Target/AMDGPU/CMakeLists.txt
  llvm/lib/Target/AMDGPU/MCA/CMakeLists.txt
  llvm/lib/Target/AMDGPU/MCTargetDesc/CMakeLists.txt
  llvm/lib/Target/AMDGPU/Utils/CMakeLists.txt
  llvm/lib/Target/ARM/AsmParser/CMakeLists.txt
  llvm/lib/Target/ARM/CMakeLists.txt
  llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt
  llvm/lib/Target/RISCV/CMakeLists.txt
  llvm/lib/Target/RISCV/MCTargetDesc/CMakeLists.txt
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/TargetSupport/CMakeLists.txt
  llvm/lib/TargetSupport/TargetParser.cpp
  llvm/unittests/Support/CMakeLists.txt
  llvm/unittests/TargetSupport/CMakeLists.txt
  llvm/utils/TableGen/CMakeLists.txt
  llvm/utils/TableGen/RISCVTargetDefEmitter.cpp
  llvm/utils/TableGen/TableGen.cpp
  llvm/utils/TableGen/TableGenBackends.h

Index: llvm/utils/TableGen/TableGenBackends.h
===
--- llvm/utils/TableGen/TableGenBackends.h
+++ llvm/utils/TableGen/TableGenBackends.h
@@ -94,7 +94,7 @@
 void EmitDirectivesDecl(RecordKeeper &RK, raw_ostream &OS);
 void EmitDirectivesImpl(RecordKeeper &RK, raw_ostream &OS);
 void EmitDXILOperation(RecordKeeper &RK, raw_ostream &OS);
-
+void EmitRISCVTargetDef(RecordKeeper &RK, raw_ostream &OS);
 } // End llvm namespace
 
 #endif
Index: llvm/utils/TableGen/TableGen.cpp
===
--- llvm/utils/TableGen/TableGen.cpp
+++ llvm/utils/TableGen/TableGen.cpp
@@ -58,6 +58,7 @@
   GenDirectivesEnumDecl,
   GenDirectivesEnumImpl,
   GenDXILOperation,
+  GenRISCVTargetDef,
 };
 
 namespace llvm {
@@ -141,8 +142,9 @@
 clEnumValN(GenDirectivesEnumImpl, "gen-directive-impl",
"Generate directive related implementation code"),
 clEnumValN(GenDXILOperation, "gen-dxil-operation",
-   "Generate DXIL operation information")));
-
+   "Generate DXIL operation information"),
+clEnumValN(GenRISCVTargetDef, "gen-riscv-target-def",
+   "Generate the list of CPU for RISCV")));
 cl::OptionCategory PrintEnumsCat("Options for -print-enums");
 cl::opt Class("class", cl::desc("Print Enum list for this class"),
cl::value_desc("class name"),
@@ -278,6 +280,9 @@
   case GenDXILOperation:
 EmitDXILOperation(Records, OS);
 break;
+  case GenRISCVTargetDef:
+EmitRISCVTargetDef(Records, OS);
+break;
   }
 
   return false;
Index: llvm/utils/TableGen/RISCVTargetDefEmitter.cpp
===
--- /dev/null
+++ llvm/utils/TableGen/RISCVTargetDefEmitter.cpp
@@ -0,0 +1,49 @@
+//===- RISCVTargetDefEmitter.cpp - Generate lists of RISCV CPUs ---===//
+//
+// 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 tablegen backend emits the include file needed by the target
+// parser to parse the RISCV CPUs.
+//
+//===--===//
+
+#include "llvm/TableGen/Record.h"
+
+namespace llvm {
+void EmitRISCVTargetDef(RecordKeeper &RK, raw_ostream &OS) {
+  const auto &Map = RK.getDefs();
+
+  OS << "#ifndef PROC\n"
+ << "#define PROC(ENUM, NAME, FEATURES, DEFAULT_MARCH)\n"
+ << "#endif\n\n";
+
+  OS << "PROC(INVALID, {\"invalid\"}, FK_INVALID, {\"\"})\n";
+  // Iterate on all definition records.
+  for (auto &Def : Map) {
+const auto &Record = Def.second;
+if (Record->isSubClassOf("RISCVProcessorModelPROC"))
+  OS << "PROC(" << Record->getName() << ", "
+ << "{\"" << Record->getValueAsString("Name") << "\"},"
+ << Record->getValueAsString("EnumFeatures") << ", "
+ << "{\"" << Record->getValueAsString("DefaultMarch") << "\"})\n";
+  }

[PATCH] D137040: [clangd] Add heuristic for dropping snippet when completing member function pointer

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

Fix test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137040

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/unittests/Sema/CodeCompleteTest.cpp

Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -23,7 +23,10 @@
 
 using namespace clang;
 using namespace clang::tooling;
+using ::testing::AllOf;
+using ::testing::Contains;
 using ::testing::Each;
+using ::testing::Field;
 using ::testing::UnorderedElementsAre;
 
 const char TestCCName[] = "test.cc";
@@ -36,6 +39,48 @@
   std::string PtrDiffType;
 };
 
+struct CompletedFunctionDecl {
+  std::string Name;
+  bool IsStatic;
+  bool CanBeCall;
+};
+
+class SaveCompletedFunctions : public CodeCompleteConsumer {
+public:
+  SaveCompletedFunctions(std::vector &CompletedFuncDecls)
+  : CodeCompleteConsumer(/*CodeCompleteOpts=*/{}),
+CompletedFuncDecls(CompletedFuncDecls),
+CCTUInfo(std::make_shared()) {}
+
+  void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
+  CodeCompletionResult *Results,
+  unsigned NumResults) override {
+for (unsigned I = 0; I < NumResults; ++I) {
+  auto R = Results[I];
+  if (R.Kind == CodeCompletionResult::RK_Declaration) {
+if (const auto *FD = llvm::dyn_cast(R.getDeclaration())) {
+  CompletedFunctionDecl D;
+  D.Name = FD->getNameAsString();
+  D.CanBeCall = R.FunctionCanBeCall;
+  D.IsStatic = FD->isStatic();
+  CompletedFuncDecls.emplace_back(std::move(D));
+}
+  }
+}
+  }
+
+private:
+  CodeCompletionAllocator &getAllocator() override {
+return CCTUInfo.getAllocator();
+  }
+
+  CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
+
+  std::vector &CompletedFuncDecls;
+
+  CodeCompletionTUInfo CCTUInfo;
+};
+
 class VisitedContextFinder : public CodeCompleteConsumer {
 public:
   VisitedContextFinder(CompletionContext &ResultCtx)
@@ -74,12 +119,15 @@
 
 class CodeCompleteAction : public SyntaxOnlyAction {
 public:
-  CodeCompleteAction(ParsedSourceLocation P, CompletionContext &ResultCtx)
-  : CompletePosition(std::move(P)), ResultCtx(ResultCtx) {}
+  CodeCompleteAction(ParsedSourceLocation P, CompletionContext &ResultCtx,
+ CodeCompleteConsumer *Consumer = nullptr)
+  : CompletePosition(std::move(P)), ResultCtx(ResultCtx),
+Consumer(Consumer) {}
 
   bool BeginInvocation(CompilerInstance &CI) override {
 CI.getFrontendOpts().CodeCompletionAt = CompletePosition;
-CI.setCodeCompletionConsumer(new VisitedContextFinder(ResultCtx));
+CI.setCodeCompletionConsumer(
+Consumer ? Consumer : new VisitedContextFinder(ResultCtx));
 return true;
   }
 
@@ -87,6 +135,7 @@
   // 1-based code complete position ;
   ParsedSourceLocation CompletePosition;
   CompletionContext &ResultCtx;
+  CodeCompleteConsumer *Consumer;
 };
 
 ParsedSourceLocation offsetToPosition(llvm::StringRef Code, size_t Offset) {
@@ -129,6 +178,83 @@
   return Types;
 }
 
+std::vector
+CollectCompletedFunctions(StringRef Code, std::size_t Point) {
+  CompletionContext DummyContext;
+  std::vector Result;
+  clang::tooling::runToolOnCodeWithArgs(
+  std::make_unique(offsetToPosition(Code, Point),
+   DummyContext,
+   new SaveCompletedFunctions(Result)),
+  Code, {"-std=c++11"}, TestCCName);
+  return Result;
+}
+
+TEST(SemaCodeCompleteTest, FunctionCanBeCall) {
+  llvm::Annotations Code(R"cpp(
+struct Foo {
+  static int staticMethod();
+  int method() const;
+  Foo() {
+this->$canBeCall^
+$canBeCall^
+Foo::$canBeCall^
+  }
+};
+
+struct Derived : Foo {
+  Derived() {
+Foo::$canBeCall^
+  }
+};
+
+struct OtherClass {
+  OtherClass() {
+Foo f;
+f.$canBeCall^
+&Foo::$cannotBeCall^
+  }
+};
+
+int main() {
+  Foo f;
+  f.$canBeCall^
+  &Foo::$cannotBeCall^
+}
+)cpp");
+
+  for (const auto &P : Code.points("canBeCall")) {
+auto Results = CollectCompletedFunctions(Code.code(), P);
+EXPECT_THAT(
+Results,
+Contains(AllOf(
+Field("Name", &CompletedFunctionDecl::Name, "method"),
+Field("IsStatic", &CompletedFunctionDecl::IsStatic, false),
+Field("CanBeCall", &CompletedFunctionDecl::CanBeCall, true;
+  }
+
+  for (const auto &P : Code.points("cannotBeCall")) 

[PATCH] D137712: Correctly handle Substitution failure in concept specialization.

2022-11-11 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I think this is a move in the right direction, and generally is probably pretty 
close.  The new bool for `ArgsHasSubstitutionFailure` isn't something I get the 
need for yet though.

we also need release notes.




Comment at: clang/include/clang/AST/ExprConcepts.h:103
 
+  bool hasSubstitutionFailureInArgs() const {
+return ArgsHasSubstitutionFailure;

Does this really belong here instead of as a part of the 
ConceptSpecializationDecl?



Comment at: clang/include/clang/AST/ExprConcepts.h:159
+  // todo: add doc ?
+struct SubstitutionDiagnostic {
+  StringRef SubstitutedEntity;

I had a previous patch at something else where I was moving toward doing this 
change, so I think this is probably something inevitable.  

However, I'm having a tough time splitting this patch mentally between the 
'fix' and the infrastructure changes needed.  A part of me thinks we should 
split this patch a bit in that direction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137712

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


[clang] 28e0798 - Revert "[Clang][AArch64][Darwin] Enable GlobalISel by default for Darwin ARM64 platforms."

2022-11-11 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2022-11-11T19:40:08Z
New Revision: 28e07984c3427908c9b423c7ed0cf6ac3064c5d8

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

LOG: Revert "[Clang][AArch64][Darwin] Enable GlobalISel by default for Darwin 
ARM64 platforms."

This reverts commit f64802e8d3e9db299cad913ffcb734c8d35dc5f0.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/global-isel.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 217a277b1f2d..90c4bb51c6ec 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7225,29 +7225,15 @@ void Clang::ConstructJob(Compilation &C, const 
JobAction &JA,
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 
-  A = Args.getLastArg(options::OPT_fglobal_isel, options::OPT_fno_global_isel);
-  // If a configuration is fully supported, we don't issue any warnings or
-  // remarks.
-  bool IsFullySupported = getToolChain().getTriple().isOSDarwin() &&
-  Triple.getArch() == llvm::Triple::aarch64;
-  if (IsFullySupported) {
-if (A && A->getOption().matches(options::OPT_fno_global_isel)) {
-  CmdArgs.push_back("-mllvm");
-  CmdArgs.push_back("-global-isel=0");
-} else {
-  CmdArgs.push_back("-mllvm");
-  CmdArgs.push_back("-global-isel=1");
-  CmdArgs.push_back("-mllvm");
-  CmdArgs.push_back("-global-isel-abort=0");
-}
-  } else if (A) {
+  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
+   options::OPT_fno_global_isel)) {
 CmdArgs.push_back("-mllvm");
 if (A->getOption().matches(options::OPT_fglobal_isel)) {
   CmdArgs.push_back("-global-isel=1");
 
   // GISel is on by default on AArch64 -O0, so don't bother adding
   // the fallback remarks for it. Other combinations will add a warning of
-  // some kind, unless we're on Darwin.
+  // some kind.
   bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
   bool IsOptLevelSupported = false;
 

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 848b81ab54a2..333d99842e23 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -381,11 +381,10 @@ void darwin::Linker::AddLinkArgs(Compilation &C, const 
ArgList &Args,
   D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
   }
 
-  // GlobalISel is enabled by default on AArch64 Darwin.
-  if (getToolChain().getArch() == llvm::Triple::aarch64) {
-Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
- options::OPT_fno_global_isel);
-if (!A || !A->getOption().matches(options::OPT_fno_global_isel)) {
+  // If GlobalISel is enabled, pass it through to LLVM.
+  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
+   options::OPT_fno_global_isel)) {
+if (A->getOption().matches(options::OPT_fglobal_isel)) {
   CmdArgs.push_back("-mllvm");
   CmdArgs.push_back("-global-isel");
   // Disable abort and fall back to SDAG silently.

diff  --git a/clang/test/Driver/global-isel.c b/clang/test/Driver/global-isel.c
index 0d3bd2b2fe26..66f196b03c1e 100644
--- a/clang/test/Driver/global-isel.c
+++ b/clang/test/Driver/global-isel.c
@@ -6,7 +6,6 @@
 // RUN: %clang -target aarch64 -fglobal-isel -S %s -### 2>&1 | FileCheck 
--check-prefix=ARM64-DEFAULT %s
 // RUN: %clang -target aarch64 -fglobal-isel -S -O0 %s -### 2>&1 | FileCheck 
--check-prefix=ARM64-O0 %s
 // RUN: %clang -target aarch64 -fglobal-isel -S -O2 %s -### 2>&1 | FileCheck 
--check-prefix=ARM64-O2 %s
-// RUN: %clang -arch arm64 -fglobal-isel -S -O2 %s -### 2>&1 | FileCheck 
--check-prefixes=DARWIN-ARM64-O2,ENABLED %s
 // RUN: %clang -target aarch64 -fglobal-isel -Wno-global-isel -S -O2 %s -### 
2>&1 | FileCheck --check-prefix=ARM64-O2-NOWARN %s
 
 // RUN: %clang -target x86_64 -fglobal-isel -S %s -### 2>&1 | FileCheck 
--check-prefix=X86_64 %s
@@ -28,7 +27,6 @@
 // ARM64-DEFAULT-NOT: warning: -fglobal-isel
 // ARM64-DEFAULT-NOT: "-global-isel-abort=2"
 // ARM64-O0-NOT: warning: -fglobal-isel
-// DARWIN-ARM64-O2-NOT: warning: -fglobal-isel
 // ARM64-O2: warning: -fglobal-isel support is incomplete for this 
architecture at the current optimization level
 // ARM64-O2: "-mllvm" "-global-isel-abort=2"
 // ARM64-O2-NOWARN-NOT: warning: -fglobal-isel



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


[clang] 0f7e863 - [LinkerWrapper] Perform device linking steps in parallel

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

Author: Joseph Huber
Date: 2022-11-11T13:46:33-06:00
New Revision: 0f7e8631547ad2cbbe5bcf1933e1353e58f58406

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

LOG: [LinkerWrapper] Perform device linking steps in parallel

This patch changes the device linking steps to be performed in parallel
when multiple offloading architectures are being used. We use the LLVM
parallelism support to accomplish this by simply doing each inidividual
device linking job in a single thread. This change required re-parsing
the input arguments as these arguments have internal state that would
not be properly shared between the threads otherwise.

By default, the parallelism uses all threads availible. But this can be
controlled with the `--wrapper-jobs=` option. This was required in a few
tests to ensure the ordering was still deterministic.

Reviewed By: tra

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

Added: 


Modified: 
clang/test/Driver/linker-wrapper.c
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td

Removed: 




diff  --git a/clang/test/Driver/linker-wrapper.c 
b/clang/test/Driver/linker-wrapper.c
index b2d73f3621087..7d958301f727b 100644
--- a/clang/test/Driver/linker-wrapper.c
+++ b/clang/test/Driver/linker-wrapper.c
@@ -107,7 +107,19 @@
 
 // CUDA: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_52 {{.*}}.o
 // CUDA: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.o {{.*}}.o
-// CUDA: fatbinary{{.*}}-64 --create {{.*}}.fatbin 
--image=profile=sm_52,file={{.*}}.out --image=profile=sm_70,file={{.*}}.out
+// CUDA: fatbinary{{.*}}-64 --create {{.*}}.fatbin 
--image=profile=sm_70,file={{.*}}.out --image=profile=sm_52,file={{.*}}.out 
+
+// RUN: clang-offload-packager -o %t.out \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=cuda,triple=nvptx64-nvidia-cuda,arch=sm_80
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=cuda,triple=nvptx64-nvidia-cuda,arch=sm_75
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=cuda,triple=nvptx64-nvidia-cuda,arch=sm_70
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=cuda,triple=nvptx64-nvidia-cuda,arch=sm_52
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
+// RUN:   -fembed-offload-object=%t.out
+// RUN: clang-linker-wrapper --dry-run --host-triple=x86_64-unknown-linux-gnu 
--wrapper-jobs=4 \
+// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=CUDA-PAR
+
+// CUDA-PAR: fatbinary{{.*}}-64 --create {{.*}}.fatbin
 
 // RUN: clang-offload-packager -o %t.out \
 // RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=hip,triple=amdgcn-amd-amdhsa,arch=gfx90a
 \
@@ -120,7 +132,7 @@
 
 // HIP: lld{{.*}}-flavor gnu --no-undefined -shared 
-plugin-opt=-amdgpu-internalize-symbols -plugin-opt=mcpu=gfx908 -o {{.*}}.out 
{{.*}}.o
 // HIP: lld{{.*}}-flavor gnu --no-undefined -shared 
-plugin-opt=-amdgpu-internalize-symbols -plugin-opt=mcpu=gfx90a -o {{.*}}.out 
{{.*}}.o
-// HIP: clang-offload-bundler{{.*}}-type=o -bundle-align=4096 
-targets=host-x86_64-unknown-linux,hipv4-amdgcn-amd-amdhsa--gfx908,hipv4-amdgcn-amd-amdhsa--gfx90a
 -input=/dev/null -input={{.*}}.out -input={{.*}}out -output={{.*}}.hipfb
+// HIP: clang-offload-bundler{{.*}}-type=o -bundle-align=4096 
-targets=host-x86_64-unknown-linux,hipv4-amdgcn-amd-amdhsa--gfx90a,hipv4-amdgcn-amd-amdhsa--gfx908
 -input=/dev/null -input={{.*}}.out -input={{.*}}out -output={{.*}}.hipfb
 
 // RUN: clang-offload-packager -o %t.out \
 // RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908
 \

diff  --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 6a12b64f7d7dd..42fde3d790fbf 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Support/Host.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Parallel.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
@@ -1119,19 +1120,34 @@ DerivedArgList getLinkerArgs(ArrayRef 
Input,
 /// be registered by the runtime.
 Expected>
 linkAndWrapDeviceFiles(SmallVectorImpl &LinkerInputFiles,
-   const InputArgList &Args) {
+   const InputArgList &Args, char **Argv, int Argc) {
   llvm::TimeTraceScope TimeScope("Handle all device input");
 
-  DenseMap> InputsForTarget;
+  DenseMap> InputMap;
   for (auto &File : LinkerInputFiles)
-InputsForTarget[File].emplace_back(std::move(File));
+InputMap[File].emplace_back(std::move(File));
   LinkerInputFiles.clear();
 
-  DenseMap>

  1   2   >