[PATCH] D122377: [PowerPC][Linux] Support 16-byte lock free atomics on pwr8 and up

2022-03-25 Thread Kai Luo via Phabricator via cfe-commits
lkail updated this revision to Diff 418142.
lkail added reviewers: dim, pkubaj.
lkail set the repository for this revision to rG LLVM Github Monorepo.
lkail added subscribers: pkubaj, dim.
lkail added a comment.

@dim  @pkubaj We are modifying layout of 16-byte atomic type on Linux to be 
consistent with GCC, I don't know if it also applies to freebsd as @MaskRay 
pointed out.
To be more specific, on Linux, for arch level supporting 16-byte lock free 
atomics, 16-byte atomic type is properly aligned.

  #include 
  
  int printf(const char *, ...);
  
  typedef struct A {
char x[16];
  } A;
  
  typedef struct B {
char q;
_Atomic(A) a;
  } B;
  
  int main(void) {
_Atomic(A) *p = 0;
printf("aligned: %d\n", __builtin_offsetof(B, a) % 16 == 0);
  #if __clang__
printf("lock free (size built-in): %d\n", 
__c11_atomic_is_lock_free(sizeof(*p)));
  #endif
printf("lock free (type query using pointer): %d\n", 
atomic_is_lock_free(p));
  }

Current clang gives

  aligned: 0
  lock free (size built-in): 1
  lock free (type query using pointer): 1

GCC gives

  aligned: 1
  lock free (type query using pointer): 1

This patch also modifies the query of `__atomic_always_lock_free(16, 0)` to 
return true for supported arch level.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/PowerPC/atomic-alignment.c
  clang/test/CodeGen/PowerPC/quadword-atomics.c
  clang/test/Driver/ppc-quadword-atomics.c
  clang/test/Sema/atomic-ops.c

Index: clang/test/Sema/atomic-ops.c
===
--- clang/test/Sema/atomic-ops.c
+++ clang/test/Sema/atomic-ops.c
@@ -9,7 +9,7 @@
 // RUN:   -target-cpu pwr7
 // RUN: %clang_cc1 %s -verify -fgnuc-version=4.2.1 -ffreestanding \
 // RUN:   -fsyntax-only -triple=powerpc64le-linux-gnu -std=c11 \
-// RUN:   -target-cpu pwr8
+// RUN:   -target-cpu pwr8 -DPPC64_PWR8
 
 // Basic parsing/Sema tests for __c11_atomic_*
 
@@ -47,7 +47,11 @@
 _Static_assert(__c11_atomic_is_lock_free(3), ""); // expected-error {{not an integral constant expression}}
 _Static_assert(__c11_atomic_is_lock_free(4), "");
 _Static_assert(__c11_atomic_is_lock_free(8), "");
+#ifndef PPC64_PWR8
 _Static_assert(__c11_atomic_is_lock_free(16), ""); // expected-error {{not an integral constant expression}}
+#else
+_Static_assert(__c11_atomic_is_lock_free(16), ""); // expected-no-error
+#endif
 _Static_assert(__c11_atomic_is_lock_free(17), ""); // expected-error {{not an integral constant expression}}
 
 _Static_assert(__atomic_is_lock_free(1, 0), "");
@@ -55,15 +59,23 @@
 _Static_assert(__atomic_is_lock_free(3, 0), ""); // expected-error {{not an integral constant expression}}
 _Static_assert(__atomic_is_lock_free(4, 0), "");
 _Static_assert(__atomic_is_lock_free(8, 0), "");
+#ifndef PPC64_PWR8
 _Static_assert(__atomic_is_lock_free(16, 0), ""); // expected-error {{not an integral constant expression}}
+#else
+_Static_assert(__atomic_is_lock_free(16, 0), ""); // expected-no-error
+#endif
 _Static_assert(__atomic_is_lock_free(17, 0), ""); // expected-error {{not an integral constant expression}}
 
 _Static_assert(atomic_is_lock_free((atomic_char*)0), "");
 _Static_assert(atomic_is_lock_free((atomic_short*)0), "");
 _Static_assert(atomic_is_lock_free((atomic_int*)0), "");
 _Static_assert(atomic_is_lock_free((atomic_long*)0), "");
+#ifndef PPC64_PWR8
 // noi128-error@+1 {{__int128 is not supported on this target}}
 _Static_assert(atomic_is_lock_free((_Atomic(__int128)*)0), ""); // expected-error {{not an integral constant expression}}
+#else
+_Static_assert(atomic_is_lock_free((_Atomic(__int128)*)0), ""); // expected-no-error
+#endif
 _Static_assert(atomic_is_lock_free(0 + (atomic_char*)0), "");
 
 char i8;
@@ -88,7 +100,11 @@
 _Static_assert(!__atomic_always_lock_free(3, 0), "");
 _Static_assert(__atomic_always_lock_free(4, 0), "");
 _Static_assert(__atomic_always_lock_free(8, 0), "");
+#ifndef PPC64_PWR8
 _Static_assert(!__atomic_always_lock_free(16, 0), "");
+#else
+_Static_assert(__atomic_always_lock_free(16, 0), "");
+#endif
 _Static_assert(!__atomic_always_lock_free(17, 0), "");
 
 _Static_assert(__atomic_always_lock_free(1, incomplete), "");
Index: clang/test/Driver/ppc-quadword-atomics.c
===
--- /dev/null
+++ clang/test/Driver/ppc-quadword-atomics.c
@@ -0,0 +1,17 @@
+// RUN: %clang -### -target powerpc-unknown-unknown -S %s 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=NO-QUADWORD-ATOMICS
+// RUN: %clang -### -target powerpc64-unknown-aix -S %s 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=NO-QUADWORD-ATOMICS
+// RUN: %clang -### -target powerpc64-unknown-unknown -S %s 2>&1 | \
+// RUN:   FileCheck %s
+// RUN: %clang -### -target powerpc64le-unknown-unknown -S %s 2>&1

[PATCH] D122377: [PowerPC][Linux] Support 16-byte lock free atomics on pwr8 and up

2022-03-25 Thread Kai Luo via Phabricator via cfe-commits
lkail added a comment.

Removed alter of `-ppc-quadword-atomcis` in backend to decouple from frontend.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

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


[PATCH] D120306: [clangd] IncludeCleaner: Add support for IWYU pragma private

2022-03-25 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 418155.
kbobyrev added a comment.

Fix a bug, add tests for diagnostics. This is ready for a review now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120306

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -9,6 +9,7 @@
 #include "Annotations.h"
 #include "IncludeCleaner.h"
 #include "SourceCode.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
@@ -266,8 +267,9 @@
 
 ReferencedLocations Locs = findReferencedLocations(AST);
 EXPECT_THAT(Locs.Stdlib, ElementsAreArray(WantSyms));
-ReferencedFiles Files = findReferencedFiles(Locs, AST.getIncludeStructure(),
-AST.getSourceManager());
+ReferencedFiles Files =
+findReferencedFiles(Locs, AST.getIncludeStructure(),
+AST.getCanonicalIncludes(), AST.getSourceManager());
 EXPECT_THAT(Files.Stdlib, ElementsAreArray(WantHeaders));
   }
 }
@@ -378,8 +380,8 @@
   auto &SM = AST.getSourceManager();
   auto &Includes = AST.getIncludeStructure();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST), Includes, SM);
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), Includes, AST.getCanonicalIncludes(), SM);
   llvm::StringSet<> ReferencedFileNames;
   for (FileID FID : ReferencedFiles.User)
 ReferencedFileNames.insert(
@@ -398,7 +400,8 @@
   EXPECT_THAT(ReferencedHeaderNames, ElementsAre(testPath("macros.h")));
 
   // Sanity check.
-  EXPECT_THAT(getUnused(AST, ReferencedHeaders), IsEmpty());
+  EXPECT_THAT(getUnused(AST, ReferencedHeaders, ReferencedFiles.PublicHeaders),
+  IsEmpty());
 }
 
 TEST(IncludeCleaner, DistinctUnguardedInclusions) {
@@ -427,9 +430,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -461,9 +464,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -479,14 +482,26 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "public.h"
+
+void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
+  TU.AdditionalFiles["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+void foo() {}
+  )cpp");
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
-  EXPECT_TRUE(ReferencedFiles.User.empty());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.size(), 1u);
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.begin()->getKey(), "\"public.h\"");
+  EXPECT_EQ(ReferencedFiles.User.size(), 1u);
+  EXPECT_EQ(*ReferencedFiles.User.begin(),
+AST.getSourceManager().getMainFileID());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
 }
 
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1616,10 +1616,15 @@
 ]]
   #include "used.h"
 
+$fix_private[[  $diag_private[[#include "private.h"]]
+]]
+  #include "public.h"
+
   #include 
 
   void foo() {
 used();
+foo();
   }
   )cpp");
   TestTU TU;

[PATCH] D122444: [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for LLVM_ENABLE_RUNTIMES builds

2022-03-25 Thread Michał Górny via Phabricator via cfe-commits
mgorny added inline comments.



Comment at: clang/lib/Driver/ToolChains/Linux.cpp:316
+  if (StringRef(D.Dir).startswith(SysRoot) &&
+  D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
 addPathIfExists(D, D.Dir + "/../lib", Paths);

I wonder if this still wouldn't get in the way of some (non-Gentoo) people who 
have clang in `/usr/bin/clang` and 32-bit libc++ in `/usr/lib/libc++.so`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122444

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


[PATCH] D120306: [clangd] IncludeCleaner: Add support for IWYU pragma private

2022-03-25 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 418159.
kbobyrev added a comment.

Add some docs, rebase on top of main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120306

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -9,6 +9,7 @@
 #include "Annotations.h"
 #include "IncludeCleaner.h"
 #include "SourceCode.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
@@ -280,8 +281,9 @@
 
 ReferencedLocations Locs = findReferencedLocations(AST);
 EXPECT_THAT(Locs.Stdlib, ElementsAreArray(WantSyms));
-ReferencedFiles Files = findReferencedFiles(Locs, AST.getIncludeStructure(),
-AST.getSourceManager());
+ReferencedFiles Files =
+findReferencedFiles(Locs, AST.getIncludeStructure(),
+AST.getCanonicalIncludes(), AST.getSourceManager());
 EXPECT_THAT(Files.Stdlib, ElementsAreArray(WantHeaders));
   }
 }
@@ -392,8 +394,8 @@
   auto &SM = AST.getSourceManager();
   auto &Includes = AST.getIncludeStructure();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST), Includes, SM);
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), Includes, AST.getCanonicalIncludes(), SM);
   llvm::StringSet<> ReferencedFileNames;
   for (FileID FID : ReferencedFiles.User)
 ReferencedFileNames.insert(
@@ -412,7 +414,8 @@
   EXPECT_THAT(ReferencedHeaderNames, ElementsAre(testPath("macros.h")));
 
   // Sanity check.
-  EXPECT_THAT(getUnused(AST, ReferencedHeaders), IsEmpty());
+  EXPECT_THAT(getUnused(AST, ReferencedHeaders, ReferencedFiles.PublicHeaders),
+  IsEmpty());
 }
 
 TEST(IncludeCleaner, DistinctUnguardedInclusions) {
@@ -441,9 +444,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -475,9 +478,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -493,14 +496,26 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "public.h"
+
+void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
+  TU.AdditionalFiles["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+void foo() {}
+  )cpp");
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
-  EXPECT_TRUE(ReferencedFiles.User.empty());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.size(), 1u);
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.begin()->getKey(), "\"public.h\"");
+  EXPECT_EQ(ReferencedFiles.User.size(), 1u);
+  EXPECT_EQ(*ReferencedFiles.User.begin(),
+AST.getSourceManager().getMainFileID());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
 }
 
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1643,10 +1643,15 @@
 ]]
   #include "used.h"
 
+$fix_private[[  $diag_private[[#include "private.h"]]
+]]
+  #include "public.h"
+
   #include 
 
   void foo() {
 used();
+foo();
   }
   )cpp");
   TestTU TU;
@@ -1659,6 +1664,15 @@
 #pra

[PATCH] D120306: [clangd] IncludeCleaner: Add support for IWYU pragma private

2022-03-25 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 418160.
kbobyrev added a comment.

Use better name for header recorder lambda.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120306

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -9,6 +9,7 @@
 #include "Annotations.h"
 #include "IncludeCleaner.h"
 #include "SourceCode.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
@@ -280,8 +281,9 @@
 
 ReferencedLocations Locs = findReferencedLocations(AST);
 EXPECT_THAT(Locs.Stdlib, ElementsAreArray(WantSyms));
-ReferencedFiles Files = findReferencedFiles(Locs, AST.getIncludeStructure(),
-AST.getSourceManager());
+ReferencedFiles Files =
+findReferencedFiles(Locs, AST.getIncludeStructure(),
+AST.getCanonicalIncludes(), AST.getSourceManager());
 EXPECT_THAT(Files.Stdlib, ElementsAreArray(WantHeaders));
   }
 }
@@ -392,8 +394,8 @@
   auto &SM = AST.getSourceManager();
   auto &Includes = AST.getIncludeStructure();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST), Includes, SM);
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), Includes, AST.getCanonicalIncludes(), SM);
   llvm::StringSet<> ReferencedFileNames;
   for (FileID FID : ReferencedFiles.User)
 ReferencedFileNames.insert(
@@ -412,7 +414,8 @@
   EXPECT_THAT(ReferencedHeaderNames, ElementsAre(testPath("macros.h")));
 
   // Sanity check.
-  EXPECT_THAT(getUnused(AST, ReferencedHeaders), IsEmpty());
+  EXPECT_THAT(getUnused(AST, ReferencedHeaders, ReferencedFiles.PublicHeaders),
+  IsEmpty());
 }
 
 TEST(IncludeCleaner, DistinctUnguardedInclusions) {
@@ -441,9 +444,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -475,9 +478,9 @@
 
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
   llvm::StringSet<> ReferencedFileNames;
   auto &SM = AST.getSourceManager();
   for (FileID FID : ReferencedFiles.User)
@@ -493,14 +496,26 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "public.h"
+
+void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
+  TU.AdditionalFiles["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+void foo() {}
+  )cpp");
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles =
-  findReferencedFiles(findReferencedLocations(AST),
-  AST.getIncludeStructure(), AST.getSourceManager());
-  EXPECT_TRUE(ReferencedFiles.User.empty());
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.size(), 1u);
+  EXPECT_EQ(ReferencedFiles.PublicHeaders.begin()->getKey(), "\"public.h\"");
+  EXPECT_EQ(ReferencedFiles.User.size(), 1u);
+  EXPECT_EQ(*ReferencedFiles.User.begin(),
+AST.getSourceManager().getMainFileID());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
 }
 
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1643,10 +1643,15 @@
 ]]
   #include "used.h"
 
+$fix_private[[  $diag_private[[#include "private.h"]]
+]]
+  #include "public.h"
+
   #include 
 
   void foo() {
 used();
+foo();
   }
   )cpp");
   TestTU TU;
@@ -1659,6 +1664,15 @@
   

[clang] 6c0e60e - [C++20][Modules][HU 1/5] Introduce header units as a module type.

2022-03-25 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-03-25T09:17:14Z
New Revision: 6c0e60e884a20016ccc0d7c7e6f06df089a0de86

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

LOG: [C++20][Modules][HU 1/5] Introduce header units as a module type.

This is the first in a series of patches that introduce C++20 importable
header units.

These differ from clang header modules in that:
 (a) they are identifiable by an internal name
 (b) they represent the top level source for a single header - although
 that might include or import other headers.

We name importable header units with the path by which they are specified
(although that need not be the absolute path for the file).

So "foo/bar.h" would have a name "foo/bar.h".  Header units are made a
separate module type so that we can deal with diagnosing places where they
are permitted but a named module is not.

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

Added: 
clang/test/Modules/cxx20-hu-01.cpp

Modified: 
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Basic/LangOptions.h
clang/include/clang/Basic/Module.h
clang/include/clang/Driver/Options.td
clang/include/clang/Frontend/FrontendActions.h
clang/include/clang/Frontend/FrontendOptions.h
clang/include/clang/Lex/ModuleMap.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/Decl.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Frontend/FrontendActions.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
clang/lib/Lex/ModuleMap.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaModule.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 3745740d3d29c..05b9691142998 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -166,7 +166,7 @@ BENIGN_LANGOPT(HeinousExtensions , 1, 0, "extensions that 
we really don't like a
 LANGOPT(Modules   , 1, 0, "modules semantics")
 COMPATIBLE_LANGOPT(ModulesTS  , 1, 0, "C++ Modules TS syntax")
 COMPATIBLE_LANGOPT(CPlusPlusModules, 1, 0, "C++ modules syntax")
-BENIGN_ENUM_LANGOPT(CompilingModule, CompilingModuleKind, 2, CMK_None,
+BENIGN_ENUM_LANGOPT(CompilingModule, CompilingModuleKind, 3, CMK_None,
 "compiling a module interface")
 BENIGN_LANGOPT(CompilingPCH, 1, 0, "building a pch")
 BENIGN_LANGOPT(BuildingPCHWithObjectFile, 1, 0, "building a pch which has a 
corresponding object file")

diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 6aa24d2facc2a..96fd6049efeca 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -90,6 +90,9 @@ class LangOptions : public LangOptionsBase {
 /// Compiling a module from a list of header files.
 CMK_HeaderModule,
 
+/// Compiling a module header unit.
+CMK_HeaderUnit,
+
 /// Compiling a C++ modules TS module interface unit.
 CMK_ModuleInterface,
   };

diff  --git a/clang/include/clang/Basic/Module.h 
b/clang/include/clang/Basic/Module.h
index 3d1af45c48f3d..9752ff61e4a27 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -109,6 +109,9 @@ class Module {
 /// This is a C++20 module interface unit.
 ModuleInterfaceUnit,
 
+/// This is a C++ 20 header unit.
+ModuleHeaderUnit,
+
 /// This is a C++ 20 module partition interface.
 ModulePartitionInterface,
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6ed87f9a464d0..784751a1a6863 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5640,6 +5640,8 @@ def emit_module_interface : Flag<["-"], 
"emit-module-interface">,
   HelpText<"Generate pre-compiled module file from a C++ module interface">;
 def emit_header_module : Flag<["-"], "emit-header-module">,
   HelpText<"Generate pre-compiled module file from a set of header files">;
+def emit_header_unit : Flag<["-"], "emit-header-unit">,
+  HelpText<"Generate C++20 header units from header files">;
 def emit_pch : Flag<["-"], "emit-pch">,
   HelpText<"Generate pre-compiled header file">;
 def emit_llvm_bc : Flag<["-"], "emit-llvm-bc">,

diff  --git a/clang/include/clang/Frontend/FrontendActions.h 
b/clang/include/clang/Frontend/FrontendActions.h
index 9b5b757034a6a..ae829d741152a 100644
--- a/clang/include/clang/Frontend/FrontendActions.h
+++ b/clang/include/clang/Frontend/FrontendActions.h
@@ -168,6 +168,15 @@ class GenerateHeaderModuleAction : public 
GenerateModuleAction {
   CreateOutputFile(CompilerInstance &CI, StringRef InFile) override;
 };
 
+class GenerateHeaderUnitAction : public Ge

[PATCH] D121095: [C++20][Modules][HU 1/5] Introduce header units as a module type.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6c0e60e884a2: [C++20][Modules][HU 1/5] Introduce header 
units as a module type. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121095

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/Module.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendActions.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/include/clang/Lex/ModuleMap.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/test/Modules/cxx20-hu-01.cpp

Index: clang/test/Modules/cxx20-hu-01.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-01.cpp
@@ -0,0 +1,104 @@
+// Test generation and import of simple C++20 Header Units.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-01.h \
+// RUN:  -o %t/hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/hu-01.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-01.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -o %t/B.pcm -Rmodule-import 2>&1  | \
+// RUN: FileCheck --check-prefix=CHECK-IMP %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-02.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -o %t/C.pcm -Rmodule-import 2>&1  | \
+// RUN: FileCheck --check-prefix=CHECK-GMF-IMP %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-02.h \
+// RUN:  -o %t/hu-02.pcm
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-03.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -fmodule-file=%t/hu-02.pcm -o %t/D.pcm \
+// RUN: -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-BOTH %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-03.h \
+// RUN: -fmodule-file=%t/hu-01.pcm  -o %t/hu-03.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/hu-03.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-04.cpp \
+// RUN:  -fmodule-file=%t/hu-03.pcm -o %t/E.pcm -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-NESTED %s -DTDIR=%t
+
+//--- hu-01.h
+int foo(int);
+
+// CHECK-HU:  == C++20 Module structure ==
+// CHECK-HU-NEXT:  Header Unit '[[TDIR]]/hu-01.h' is the Primary Module at index #1
+
+//--- imp-hu-01.cpp
+export module B;
+import "hu-01.h";
+
+int bar(int x) {
+  return foo(x);
+}
+// CHECK-IMP: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// expected-no-diagnostics
+
+//--- imp-hu-02.cpp
+module;
+import "hu-01.h";
+
+export module C;
+
+int bar(int x) {
+  return foo(x);
+}
+// CHECK-GMF-IMP: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// expected-no-diagnostics
+
+//--- hu-02.h
+int baz(int);
+
+//--- imp-hu-03.cpp
+module;
+export import "hu-01.h";
+
+export module D;
+import "hu-02.h";
+
+int bar(int x) {
+  return foo(x) + baz(x);
+}
+// CHECK-BOTH: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// CHECK-BOTH: remark: importing module '[[TDIR]]/hu-02.h' from '[[TDIR]]/hu-02.pcm'
+// expected-no-diagnostics
+
+//--- hu-03.h
+export import "hu-01.h";
+int baz(int);
+// CHECK-HU-HU:  == C++20 Module structure ==
+// CHECK-HU-HU-NEXT:  Header Unit '[[TDIR]]/hu-03.h' is the Primary Module at index #2
+// CHECK-HU-HU-NEXT:   Exports:
+// CHECK-HU-HU-NEXT:Header Unit '[[TDIR]]/hu-01.h' is at index #1
+
+// expected-no-diagnostics
+
+//--- imp-hu-04.cpp
+module;
+import "hu-03.h";
+
+export module E;
+
+int bar(int x) {
+  return foo(x) + baz(x);
+}
+// CHECK-NESTED: remark: importing module '[[TDIR]]/hu-03.h' from '[[TDIR]]/hu-03.pcm'
+// expected-no-diagnostics
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -97,6 +97,38 @@
   return nullptr;
 }
 
+void Sema::HandleStartOfHeaderUnit() {
+  assert(getLangOpts().CPlusPlusModules &&
+ "Header units are only valid for C++20 modules");
+  SourceLocation StartOfTU =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+
+  StringRef HUName = getLangOpts().CurrentModule;
+  if (HUName.empty()) {
+HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
+const_cast(getLangOpts()).CurrentModule = HUName.

[clang] 520c8ca - [Clang] Added release note for improved -Wunused-but-set-variable warning

2022-03-25 Thread Dávid Bolvanský via cfe-commits

Author: Dávid Bolvanský
Date: 2022-03-25T10:45:28+01:00
New Revision: 520c8ca9d2f940dd93618ad98c445573f13aa714

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

LOG: [Clang] Added release note for improved -Wunused-but-set-variable warning

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b268d0f8c20d8..cb2d81e21f243 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -93,6 +93,8 @@ Improvements to Clang's diagnostics
   extension definitions of an inline namespace and therefore points its note
   at the original definition. This fixes `Issue 50794 (PR51452)
   `_.
+- ``-Wunused-but-set-variable`` now also warns if the variable is only used
+  by unary operators.
 
 Non-comprehensive list of changes in this release
 - The builtin function __builtin_dump_struct would crash clang when the target 



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


[PATCH] D121757: [clang-format] Take out common code for parsing blocks

2022-03-25 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D121757#3406814 , @sstwcw wrote:

> I tried formatting the files in `clang-formatted-files.txt`. Besides the 
> files in the list that get changed when formatted with the program built from 
> `main`, none gets changed when I format them with the program built from this 
> patch, whether or not `parseSwitch` is modified.

To test a token-changing patch (e.g. inserting/removing braces) on a large 
codebase like clang, I would go through the following steps:

1. Build a debug version of clang-format from scratch without applying the 
patch.
2. Run the built clang-format on every `.(c|cpp|h)` file under `clang/`.
3. Build clang.
4. Run check-clang and save the output in a log file.
5. Run `git reset --hard` and apply the patch.
6. Build clang-format again.
7. Add `InsertBraces: true` to `clang/.clang-format`.
8. Repeat steps 2-4 above.
9. Compare the new log file with the pre-patch one. They should have exactly 
the same Unresolved/Failed tests. They should also have the same //numbers// of 
Skipped/Unsupported/Passed/Expectedly Failed tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121757

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


[clang] 311a00c - [clang-format] Clean up DefinitionBlockSeparatorTest. NFC.

2022-03-25 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-25T10:59:46+01:00
New Revision: 311a00c39046ed3f84cd31ffcd513975d3000402

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

LOG: [clang-format] Clean up DefinitionBlockSeparatorTest. NFC.

Added: 


Modified: 
clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 582b62e445df9..53a3c57ad59fa 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -56,17 +56,15 @@ class DefinitionBlockSeparatorTest : public ::testing::Test 
{
   InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
 else
   InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
-EXPECT_EQ(ExpectedCode.str(), separateDefinitionBlocks(ExpectedCode, 
Style))
+EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-std::string InverseResult =
-separateDefinitionBlocks(ExpectedCode, InverseStyle);
-EXPECT_NE(ExpectedCode.str(), InverseResult)
+EXPECT_NE(ExpectedCode,
+  separateDefinitionBlocks(ExpectedCode, InverseStyle))
 << "Inverse formatting makes no 
diff erence";
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
-EXPECT_EQ(ExpectedCode.str(), Result) << "Test failed. Formatted:\n"
-  << Result;
+EXPECT_EQ(ExpectedCode, Result) << "Test failed. Formatted:\n" << Result;
   }
 
   static std::string removeEmptyLines(llvm::StringRef Code) {



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


[PATCH] D121757: [clang-format] Take out common code for parsing blocks

2022-03-25 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D121757#3407539 , @owenpan wrote:

> In D121757#3406814 , @sstwcw wrote:
>
>> I tried formatting the files in `clang-formatted-files.txt`. Besides the 
>> files in the list that get changed when formatted with the program built 
>> from `main`, none gets changed when I format them with the program built 
>> from this patch, whether or not `parseSwitch` is modified.
>
> To test a token-changing patch (e.g. inserting/removing braces) on a large 
> codebase like clang, I would go through the following steps:
>
> 1. Build a debug version of clang-format from scratch without applying the 
> patch.
> 2. Run the built clang-format on every `.(c|cpp|h)` file under `clang/`.
> 3. Build clang.
> 4. Run check-clang and save the output in a log file.
> 5. Run `git reset --hard` and apply the patch.
> 6. Build clang-format again.

And then run `git reset --hard` again before step 7 below.

> 7. Add `InsertBraces: true` to `clang/.clang-format`.
> 8. Repeat steps 2-4 above.
> 9. Compare the new log file with the pre-patch one. They should have exactly 
> the same Unresolved/Failed tests. They should also have the same //numbers// 
> of Skipped/Unsupported/Passed/Expectedly Failed tests.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121757

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


[PATCH] D122468: [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

2022-03-25 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122468

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -67,6 +67,25 @@
 EXPECT_EQ(ExpectedCode, Result) << "Test failed. Formatted:\n" << Result;
   }
 
+  static void _verifyFormatNoInverse(const char *File, int Line,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle(),
+ llvm::StringRef ExpectedCode = "") {
+::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
+bool HasOriginalCode = true;
+if (ExpectedCode == "") {
+  ExpectedCode = Code;
+  HasOriginalCode = false;
+}
+
+EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
+<< "Expected code is not stable";
+std::string CodeToFormat =
+HasOriginalCode ? Code.str() : removeEmptyLines(Code);
+std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
+EXPECT_EQ(ExpectedCode, Result) << "Test failed. Formatted:\n" << Result;
+  }
+
   static std::string removeEmptyLines(llvm::StringRef Code) {
 std::string Result = "";
 for (auto Char : Code.str()) {
@@ -83,6 +102,8 @@
 };
 
 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyFormatNoInverse(...) 
\
+  _verifyFormatNoInverse(__FILE__, __LINE__, __VA_ARGS__)
 
 TEST_F(DefinitionBlockSeparatorTest, Basic) {
   FormatStyle Style = getLLVMStyle();
@@ -448,6 +469,32 @@
Style);
 }
 
+TEST_F(DefinitionBlockSeparatorTest, TryBlocks) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormatNoInverse("void FunctionWithInternalTry()\n"
+"{\n"
+"  try\n"
+"  {\n"
+"return;\n"
+"  }\n"
+"  catch (const std::exception &)\n"
+"  {\n"
+"  }\n"
+"}",
+Style);
+  verifyFormatNoInverse("void FunctionWithTryBlock()\n"
+"try\n"
+"{\n"
+"  return;\n"
+"}\n"
+"catch (const std::exception &)\n"
+"{\n"
+"}",
+Style);
+}
+
 TEST_F(DefinitionBlockSeparatorTest, Leave) {
   FormatStyle Style = getLLVMStyle();
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2603,6 +2603,7 @@
   nextToken();
 }
 NeedsUnwrappedLine = false;
+Line->MustBeDeclaration = false;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -67,6 +67,25 @@
 EXPECT_EQ(ExpectedCode, Result) << "Test failed. Formatted:\n" << Result;
   }
 
+  static void _verifyFormatNoInverse(const char *File, int Line,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle(),
+ llvm::StringRef ExpectedCode = "") {
+::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
+bool HasOriginalCode = true;
+if (ExpectedCode == "") {
+  ExpectedCode = Code;
+  HasOriginalCode = false;
+}
+
+EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
+<< "Expected code is not stable";
+std::string CodeToFormat =
+HasOriginalCode ? Code.str() : removeEmptyLines(Code);
+std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
+EXPECT_EQ(ExpectedCode, Result) << "Test failed. For

[clang] ce2b36e - [clang] CheckSizelessVectorOperands - use castAs<> instead of getAs<> to avoid dereference of nullptr

2022-03-25 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2022-03-25T10:23:30Z
New Revision: ce2b36e123e7b5312016b09c1b2971c9d80416e7

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

LOG: [clang] CheckSizelessVectorOperands - use castAs<> instead of getAs<> to 
avoid dereference of nullptr

Move the only uses of the cast to where they are dereferenced.

Added: 


Modified: 
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ae48db03e06c9..1547a34b5c730 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10490,12 +10490,10 @@ QualType Sema::CheckSizelessVectorOperands(ExprResult 
&LHS, ExprResult &RHS,
   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
 
-  const BuiltinType *LHSVecType = LHSType->getAs();
-  const BuiltinType *RHSVecType = RHSType->getAs();
-
   unsigned DiagID = diag::err_typecheck_invalid_operands;
   if ((OperationKind == ACK_Arithmetic) &&
-  (LHSVecType->isSVEBool() || RHSVecType->isSVEBool())) {
+  (LHSType->castAs()->isSVEBool() ||
+   RHSType->castAs()->isSVEBool())) {
 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
   << RHS.get()->getSourceRange();
 return QualType();



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


[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418171.
iains added a comment.
Herald added a subscriber: MaskRay.

rebased, fix testcase for windows, add command line options to docs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,7 +189,9 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None),
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
   DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
   CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
@@ -335,8 +337,12 @@
 FinalPhase = phases::Preprocess;
 
   // --precompile only runs up to precompilation.
+  // Options that cause the output of C++20 compiled module interfaces or
+  // header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1252,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treating them as PCH, implicit modules or C++20 ones.
+  // TODO: inferring the mode like this seems fragile (it meets the objective
+  // of not requiring anything new for operation, however).
+  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
+  ModulesModeCXX20 =
+  !Args.hasArg(options::OPT_fmodules) && Std &&
+  (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
+   Std->containsValue("c++2a") || Std->containsValue("c++latest"));
+
+  // Process -fmodule-header{=} flags.
+  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
+   options::OPT_fmodule_header)) {
+// These flags force C++20 handling of headers.
+ModulesModeCXX20 = true;
+if (A->getOption().matches(options::OPT_fmodule_header))
+  CXX20HeaderType = HeaderMode_Default;
+else {
+  StringRef ArgName = A->getValue();
+  unsigned Kind = llvm::StringSwitch(ArgName)
+  .Case("user", HeaderMode_User)
+  .Case("system", HeaderMode_System)
+  .Default(~0U);
+  if (Kind == ~0U) {
+Diags.Report(diag::err_drv_invalid_value)
+<< A->getAsString(Args) << ArgName;
+  } else
+CXX20HeaderType = static

[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418172.
iains added a comment.

fix some formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,13 +189,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -334,9 +335,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1251,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treating them as PCH, implicit modules or C++20 ones.
+  // TODO: inferring the mode like this seems fragile (it meets the objective
+  // of not requiring anything new for operation, however).
+  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
+  ModulesModeCXX20 =
+  !Args.hasArg(options::OPT_fmodules) && Std &&
+  (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
+   Std->containsValue("c++2a") || Std->containsValue("c++latest"));
+
+  // Process -fmodule-header{=} flags.
+  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
+  

[PATCH] D122394: [C++20][Modules] Correct an assert for modules-ts.

2022-03-25 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan accepted this revision.
urnathan added a comment.
This revision is now accepted and ready to land.

Understood.  To document the approach:

1. clearly separate -fmodules-ts semantics (which are vague in places, but 
whatever)
2. implement c++20 modules semantics

3a) switch -fmodules-ts option to behave as #2 and delete any now-unreachable 
TS-specific code
3b) deprecate -fmodules-ts option and then remove.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122394

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


[clang] 635dde8 - Fix clang Sphinx build bot

2022-03-25 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-03-25T07:13:26-04:00
New Revision: 635dde811717e736ddb6b675f678b64c54607eba

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

LOG: Fix clang Sphinx build bot

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb2d81e21f243..58523c2569283 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,11 +97,11 @@ Improvements to Clang's diagnostics
   by unary operators.
 
 Non-comprehensive list of changes in this release
+-
 - The builtin function __builtin_dump_struct would crash clang when the target 
   struct have bitfield. Now it fixed, and __builtin_dump_struct support dump
   the bitwidth of bitfields.
   This fixes `Issue 54462 
`_.
--
 
 New Compiler Flags
 --



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


[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418187.
iains added a comment.

amend filecheck match to avoid quoting windows pathnames.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-01.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/test/Driver/cxx20-header-units-01.cpp
===
--- clang/test/Driver/cxx20-header-units-01.cpp
+++ clang/test/Driver/cxx20-header-units-01.cpp
@@ -16,4 +16,4 @@
 // CHECK-SYSTEM-SAME: "-x" "c++-system-header" "vector"
 // CHECK-ABS: "-emit-header-unit"
 // CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
-// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
+// CHECK-ABS-SAME: -x c++-header-unit-header [[TDIR]]/header-unit-01.hh
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,13 +189,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -334,9 +335,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1251,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends o

[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418188.
iains added a comment.

amend second testcase for windows


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-01.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: -x c++-header-unit-header [[TDIR]]/header-unit-01.hh
Index: clang/test/Driver/cxx20-header-units-01.cpp
===
--- clang/test/Driver/cxx20-header-units-01.cpp
+++ clang/test/Driver/cxx20-header-units-01.cpp
@@ -16,4 +16,4 @@
 // CHECK-SYSTEM-SAME: "-x" "c++-system-header" "vector"
 // CHECK-ABS: "-emit-header-unit"
 // CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
-// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
+// CHECK-ABS-SAME: -x c++-header-unit-header [[TDIR]]/header-unit-01.hh
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,13 +189,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -334,9 +335,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1251,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treatin

[PATCH] D120185: [ASTMatchers] Output currently processing match and nodes on crash

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120185#3406765 , @njames93 wrote:

> In D120185#3405091 , @aaron.ballman 
> wrote:
>
>> @thakis -- is it possible your build bot is configured to disable generation 
>> of crash dumps?
>
> So with a lot of trial and error, it seems that on certain windows 
> configurations, crash dumps just aren't being emitted.
> Best I can see so far is using clang to build the tests, results in 
> ENABLE_BACKTRACES being enabled, but no crash dumps being emitted, causing 
> the test failure.

From looking at CMake, I don't see anything that actually tests if backtraces 
are enabled by the OS; we just trust the user told us something valid and set 
ENABLE_BACKTRACES accordingly. So I'd still like to hear from @thakis about his 
bot configuration.

> I did change the test to throw an assert instead of a TRAP instruction, and 
> the assert message was captured but no crash dump was reported, so the test 
> infrastructure has no issue there.

That's good at least.

> I feel like a stop gap may be to disable the test when clang is the host 
> compiler and windows is the platform.

I wonder if "clang is the host compiler" is just happenstance though and this 
will cause us to pass @thakis' bots but not other testing situations (other 
downstreams, for example). So this may work as a stopgap, but if we can get to 
the bottom of the issue, I think it would be valuable. e.g., perhaps the better 
solution is for cmake to run a configure test to see if crash dumps are 
actually generated (or enabled, if there's a WMI query or something we can 
use), and if not, warn the user and don't define `ENABLE_BACKTRACES` in that 
case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120185

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


[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-03-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

> Sorry, for my own sanity, I've stopped reviewing C++ Core Guideline reviews 
> for their diagnostic behavior until the guideline authors put effort into 
> specifying realistic enforcement guidance.

And how can we continue now? I fear that this is effectively the death of this 
check. :/
Isn't the "make this const" good enough?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D54943#3407789 , @JonasToth wrote:

>> Sorry, for my own sanity, I've stopped reviewing C++ Core Guideline reviews 
>> for their diagnostic behavior until the guideline authors put effort into 
>> specifying realistic enforcement guidance.
>
> And how can we continue now? I fear that this is effectively the death of 
> this check. :/
> Isn't the "make this const" good enough?

Our rule of thumb in clang-tidy when checking against a coding standard is that 
the coding standard is the law as to how the check should work (what it 
diagnoses, what it doesn't diagnose). When the coding standard gives guidance 
that can reasonably be handled another way, we give config options so that 
users can pick the behavior they need to enforce. The trouble is: the C++ Core 
Guidelines rarely have a useful enforcement to suggest and the rules themselves 
are often not sufficiently precise to tease out what to enforce. This puts the 
onus on *us* to decide what the behavior should be, which is inappropriate 
unless the guideline authors are involved in the discussions and reflect the 
decisions in the guidelines. To date, that has (almost?) never happened with 
any C++ Core Guideline checks.

In this specific case, the guideline being checked is 
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es25-declare-an-object-const-or-constexpr-unless-you-want-to-modify-its-value-later-on
 and its enforcement guidance is:

> Look to see if a variable is actually mutated, and flag it if not. 
> Unfortunately, it might be impossible to detect when a non-const was not 
> intended to vary (vs when it merely did not vary).

This is not useful enforcement guidance, so as a code reviewer, I have to spend 
*considerable* time trying to figure out what's reasonable and what's not. I've 
gone through this with basically each C++ Core Guideline check (many of them 
don't even TRY to give enforcement, like this: 
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enforcement-345),
 so this is not at all specific to you or something that's your fault. But 
that's why I no longer am willing to review C++ Core Guideline checks; they're 
a burden to support without the guideline authors active engagement, which has 
never materialized.

So how can we continue now is definitely a good question. I think there's 
plenty of utility in this check already, and so my recommendation would be to 
pull out all mentions of the C++ Core Guidelines (so we don't have to stick 
specifically to what they recommend) and AUTOSAR (see 
https://reviews.llvm.org/D112730#3332366 for details) and move the check to 
`misc-` (I don't see a better module for it at the moment as it's not really 
bugprone and it's not really readability, but I'm not strongly tied to which 
module it lives in). From there, I hope we can converge on the check MUCH 
faster because I think the "make this const" is good enough (and SUPER USEFUL). 
However, I don't know what your goals or requirements are (if you need this to 
adhere to the C++ Core Guidelines specifically), so another option is for the 
other reviewers to sign off on it; I won't actively block the addition of new 
C++ Core Guideline checks.

(Personally, I'm of the opinion we should pull the C++ Core Guidelines modules 
out of clang-tidy and distribute the existing checks amongst the other modules. 
Then we no longer have to worry about what the guidelines say, we can use them 
purely as inspiration for things we feel may be useful to check, but without 
tying ourselves to supporting their document. However, that's a decision which 
requires a far wider audience and is way outside the scope of this check.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418196.
iains added a comment.

another tweak to the second testcase for windows
*sigh* ... I will get the recipe right eventually.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-01.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %/S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%/S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: -x c++-header-unit-header [[TDIR]]/header-unit-01.hh
Index: clang/test/Driver/cxx20-header-units-01.cpp
===
--- clang/test/Driver/cxx20-header-units-01.cpp
+++ clang/test/Driver/cxx20-header-units-01.cpp
@@ -16,4 +16,4 @@
 // CHECK-SYSTEM-SAME: "-x" "c++-system-header" "vector"
 // CHECK-ABS: "-emit-header-unit"
 // CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
-// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
+// CHECK-ABS-SAME: -x c++-header-unit-header [[TDIR]]/header-unit-01.hh
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,13 +189,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -334,9 +335,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1251,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jo

[PATCH] D120306: [clangd] IncludeCleaner: Add support for IWYU pragma private

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

Thanks, this is much nicer!




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:310
 findReferencedFiles(const ReferencedLocations &Locs, const SourceManager &SM,
-llvm::function_ref HeaderResponsible) {
+llvm::function_ref &,
+llvm::StringSet<> &)>

this signature/hook is a bit hard to understand (and undocumented).

I think understanding at least the idea of an IWYU mapping (if not the syntax) 
is in scope for this library, and I think it would be clearer to have a 
function(FileID)> specifically to look up those mappings 
instead

(It's fine that clangd uses the existing CanonicalIncludes mapping for now, but 
I also think when we pull this out as a library, that library will provide some 
facility for recording these mappings, so the interface here shouldn't be too 
high-level)



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:62
+  /// in private headers (private headers have IWYU pragma: private, include
+  /// "public.h"). We store spelling of the public header files here to avoid
+  /// dealing with full filenames and visibility.

Specify whether the spelling includes quotes or not



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:64
+  /// dealing with full filenames and visibility.
+  llvm::StringSet<> PublicHeaders;
 };

Maybe call this ExactSpellings or SpelledUmbrellas? I think public vs private 
isn't the right distinction, stdlib headers and user headers are also often 
public.



Comment at: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp:1640
 
 TEST(DiagnosticsTest, IncludeCleaner) {
   Annotations Test(R"cpp(

Must we test this here (which is AIUI a smoke test of emitting diagnostics) 
instead of in the getUnused tests in IncludeCleanerTests?



Comment at: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp:1690
+  withFix(Fix(Test.range("fix"), "", "remove #include 
directive"))),
+  AllOf(Diag(Test.range("diag_private"),
+ "included header private.h is not used"),

This doesn't seem strictly correct (I assume it fires even if we don't include 
public.h).
There's a problem here, but it isn't that the header is unused. And worse, at 
the moment we can't help you fix this problem, and the suggested change here is 
likely to break the build.

For unused, I think we probably want to mark both as used?
(For missing, we'd only require the public header)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120306

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


[PATCH] D121951: [AMDGPU][OpenCL] Add "amdgpu-no-hostcall-ptr" in Clang codegen pre-COV_5

2022-03-25 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9381
+  M.getTarget().getTargetOpts().CodeObjectVersion != 500) {
+F->addFnAttr("amdgpu-no-hostcall-ptr");
+  }

sameerds wrote:
> The frontend does not need to worry about this attribute. See the comment in 
> the MetadataStreamer. A worthwhile check would be to generate an error if we 
> are able to detect that some hostcall service is being used in OpenCL on 
> code-object-v4 or lower. None exists right now, but we should add the check 
> if such services show up. But those checks are likely to be in a different 
> place. For example, enabling asan on OpenCL for code-object-v4 should result 
> in an error in the place where asan commandline options are parsed.
Should be all opencl, not just kernels. Also < instead of !=?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121951

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


[PATCH] D117522: [clang-tidy] Add modernize-macro-to-enum check

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

Thanks for the discussion on this new check, it LGTM!




Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:47
+CRLF,
+CRLFCR,
+  };

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > LegalizeAdulthood wrote:
> > > aaron.ballman wrote:
> > > > LegalizeAdulthood wrote:
> > > > > aaron.ballman wrote:
> > > > > > LegalizeAdulthood wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > I'm a bit confused by this one as this is not a valid line 
> > > > > > > > ending (it's either three valid line endings or two valid line 
> > > > > > > > endings, depending on how you look at it). Can you explain why 
> > > > > > > > this is needed?
> > > > > > > It's a state machine, where the states are named for what we've 
> > > > > > > seen so far and we're looking for //two// consecutive line 
> > > > > > > endings, not just one.  Does it make sense now?
> > > > > > Thanks, I understood it was a state machine, but it's a confused 
> > > > > > one to me. `\r` was the line ending on Mac Classic, I've not seen 
> > > > > > it used outside of that platform (and I've not seen anyone write 
> > > > > > code for that platform in a long time). So, to me, the only valid 
> > > > > > combinations of line endings to worry about are: `LF LF`; `CRLF 
> > > > > > CRLF`; `CRLF LF`; `LF CRLF`.
> > > > > > 
> > > > > > `LF LF` returns false (Nothing -> LF -> return false)
> > > > > > `CRLF CRLF` returns false (Nothing -> CR -> CRLF -> CRLFCR -> 
> > > > > > return false)
> > > > > > `CRLF LF` returns true (Nothing -> CR -> CRLF -> LF -> finish loop)
> > > > > > `LF CRLF` returns true (Nothing -> LF -> CR -> CRLF -> finish loop)
> > > > > > 
> > > > > > (If you also intend to support Mac Classic line endings for some 
> > > > > > reason, this gets even more complicated.)
> > > > > I was trying to follow "be liberal in what you accept as input and 
> > > > > conservative in what you generate as output" maxim.  I can remove the 
> > > > > `CR` as a line ending case if you think it's too obscure.
> > > > If Clang supports it as a line ending, we probably should too, but... 
> > > > how do we handle CRLF vs "I mixed a CR with an LF by accident" kind of 
> > > > inputs? (Maybe we just treat that as CRLF and if the behavior is bad, 
> > > > the user shouldn't mix their line endings that way; I think that's 
> > > > defensible.) That seems to be similar to the scenario that's confusing 
> > > > me above where the user mixed an LF and CRLF by accident.
> > > Well, as far as Clang is concerned it's all just "whitespace" that gets 
> > > eaten up by the preprocessor.  Actually, that gives me a thought.  A 
> > > preprocessing directive is considered to end at the physical line ending, 
> > > so I should look to see what sort of characters it considers to "end the 
> > > line".
> > > 
> > > For the accidental mix-up, I'm not going to worry about that here.  Your 
> > > input files are assumed to be "well formed".  The worst that happens in 
> > > this check is that two blocks of macros that //look// like they are 
> > > separated by a blank line are considered as a single clump by this check.
> > > 
> > > In other words, the worst that can happen is:
> > >   - Two clumps of macros are considered together.
> > >   - One clump of macros that is discarded because it doesn't follow the 
> > > constraints "taints" an adjacent clump of macros that do follow the 
> > > constraints.
> > > 
> > > Either way, nothing harmful happens to your code.  It will still compile 
> > > and be syntactically and semantically equivalent to what was there before.
> > > 
> > > Actually, that gives me a thought. A preprocessing directive is 
> > > considered to end at the physical line ending, so I should look to see 
> > > what sort of characters it considers to "end the line".
> > 
> > All of `\r`, `\n`, `\r\n` I believe (you can double-check in 
> > `Lexer::LexTokenInternal()`
> > 
> > > Either way, nothing harmful happens to your code. It will still compile 
> > > and be syntactically and semantically equivalent to what was there before.
> > 
> > Oh, that's a very good point, thank you. I think that's reasonable fallback 
> > behavior for these weird edge cases.
> Well. maybe.
> 
> If you look at `Lexer::ReadToEndOfLine` which is used to skip to the end of a 
> preprocessor directive you'll see that it considers the first of `'\r'`, 
> `'\n'` or `'\0'` (end of file) as the end of the "line".  This is around line 
> 2835 of Lexer.cpp in my tree.
Yeah, I saw that as well (that's typically used for error recovery in the 
preprocessor). We also have `Lexer::SkipWhitespace()` which skips all vertical 
whitespace, but not `\0`.


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

https://reviews.llvm.org/D117522

___
cfe-commits ma

[PATCH] D122478: [PowerPC] Add max/min intrinsics to Clang and PPC backend

2022-03-25 Thread Ting Wang via Phabricator via cfe-commits
tingwang created this revision.
tingwang added reviewers: PowerPC, jsji, nemanjai, shchenz.
tingwang added a project: LLVM.
Herald added subscribers: kbarton, hiraditya.
Herald added a project: All.
tingwang requested review of this revision.
Herald added a project: clang.
Herald added subscribers: llvm-commits, cfe-commits.

Add support for __builtin_[max|min] which has below prototype:
A __builtin_max (A1, A2, A3, ...)
All arguments must have the same type; they must all be float, double, or long 
double.

Internally use SelectCC to get the result, and depends on D122462 
 to work properly for ppcf128.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122478

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc.c
  clang/test/Sema/builtins-ppc.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCISelLowering.cpp
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-maxmin.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-maxmin.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-maxmin.ll
@@ -0,0 +1,150 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mcpu=pwr9 -mtriple=powerpc64le-unknown-linux < %s | FileCheck %s
+
+declare ppc_fp128 @llvm.ppc.maxfe(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c, ...)
+define ppc_fp128 @test_maxfe(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c, ppc_fp128 %d) {
+; CHECK-LABEL: test_maxfe:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:fcmpu 0, 6, 4
+; CHECK-NEXT:fcmpu 1, 5, 3
+; CHECK-NEXT:crand 20, 6, 1
+; CHECK-NEXT:cror 20, 5, 20
+; CHECK-NEXT:bc 12, 20, .LBB0_2
+; CHECK-NEXT:  # %bb.1: # %entry
+; CHECK-NEXT:fmr 6, 4
+; CHECK-NEXT:  .LBB0_2: # %entry
+; CHECK-NEXT:fcmpu 0, 6, 2
+; CHECK-NEXT:bc 12, 20, .LBB0_4
+; CHECK-NEXT:  # %bb.3: # %entry
+; CHECK-NEXT:fmr 5, 3
+; CHECK-NEXT:  .LBB0_4: # %entry
+; CHECK-NEXT:fcmpu 1, 5, 1
+; CHECK-NEXT:crand 20, 6, 1
+; CHECK-NEXT:cror 20, 5, 20
+; CHECK-NEXT:bc 12, 20, .LBB0_6
+; CHECK-NEXT:  # %bb.5: # %entry
+; CHECK-NEXT:fmr 6, 2
+; CHECK-NEXT:  .LBB0_6: # %entry
+; CHECK-NEXT:fcmpu 0, 6, 8
+; CHECK-NEXT:bc 12, 20, .LBB0_8
+; CHECK-NEXT:  # %bb.7: # %entry
+; CHECK-NEXT:fmr 5, 1
+; CHECK-NEXT:  .LBB0_8: # %entry
+; CHECK-NEXT:fcmpu 1, 5, 7
+; CHECK-NEXT:crand 20, 6, 1
+; CHECK-NEXT:cror 20, 5, 20
+; CHECK-NEXT:bc 12, 20, .LBB0_10
+; CHECK-NEXT:  # %bb.9: # %entry
+; CHECK-NEXT:fmr 5, 7
+; CHECK-NEXT:  .LBB0_10: # %entry
+; CHECK-NEXT:bc 12, 20, .LBB0_12
+; CHECK-NEXT:  # %bb.11: # %entry
+; CHECK-NEXT:fmr 6, 8
+; CHECK-NEXT:  .LBB0_12: # %entry
+; CHECK-NEXT:fmr 1, 5
+; CHECK-NEXT:fmr 2, 6
+; CHECK-NEXT:blr
+entry:
+  %0 = call ppc_fp128 (ppc_fp128, ppc_fp128, ppc_fp128, ...) @llvm.ppc.maxfe(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c, ppc_fp128 %d)
+  ret ppc_fp128 %0
+}
+
+declare double @llvm.ppc.maxfl(double %a, double %b, double %c, ...)
+define double @test_maxfl(double %a, double %b, double %c, double %d) {
+; CHECK-LABEL: test_maxfl:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:xsmaxcdp 0, 3, 2
+; CHECK-NEXT:xsmaxcdp 0, 0, 1
+; CHECK-NEXT:xsmaxcdp 1, 0, 4
+; CHECK-NEXT:blr
+entry:
+  %0 = call double (double, double, double, ...) @llvm.ppc.maxfl(double %a, double %b, double %c, double %d)
+  ret double %0
+}
+
+declare float @llvm.ppc.maxfs(float %a, float %b, float %c, ...)
+define float @test_maxfs(float %a, float %b, float %c, float %d) {
+; CHECK-LABEL: test_maxfs:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:xsmaxcdp 0, 3, 2
+; CHECK-NEXT:xsmaxcdp 0, 0, 1
+; CHECK-NEXT:xsmaxcdp 1, 0, 4
+; CHECK-NEXT:blr
+entry:
+  %0 = call float (float, float, float, ...) @llvm.ppc.maxfs(float %a, float %b, float %c, float %d)
+  ret float %0
+}
+
+declare ppc_fp128 @llvm.ppc.minfe(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c, ...)
+define ppc_fp128 @test_minfe(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c, ppc_fp128 %d) {
+; CHECK-LABEL: test_minfe:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:fcmpu 0, 6, 4
+; CHECK-NEXT:fcmpu 1, 5, 3
+; CHECK-NEXT:crand 20, 6, 0
+; CHECK-NEXT:cror 20, 4, 20
+; CHECK-NEXT:bc 12, 20, .LBB3_2
+; CHECK-NEXT:  # %bb.1: # %entry
+; CHECK-NEXT:fmr 6, 4
+; CHECK-NEXT:  .LBB3_2: # %entry
+; CHECK-NEXT:fcmpu 0, 6, 2
+; CHECK-NEXT:bc 12, 20, .LBB3_4
+; CHECK-NEXT:  # %bb.3: # %entry
+; CHECK-NEXT:fmr 5, 3
+; CHECK-NEXT:  .LBB3_4: # %entry
+; CHECK-NEXT:fcmpu 1, 5, 1
+; CHECK-NEXT:crand 20, 6, 0
+; CHECK-NEXT:cror 20, 4, 20
+; CHECK-NEXT:bc 12, 20, .LBB3_6
+; CHECK-NEXT:  # %bb.5: # %entry
+; CHECK-NEXT:fmr 6, 2
+; CHECK-NEXT:  .L

[clang-tools-extra] 72864d9 - [pseudo] Use box-drawing chars to prettify debug dumps. NFC

2022-03-25 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-03-25T14:17:38+01:00
New Revision: 72864d9bfec929b2427981d99c2ac67ff5fcfe19

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

LOG: [pseudo] Use box-drawing chars to prettify debug dumps. NFC

Added: 


Modified: 
clang-tools-extra/pseudo/lib/Forest.cpp
clang-tools-extra/pseudo/unittests/ForestTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/Forest.cpp 
b/clang-tools-extra/pseudo/lib/Forest.cpp
index 41b9be8a8d30f..6948422a23a6e 100644
--- a/clang-tools-extra/pseudo/lib/Forest.cpp
+++ b/clang-tools-extra/pseudo/lib/Forest.cpp
@@ -46,15 +46,23 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
   };
   CountVisits(this);
 
+  // The box-drawing characters that should be added as a child is rendered.
+  struct LineDecoration {
+std::string Prefix; // Prepended to every line.
+llvm::StringRef First;  // added to the child's line.
+llvm::StringRef Subsequent; // added to descendants' lines.
+  };
+
   // We print a "#" for nonterminal forest nodes that are being dumped
   // multiple times.
   llvm::DenseMap ReferenceIds;
   std::string Result;
   constexpr Token::Index KEnd = std::numeric_limits::max();
-  std::function)>
-  Dump = [&](const ForestNode *P, unsigned Level, Token::Index End,
- llvm::Optional ElidedParent) {
+  std::function,
+ LineDecoration &LineDec)>
+  Dump = [&](const ForestNode *P, Token::Index End,
+ llvm::Optional ElidedParent,
+ LineDecoration LineDec) {
 llvm::ArrayRef Children;
 auto EndOfElement = [&](size_t ChildIndex) {
   return ChildIndex + 1 == Children.size()
@@ -72,18 +80,19 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
   if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
   EndOfElement(I) == End) {
 return Dump(
-Children[I], Level, End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()));
+Children[I], End,
+/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+LineDec);
   }
   }
 }
 
-// FIXME: pretty ascii trees
 if (End == KEnd)
   Result += llvm::formatv("[{0,3}, end) ", P->startTokenIndex());
 else
   Result += llvm::formatv("[{0,3}, {1,3}) ", P->startTokenIndex(), 
End);
-Result.append(2 * Level, ' ');
+Result += LineDec.Prefix;
+Result += LineDec.First;
 if (ElidedParent.hasValue()) {
   Result += G.symbolName(*ElidedParent);
   Result += "~";
@@ -99,12 +108,23 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
 }
 Result.push_back('\n');
 
-++Level;
-for (size_t I = 0; I < Children.size(); ++I)
-  Dump(Children[I], Level,
-   P->kind() == Sequence ? EndOfElement(I) : End, llvm::None);
+auto OldPrefixSize = LineDec.Prefix.size();
+LineDec.Prefix += LineDec.Subsequent;
+for (size_t I = 0; I < Children.size(); ++I) {
+  if (I == Children.size() - 1) {
+LineDec.First = "└─";
+LineDec.Subsequent = "  ";
+  } else {
+LineDec.First = "├─";
+LineDec.Subsequent = "│ ";
+  }
+  Dump(Children[I], P->kind() == Sequence ? EndOfElement(I) : End,
+   llvm::None, LineDec);
+}
+LineDec.Prefix.resize(OldPrefixSize);
   };
-  Dump(this, 0, KEnd, llvm::None);
+  LineDecoration LineDec;
+  Dump(this, KEnd, llvm::None, LineDec);
   return Result;
 }
 

diff  --git a/clang-tools-extra/pseudo/unittests/ForestTest.cpp 
b/clang-tools-extra/pseudo/unittests/ForestTest.cpp
index b9bd08d78288a..a734a8f7f8616 100644
--- a/clang-tools-extra/pseudo/unittests/ForestTest.cpp
+++ b/clang-tools-extra/pseudo/unittests/ForestTest.cpp
@@ -71,19 +71,20 @@ TEST_F(ForestTest, DumpBasic) {
 ruleFor("id-expression"), {&T[2]});
 
   const auto *Add =
-  &Arena.createSequence(symbol("add-expression"), 
ruleFor("add-expression"), {Left, &T[1], Right});
+  &Arena.createSequence(symbol("add-expression"), 
ruleFor("add-expression"),
+{Left, &T[1], Right});
   EXPECT_EQ(Add->dumpRecursive(*G, true),
 "[  0, end) add-expression := id-expression + id-expression\n"
-"[  0,   1)   id-expression~IDENTIFIER := tok[0]\n"
-"[  1,   2)   + := tok[1]\n"
-"[  2, end)   id-expression~IDENTIFIER := tok[2]\n");
+"[  0,   1) ├─id-expression~IDENTIFIER := tok[0]\n"
+"[  1,   2) ├─+ := tok[1]\

[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 418206.
ymandel added a comment.

remove stray comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122231

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1710,6 +1710,91 @@
  UnorderedElementsAre(Pair("check", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, ValueOrComparison) {
+  // Pointers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(nullptr) != nullptr) {
+opt.value();
+/*[[check-ptrs-1]]*/
+  } else {
+opt.value();
+/*[[check-ptrs-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ptrs-1", "safe"),
+   Pair("check-ptrs-2", "unsafe: input.cc:10:9")));
+
+  // Integers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(0) != 0) {
+opt.value();
+/*[[check-ints-1]]*/
+  } else {
+opt.value();
+/*[[check-ints-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ints-1", "safe"),
+   Pair("check-ints-2", "unsafe: input.cc:10:9")));
+
+  // Strings.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+namespace std {
+  struct string {
+bool empty();
+  };
+}
+
+void target() {
+  $ns::$optional opt;
+  if (!opt.value_or("").empty()) {
+opt.value();
+/*[[check-strings-1]]*/
+  } else {
+opt.value();
+/*[[check-strings-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-strings-1", "safe"),
+   Pair("check-strings-2", "unsafe: input.cc:16:9")));
+
+  // Pointer-to-optional.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  auto *opt_p = &opt;
+  if (opt_p->value_or(0) != 0) {
+opt_p->value();
+/*[[check-pto-1]]*/
+  } else {
+opt_p->value();
+/*[[check-pto-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-pto-1", "safe"),
+   Pair("check-pto-2", "unsafe: input.cc:11:9")));
+}
+
 TEST_P(UncheckedOptionalAccessTest, Emplace) {
   ExpectLatticeChecksFor(R"(
 #include "unchecked_optional_access_test.h"
@@ -2008,5 +2093,4 @@
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
 // - invalidation (passing optional by non-const reference/pointer)
-// - `value_or(nullptr) != nullptr`, `value_or(0) != 0`, `value_or("").empty()`
 // - nested `optional` values
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -113,6 +113,40 @@
   hasArgument(1, hasOptionalType()));
 }
 
+constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall";
+
+auto isValueOrStringEmptyCall() {
+  // `opt.value_or("").empty()`
+  return cxxMemberCallExpr(
+  callee(cxxMethodDecl(hasName("empty"))),
+  onImplicitObjectArgument(ignoringImplicit(
+  cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+callee(cxxMethodDecl(hasName("value_or"),
+ ofClass(optionalClass(,
+hasArgument(0, stringLiteral(hasSize(0
+  .bind(ValueOrCallID;
+}
+
+auto isValueOrCondition() {
+  auto ComparesToSame = [](ast_matchers::internal::Matcher Arg) {
+return hasOperands(
+cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+  callee(cxxMethodDecl(hasName("value_or"),
+   ofClass(optionalClass(,
+  hasArgument(0, Arg))
+.bind(ValueOrCallID),
+ignoringImplicit(Arg));
+  };
+
+  // `opt.value_or(nullptr) != nullptr` and `opt.value_or(0) != 0`. Ideally,
+  // we'd support this pattern for any expression, but the AST does not have a
+  // generic expression comparison facility, so we specialize to common cases
+

[PATCH] D122179: Serialize PragmaAssumeNonNullLoc to support preambles

2022-03-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks, this looks really solid now!




Comment at: clang/lib/Lex/PPLexerChange.cpp:430
 
-  // Complain about reaching a true EOF within assume_nonnull.
+  // Complain about reaching a true EOF.
+  //

revert comment change? this is still specific to assume_nonnull


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122179

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


[PATCH] D122078: [clang-tidy] Ignore concepts in `misc-redundant-expression`

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: alexfh, sammccall.
aaron.ballman added subscribers: sammccall, alexfh.
aaron.ballman added a comment.

Thanks for the fix, can you also add a release note for it?

I'm a bit worried about using `hasAncestor()` for this; that has a tendency to 
do surprising things in addition to being expensive because it's very greedy. 
However, I can't see a situation in which it's going to be wrong, because the 
body of the requires expression is always unevaluated (so we really don't need 
to worry about nonsense like defining a lambda in the requires body, and then 
defining a class in the lambda, and having a redundant expression we care to 
diagnose in a member function of that class).

@alexfh or @sammccall -- do you see any concerns with this use of 
`hasAncestor()`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122078

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 418205.
ymandel added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122231

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1710,6 +1710,91 @@
  UnorderedElementsAre(Pair("check", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, ValueOrComparison) {
+  // Pointers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(nullptr) != nullptr) {
+opt.value();
+/*[[check-ptrs-1]]*/
+  } else {
+opt.value();
+/*[[check-ptrs-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ptrs-1", "safe"),
+   Pair("check-ptrs-2", "unsafe: input.cc:10:9")));
+
+  // Integers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(0) != 0) {
+opt.value();
+/*[[check-ints-1]]*/
+  } else {
+opt.value();
+/*[[check-ints-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ints-1", "safe"),
+   Pair("check-ints-2", "unsafe: input.cc:10:9")));
+
+  // Strings.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+namespace std {
+  struct string {
+bool empty();
+  };
+}
+
+void target() {
+  $ns::$optional opt;
+  if (!opt.value_or("").empty()) {
+opt.value();
+/*[[check-strings-1]]*/
+  } else {
+opt.value();
+/*[[check-strings-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-strings-1", "safe"),
+   Pair("check-strings-2", "unsafe: input.cc:16:9")));
+
+  // Pointer-to-optional.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  auto *opt_p = &opt;
+  if (opt_p->value_or(0) != 0) {
+opt_p->value();
+/*[[check-pto-1]]*/
+  } else {
+opt_p->value();
+/*[[check-pto-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-pto-1", "safe"),
+   Pair("check-pto-2", "unsafe: input.cc:11:9")));
+}
+
 TEST_P(UncheckedOptionalAccessTest, Emplace) {
   ExpectLatticeChecksFor(R"(
 #include "unchecked_optional_access_test.h"
@@ -2008,5 +2093,4 @@
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
 // - invalidation (passing optional by non-const reference/pointer)
-// - `value_or(nullptr) != nullptr`, `value_or(0) != 0`, `value_or("").empty()`
 // - nested `optional` values
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -113,6 +113,49 @@
   hasArgument(1, hasOptionalType()));
 }
 
+constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall";
+
+auto isValueOrStringEmptyCall() {
+  // `opt.value_or("").empty()`
+  // (opt.has_value /\ opt.value == "") v !opt.has_value
+  // So, !((opt.has_value /\ opt.value == "") v !opt.has_value)
+  //  = !(opt.has_value /\ opt.value == "") /\ opt.has_value
+  //  = (!opt.has_value v opt.value != "") /\ opt.has_value
+  //  = False v (opt.value != "" /\ opt.has_value)
+  //  = opt.value != "" /\ opt.has_value
+  //  = opt.has_value /\ opt.value != ""
+  return cxxMemberCallExpr(
+  callee(cxxMethodDecl(hasName("empty"))),
+  onImplicitObjectArgument(ignoringImplicit(
+  cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+callee(cxxMethodDecl(hasName("value_or"),
+ ofClass(optionalClass(,
+hasArgument(0, stringLiteral(hasSize(0
+  .bind(ValueOrCallID;
+}
+
+auto isValueOrCondition() {
+  auto ComparesToSame = [](ast_matchers::internal::Matcher Arg) {
+return hasOperands(
+cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+  callee(cxxMethodDecl(hasName("value_or"),
+   ofClass(op

[PATCH] D122344: [clang][driver] Disable non-functional --version option for clang -cc1

2022-03-25 Thread Nico Weber via Phabricator via cfe-commits
thakis accepted this revision.
thakis 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/D122344/new/

https://reviews.llvm.org/D122344

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


[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 6 inline comments as done and an inline comment as not done.
ymandel added a comment.

Thanks for the detailed review!




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:119
+  auto NonEmptyStringOptional = unaryOperator(
+  hasOperatorName("!"),
+  hasUnaryOperand(cxxMemberCallExpr(

sgatev wrote:
> Why handle negation here? Would it work for `if (opt.value_or("").empty()) { 
> ... } else { opt.value(); }`?
The negation is a simpler predicate, but you're right that it's too specific. 
I've rewritten the code to drop the constraint and handle the more general 
`opt.value_or("").empty()`. The new code also encodes a more precise 
relationship in the logic, per Gabor's comments below about the implication in 
the other direction. It also now directly attaches the formula to the value, 
rather than dropping an implication in the flow conditions.

Overall, I think the new approach is an improvement, but please let me know if 
you disagree.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:148
+anyOf(ComparesToSame(cxxNullPtrLiteralExpr()),
+  
ComparesToSame(integerLiteral(equals(0)));
+}

sgatev wrote:
> Why `0`? How about `opt_p->value_or(21) != 21`?
This is addressed in the comment, but do you think we should add a FIXME to 
support some amount of expression comparision? Integers, floats, bools and 
variables would be an easy place to start, for example.  But, we'd need to drop 
into regular code -- the matchers can't express that kind of constraint.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:269
+// the implication `(opt.value_or(X) != X) => opt.hasValue()`.
+State.Env.addToFlowCondition(
+State.Env.makeImplication(*ComparisonExprValue, *HasValueVal));

xazax.hun wrote:
> There is an implication in the reverse direction as well. In case we know the 
> optional is empty, we can prune one of the branches from the analysis. Is it 
> possible to implement that with the current status of the framework?
Yes, good point! Please see my response to Stanislav above. I think the new 
version handles this by modeling the value_or directly, rather than dropping in 
an implication.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:482
+  .CaseOf(
+  isValueOrCondition("ValueOrCall"),
+  [](const clang::Expr *E, const MatchFinder::MatchResult &Result,

sgatev wrote:
> Why not hard-code this in the `isValueOrCondition` matcher?
Safety/hygiene. It's easier to see that the ID to which the node is bound is 
the same that's being used in `getNodeAs`. An alternative which I often use is 
to use a (static) global constant, so I've changed to that.



Comment at: 
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp:1722
+  if (opt.value_or(nullptr) != nullptr) {
+return *opt;
+/*[[check-ptrs-1]]*/

sgatev wrote:
> Is the `return` important? I think having `void` return type would be 
> simpler. Same comment for the cases below.
Totally. Thanks for pointing that out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122231

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


[PATCH] D122155: Add warning when eval-method is set in the presence of value unsafe floating-point calculations.

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticFrontendKinds.td:50-53
+def warn_eval_method_setting_via_option_in_value_unsafe_context : Warning<
+"setting the eval method via '-ffp-eval-method' has not effect when 
numeric "
+"results of floating-point calculations aren't value-safe.">,
+InGroup;

aaron.ballman wrote:
> zahiraam wrote:
> > aaron.ballman wrote:
> > > andrew.w.kaylor wrote:
> > > > zahiraam wrote:
> > > > > aaron.ballman wrote:
> > > > > > Unless you have a strong reason for this to be a warning, this 
> > > > > > seems like a situation we should diagnose as an error with a much 
> > > > > > clearer message.
> > > > > May  be @andrew.w.kaylor would weigh in on this?
> > > > I was going to say that for the command line option we could just issue 
> > > > a warning saying that the later option overrides the earlier, but it's 
> > > > a bit complicated to sort out what that would mean if the eval method 
> > > > follows a fast-math option and it might not always be what the user 
> > > > intended. So, I guess I'd agree that it should be an error.
> > > > 
> > > > For the case with pragmas, the model I'd follow is the mixing of 
> > > > #pragma float_control(except, on) with a fast-math mode or #pragma 
> > > > float_control(precise, off) with a non-ignore exception mode. In both 
> > > > those cases we issue an error.
> > > > For the case with pragmas, the model I'd follow is the mixing of 
> > > > #pragma float_control(except, on) with a fast-math mode or #pragma 
> > > > float_control(precise, off) with a non-ignore exception mode. In both 
> > > > those cases we issue an error.
> > > 
> > > Good catch, I think that's a good approach as well.
> > I think i  will have the issue with the order of appearance of the options 
> > on the command line. 
> > // RUN: -freciprocal-math -mreassociate   -ffp-eval-method=source 
> > and
> > // RUN: -mreassociate -ffp-eval-method=source 
> > 
> > will depend on which order I will test for 
> > LangOpts.ApproxFunc/AllowFPReasson/AllowRecip being used or not?
> > 
> > The run lines above might give the same diagnostic. Unless I do something 
> > really complicated to check the order of the options on the command line?
> > I think i will have the issue with the order of appearance of the options 
> > on the command line.
> 
> You shouldn't -- you should be able to test the language options after the 
> command line was fully parsed. See `FixupInvocation()` in 
> `CompilerInvocation.cpp`.
I still prefer the suggested wording I had originally: `"'-ffp-eval-method' 
cannot be used with '%0'"`; I think it's a good generalization but still 
sufficiently informative. WDYT?



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6480
+  "eval method setting via '%0' cannot be used with "
+  "'pragma_clang_fp_eval_reassociate'">, InGroup;
+def warn_pragma_clang_fp_eval_method_used_with_fapprox_func : Warning<

I'm not certain what `pragma_clang_fp_eval_reassociate` is?



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6481-6489
+def warn_pragma_clang_fp_eval_method_used_with_fapprox_func : Warning<
+  "'#pragma clang fp eval_method' cannot be used with 'fapprox_func'">,
+  InGroup;
+def warn_pragma_clang_fp_eval_method_used_with_mreassociate : Warning<
+  "'#pragma clang fp eval_method' cannot be used with 'mreassociate'">,
+  InGroup;
+def warn_pragma_clang_fp_eval_method_used_with_freciprocal : Warning<

These should be combined into one diagnostic, which I believe we wanted to be 
an error instead of a warning. Also, because this will trigger for pragma use 
OR command line argument use, I think we need to be more generalize about what 
it cannot be used with. e.g., `'#pragma clang fp eval_method' cannot be used 
when %select{approximate functions|reassociation|reciprocal whatever}0 is 
enabled` or something along those lines (I'm hoping @andrew.w.kaylor can help 
figure out what the best terminology is here, as I'm not super familiar with 
those floating-point features).


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

https://reviews.llvm.org/D122155

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


[PATCH] D122155: Add warning when eval-method is set in the presence of value unsafe floating-point calculations.

2022-03-25 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 418210.

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

https://reviews.llvm.org/D122155

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/test/Sema/eval-method-with-unsafe-math.c

Index: clang/test/Sema/eval-method-with-unsafe-math.c
===
--- /dev/null
+++ clang/test/Sema/eval-method-with-unsafe-math.c
@@ -0,0 +1,82 @@
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu  \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu  -freciprocal-math \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=WARN-RECPR,WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu  -mreassociate \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=WARN-REC,WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu  -fapprox-func \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=WARN-FUNC,WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -freciprocal-math -mreassociate -verify \
+// RUN: %s 2>&1 | FileCheck %s --check-prefixes=WARN-REC,WARN-RECPR,WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -freciprocal-math -mreassociate -fapprox-func \
+// RUN: -verify %s 2>&1 \
+// RUN: | FileCheck %s --check-prefixes=WARN-FUNC,WARN-REC,WARN-RECPR,WARN-PRGM
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -fapprox-func -ffp-eval-method=source \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=CHECK-FUNC
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -mreassociate -ffp-eval-method=source \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=CHECK-ASSOC
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -freciprocal-math -ffp-eval-method=source \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=CHECK-RECPR
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -freciprocal-math -mreassociate \
+// RUN: -ffp-eval-method=source \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=CHECK-ASSOC,CHECK-RECPR
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -freciprocal-math -mreassociate -fapprox-func \
+// RUN: -ffp-eval-method=source -verify %s 2>&1 \
+// RUN: | FileCheck %s --check-prefixes=CHECK-ASSOC,CHECK-RECPR,CHECK-FUNC
+
+// RUN: not %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -ffp-eval-method=source \
+// RUN: -verify %s 2>&1 | FileCheck %s --check-prefixes=WARN-FUNC-OPT,WARN-PRGM
+
+// CHECK-FUNC: (frontend): 'fapprox-func' produces inaccurate arithmetic results. It is illegal when 'ffp-eval-method' is set.
+// CHECK-ASSOC: (frontend): 'mreassociate' produces inaccurate arithmetic results. It is illegal when 'ffp-eval-method' is set.
+// CHECK-RECPR: (frontend): 'freciprocal' produces inaccurate arithmetic results. It is illegal when 'ffp-eval-method' is set.
+
+// expected-no-diagnostics
+
+float f1(float a, float b, float c) {
+  a = b + c;
+  return a * b + c;
+}
+
+float f2(float a, float b, float c) {
+  // WARN-FUNC-OPT: eval method setting via 'option ffp-eval-method' cannot be used with 'pragma_clang_fp_eval_reassociate'
+#pragma clang fp reassociate (on)
+  return (a + b) + c;
+}
+
+float f3(float a, float b, float c) {
+#pragma clang fp reassociate (off)
+  return (a - b) - c;
+}
+
+float f4(float a, float b, float c) {
+#pragma clang fp eval_method (double)
+  // WARN-FUNC: '#pragma clang fp eval_method' cannot be used with 'fapprox_func'
+  // WARN-REC: '#pragma clang fp eval_method' cannot be used with 'mreassociate'
+  // WARN-RECPR: '#pragma clang fp eval_method' cannot be used with 'freciprocal'
+  // WARN-PRGM: eval method setting via '#pragma clang fp eval_method' cannot be used with 'pragma_clang_fp_eval_reassociate'
+#pragma clang fp reassociate (on)
+  return (a * c) - (b * c);
+}
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -486,6 +486,15 @@
 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
 break;
   }
+  if (getLangOpts().ApproxFunc)
+Diag(Loc, diag::warn_pragma_clang_fp_eval_method_used_with_fapprox_func)
+<< "#pragma clang fp eval_method";
+  if (getLangOpts().AllowFPReassoc)
+Diag(Lo

[PATCH] D122231: [clang][dataflow] Add support for `value_or` in a comparison.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 418209.
ymandel marked an inline comment as done.
ymandel added a comment.

adjust logical formula


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122231

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1710,6 +1710,91 @@
  UnorderedElementsAre(Pair("check", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, ValueOrComparison) {
+  // Pointers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(nullptr) != nullptr) {
+opt.value();
+/*[[check-ptrs-1]]*/
+  } else {
+opt.value();
+/*[[check-ptrs-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ptrs-1", "safe"),
+   Pair("check-ptrs-2", "unsafe: input.cc:10:9")));
+
+  // Integers.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  if (opt.value_or(0) != 0) {
+opt.value();
+/*[[check-ints-1]]*/
+  } else {
+opt.value();
+/*[[check-ints-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-ints-1", "safe"),
+   Pair("check-ints-2", "unsafe: input.cc:10:9")));
+
+  // Strings.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+namespace std {
+  struct string {
+bool empty();
+  };
+}
+
+void target() {
+  $ns::$optional opt;
+  if (!opt.value_or("").empty()) {
+opt.value();
+/*[[check-strings-1]]*/
+  } else {
+opt.value();
+/*[[check-strings-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-strings-1", "safe"),
+   Pair("check-strings-2", "unsafe: input.cc:16:9")));
+
+  // Pointer-to-optional.
+  ExpectLatticeChecksFor(
+  R"code(
+#include "unchecked_optional_access_test.h"
+
+void target() {
+  $ns::$optional opt;
+  auto *opt_p = &opt;
+  if (opt_p->value_or(0) != 0) {
+opt_p->value();
+/*[[check-pto-1]]*/
+  } else {
+opt_p->value();
+/*[[check-pto-2]]*/
+  }
+}
+  )code",
+  UnorderedElementsAre(Pair("check-pto-1", "safe"),
+   Pair("check-pto-2", "unsafe: input.cc:11:9")));
+}
+
 TEST_P(UncheckedOptionalAccessTest, Emplace) {
   ExpectLatticeChecksFor(R"(
 #include "unchecked_optional_access_test.h"
@@ -2008,5 +2093,4 @@
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
 // - invalidation (passing optional by non-const reference/pointer)
-// - `value_or(nullptr) != nullptr`, `value_or(0) != 0`, `value_or("").empty()`
 // - nested `optional` values
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -113,6 +113,40 @@
   hasArgument(1, hasOptionalType()));
 }
 
+constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall";
+
+auto isValueOrStringEmptyCall() {
+  // `opt.value_or("").empty()`
+  return cxxMemberCallExpr(
+  callee(cxxMethodDecl(hasName("empty"))),
+  onImplicitObjectArgument(ignoringImplicit(
+  cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+callee(cxxMethodDecl(hasName("value_or"),
+ ofClass(optionalClass(,
+hasArgument(0, stringLiteral(hasSize(0
+  .bind(ValueOrCallID;
+}
+
+auto isValueOrCondition() {
+  auto ComparesToSame = [](ast_matchers::internal::Matcher Arg) {
+return hasOperands(
+cxxMemberCallExpr(on(expr(unless(cxxThisExpr(,
+  callee(cxxMethodDecl(hasName("value_or"),
+   ofClass(optionalClass(,
+  hasArgument(0, Arg))
+.bind(ValueOrCallID),
+ignoringImplicit(Arg));
+  };
+
+  // `opt.value_or(nullptr) != nullptr` and `opt.value_or(0) != 0`. Ideally,
+  // we'd support this pattern for any expression, but the AST does not have a
+  // generic expression comparison f

[PATCH] D122478: [PowerPC] Add max/min intrinsics to Clang and PPC backend

2022-03-25 Thread Ting Wang via Phabricator via cfe-commits
tingwang added a comment.

Since this is compatibility support, I'm trying to match the result from XLC in 
scenarios where there is all kinds of QNaN, SNaN, +/-Infinity, +/-ZERO. 
Currently maxfl and maxfs still give different result compared with XLC in 
above scenario. This is one thing I'm still looking into.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122478

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


[PATCH] D122078: [clang-tidy] Ignore concepts in `misc-redundant-expression`

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

I don't actually know a great deal about matcher performance :-( I wish I did.
I think this is pretty much in line with how plenty of check matchers already 
work though, in particular unless(isInTemplateInstantiation()) is basically the 
same thing and is used in many places including this check.
So I wouldn't be particularly worried.

(Obviously from first principles you'd prefer to prune the subtree rather than 
match within it and then walk up the parent chain, but I don't think matchers 
supports this pattern well).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122078

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


[PATCH] D122078: [clang-tidy] Ignore concepts in `misc-redundant-expression`

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

In D122078#3407981 , @sammccall wrote:

> I don't actually know a great deal about matcher performance :-( I wish I did.
> I think this is pretty much in line with how plenty of check matchers already 
> work though, in particular unless(isInTemplateInstantiation()) is basically 
> the same thing and is used in many places including this check.
> So I wouldn't be particularly worried.
>
> (Obviously from first principles you'd prefer to prune the subtree rather 
> than match within it and then walk up the parent chain, but I don't think 
> matchers supports this pattern well).

Okie dokie, thanks for weighing in! This LGTM (feel free to add the release 
note when landing). If @alexfh has some technical concerns with 
`hasAncestor()`, we can always revert and address them once we know more.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122078

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


[PATCH] D120589: [Clang] Implement decltype(auto)(x) from P0849R2

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: rsmith, clang-language-wg.
aaron.ballman added a comment.
Herald added a project: All.

I'm adding more reviewers for a wider audience on this topic. Personally, I 
don't think we should support this extension. EWG voted pretty strongly against 
it: 0/3/7/6/1 
(https://github.com/cplusplus/papers/issues/293#issuecomment-585662477) and 
Clang has a policy that language extensions should have representation within 
the appropriate governing body 
(https://clang.llvm.org/get_involved.html#criteria). Given that the governing 
body for this rejected it and there's not a significant user benefit to 
supporting it, I think we shouldn't step into the C++ design space for this 
extension. However, I have no idea how others feel.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120589

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


[PATCH] D120589: [Clang] Implement decltype(auto)(x) from P0849R2

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

In D120589#3408015 , @aaron.ballman 
wrote:

> I'm adding more reviewers for a wider audience on this topic. Personally, I 
> don't think we should support this extension. EWG voted pretty strongly 
> against it: 0/3/7/6/1 
> (https://github.com/cplusplus/papers/issues/293#issuecomment-585662477) and 
> Clang has a policy that language extensions should have representation within 
> the appropriate governing body 
> (https://clang.llvm.org/get_involved.html#criteria). Given that the governing 
> body for this rejected it and there's not a significant user benefit to 
> supporting it, I think we shouldn't step into the C++ design space for this 
> extension. However, I have no idea how others feel.

I tend to agree, EWG seemed quite against this (though sadly, it looks like the 
minutes never got uploaded to the wiki).  For something to fail the 'is a 
problem worth solving' (aka, the 'author should do more work' vote) it means 
the room was quite against it.  While I can see the attraction of this, I don't 
think it is a good feature.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120589

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


[PATCH] D121824: [clang] Do not crash on arrow operator on dependent type.

2022-03-25 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz updated this revision to Diff 418219.
adamcz marked an inline comment as done.
adamcz added a comment.

added a comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121824

Files:
  clang/lib/Sema/TreeTransform.h
  clang/test/SemaCXX/arrow-operator.cpp


Index: clang/test/SemaCXX/arrow-operator.cpp
===
--- clang/test/SemaCXX/arrow-operator.cpp
+++ clang/test/SemaCXX/arrow-operator.cpp
@@ -65,3 +65,51 @@
 }
 
 } // namespace arrow_suggest
+
+namespace no_crash_dependent_type {
+
+template 
+struct A {
+  void call();
+  A *operator->();
+};
+
+template 
+void foo() {
+  // The "requires an initializer" error seems unnecessary.
+  A &x = blah[7]; // expected-error {{use of undeclared identifier 
'blah'}} \
+// expected-error {{requires an initializer}}
+  // x is dependent.
+  x->call();
+}
+
+void test() {
+  foo(); // expected-note {{requested here}}
+}
+
+} // namespace no_crash_dependent_type
+
+namespace clangd_issue_1073_no_crash_dependent_type {
+
+template  struct Ptr {
+  T *operator->();
+};
+
+struct Struct {
+  int len;
+};
+
+template 
+struct TemplateStruct {
+  Ptr val(); // expected-note {{declared here}}
+};
+
+template 
+void templateFunc(const TemplateStruct &ts) {
+  Ptr ptr = ts.val(); // expected-error {{function is not marked 
const}}
+  auto foo = ptr->len;
+}
+
+template void templateFunc<0>(const TemplateStruct<0> &); // expected-note 
{{requested here}}
+
+} // namespace clangd_issue_1073_no_crash_dependent_type
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14757,6 +14757,10 @@
   return getSema().CreateBuiltinArraySubscriptExpr(
   First, Callee->getBeginLoc(), Second, OpLoc);
   } else if (Op == OO_Arrow) {
+// It is possible that the type refers to a RecoveryExpr created earlier
+// in the tree transformation.
+if (First->getType()->isDependentType())
+  return ExprError();
 // -> is never a builtin operation.
 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   } else if (Second == nullptr || isPostIncDec) {


Index: clang/test/SemaCXX/arrow-operator.cpp
===
--- clang/test/SemaCXX/arrow-operator.cpp
+++ clang/test/SemaCXX/arrow-operator.cpp
@@ -65,3 +65,51 @@
 }
 
 } // namespace arrow_suggest
+
+namespace no_crash_dependent_type {
+
+template 
+struct A {
+  void call();
+  A *operator->();
+};
+
+template 
+void foo() {
+  // The "requires an initializer" error seems unnecessary.
+  A &x = blah[7]; // expected-error {{use of undeclared identifier 'blah'}} \
+// expected-error {{requires an initializer}}
+  // x is dependent.
+  x->call();
+}
+
+void test() {
+  foo(); // expected-note {{requested here}}
+}
+
+} // namespace no_crash_dependent_type
+
+namespace clangd_issue_1073_no_crash_dependent_type {
+
+template  struct Ptr {
+  T *operator->();
+};
+
+struct Struct {
+  int len;
+};
+
+template 
+struct TemplateStruct {
+  Ptr val(); // expected-note {{declared here}}
+};
+
+template 
+void templateFunc(const TemplateStruct &ts) {
+  Ptr ptr = ts.val(); // expected-error {{function is not marked const}}
+  auto foo = ptr->len;
+}
+
+template void templateFunc<0>(const TemplateStruct<0> &); // expected-note {{requested here}}
+
+} // namespace clangd_issue_1073_no_crash_dependent_type
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14757,6 +14757,10 @@
   return getSema().CreateBuiltinArraySubscriptExpr(
   First, Callee->getBeginLoc(), Second, OpLoc);
   } else if (Op == OO_Arrow) {
+// It is possible that the type refers to a RecoveryExpr created earlier
+// in the tree transformation.
+if (First->getType()->isDependentType())
+  return ExprError();
 // -> is never a builtin operation.
 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   } else if (Second == nullptr || isPostIncDec) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121824: [clang] Do not crash on arrow operator on dependent type.

2022-03-25 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added a comment.

Thanks for all the comments!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121824

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


[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418220.
iains added a comment.

we need the quotes around the components.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %/S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%/S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -189,13 +189,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -334,9 +335,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1246,6 +1251,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treating them as PCH, implicit modules or C++20 ones.
+  // TODO: inferring the mode like this seems fragile (it meets the objective
+  // of not requiring anything new for operation, however).
+  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
+  ModulesModeCXX20 =
+  !Args.hasArg(options::OPT_fmodules) && Std &&
+  (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
+   Std->containsValue("c++2a") || Std->containsValue("c++latest"));
+
+  // Process -fmodule-header{=} flags.
+  if (Arg *A = Args.getLastArg(options::OPT_fmo

[PATCH] D118095: [clang][AVR] Reject non assembly source files for the avr1 family

2022-03-25 Thread Ayke via Phabricator via cfe-commits
aykevl added a comment.
Herald added a subscriber: StephenFan.

@MaskRay it was my suggestion to move this from the toolchain specific file to 
the generic file, because it makes the implementation much simpler. See my 
comment D117423#3251110  for details.

In D118095#3282039 , @MaskRay wrote:

> Rejecting some -mmcu= for C source files looks quite dubious. Does it really 
> help users?

For context: the avr1 family isn't supported by avr-gcc either. It's a old and 
rather limited subset of the AVR instruction set. I assume it's going to be 
rather difficult (and not worth the trouble) to write a C compiler for it, as 
it doesn't even have a fully functional stack. From Wikipedia 
:

> The AVR1 subset was not popular and no new models have been introduced since 
> 2000. It omits all RAM except for the 32 registers mapped at address 0–31 and 
> the I/O ports at addresses 32–95. The stack is replaced by a 3-level hardware 
> stack, and the PUSH and POP instructions are deleted. All 16-bit operations 
> are deleted, as are IJMP, ICALL, and all load and store addressing modes 
> except indirect via Z.

So I think the idea is to disallow this family so that users won't accidentally 
try to use a C compiler for these chips.


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

https://reviews.llvm.org/D118095

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert reopened this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

Our internal CI flagged an assertion in 
`llvm::NVPTXTargetLowering::getFunctionParamOptimizedAlign(llvm::Function 
const*, llvm::Type*, llvm::DataLayout const&)` last night.

Given the error:
`static bool llvm::isa_impl_cl::doit(const From *) [To = llvm::ConstantAsMetadata, From = const 
llvm::Metadata *]: Assertion `Val && "isa<> used on a null pointer"' failed.`
I assume it's this patch and the constant as metadata casts.

I'm working on the reproducer now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[clang] 7e45912 - [clang] Do not crash on arrow operator on dependent type.

2022-03-25 Thread Adam Czachorowski via cfe-commits

Author: Adam Czachorowski
Date: 2022-03-25T15:48:08+01:00
New Revision: 7e459126185f4d5115e6e2166a866aba1369d024

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

LOG: [clang] Do not crash on arrow operator on dependent type.

There seems to be more than one way to get to that state. I included to
example cases in the test, both were noticed recently.

There is room for improvement, for example by creating RecoveryExpr in
place of the bad initializer, but for now let's stop the crashes.

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

Added: 


Modified: 
clang/lib/Sema/TreeTransform.h
clang/test/SemaCXX/arrow-operator.cpp

Removed: 




diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index fb830ef2a118a..1ee457b0566ae 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -14757,6 +14757,10 @@ 
TreeTransform::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   return getSema().CreateBuiltinArraySubscriptExpr(
   First, Callee->getBeginLoc(), Second, OpLoc);
   } else if (Op == OO_Arrow) {
+// It is possible that the type refers to a RecoveryExpr created earlier
+// in the tree transformation.
+if (First->getType()->isDependentType())
+  return ExprError();
 // -> is never a builtin operation.
 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   } else if (Second == nullptr || isPostIncDec) {

diff  --git a/clang/test/SemaCXX/arrow-operator.cpp 
b/clang/test/SemaCXX/arrow-operator.cpp
index 3e32a6ba33eb2..c6d2a99251be4 100644
--- a/clang/test/SemaCXX/arrow-operator.cpp
+++ b/clang/test/SemaCXX/arrow-operator.cpp
@@ -65,3 +65,51 @@ void test() {
 }
 
 } // namespace arrow_suggest
+
+namespace no_crash_dependent_type {
+
+template 
+struct A {
+  void call();
+  A *operator->();
+};
+
+template 
+void foo() {
+  // The "requires an initializer" error seems unnecessary.
+  A &x = blah[7]; // expected-error {{use of undeclared identifier 
'blah'}} \
+// expected-error {{requires an initializer}}
+  // x is dependent.
+  x->call();
+}
+
+void test() {
+  foo(); // expected-note {{requested here}}
+}
+
+} // namespace no_crash_dependent_type
+
+namespace clangd_issue_1073_no_crash_dependent_type {
+
+template  struct Ptr {
+  T *operator->();
+};
+
+struct Struct {
+  int len;
+};
+
+template 
+struct TemplateStruct {
+  Ptr val(); // expected-note {{declared here}}
+};
+
+template 
+void templateFunc(const TemplateStruct &ts) {
+  Ptr ptr = ts.val(); // expected-error {{function is not marked 
const}}
+  auto foo = ptr->len;
+}
+
+template void templateFunc<0>(const TemplateStruct<0> &); // expected-note 
{{requested here}}
+
+} // namespace clangd_issue_1073_no_crash_dependent_type



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


[PATCH] D121824: [clang] Do not crash on arrow operator on dependent type.

2022-03-25 Thread Adam Czachorowski 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 rG7e459126185f: [clang] Do not crash on arrow operator on 
dependent type. (authored by adamcz).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121824

Files:
  clang/lib/Sema/TreeTransform.h
  clang/test/SemaCXX/arrow-operator.cpp


Index: clang/test/SemaCXX/arrow-operator.cpp
===
--- clang/test/SemaCXX/arrow-operator.cpp
+++ clang/test/SemaCXX/arrow-operator.cpp
@@ -65,3 +65,51 @@
 }
 
 } // namespace arrow_suggest
+
+namespace no_crash_dependent_type {
+
+template 
+struct A {
+  void call();
+  A *operator->();
+};
+
+template 
+void foo() {
+  // The "requires an initializer" error seems unnecessary.
+  A &x = blah[7]; // expected-error {{use of undeclared identifier 
'blah'}} \
+// expected-error {{requires an initializer}}
+  // x is dependent.
+  x->call();
+}
+
+void test() {
+  foo(); // expected-note {{requested here}}
+}
+
+} // namespace no_crash_dependent_type
+
+namespace clangd_issue_1073_no_crash_dependent_type {
+
+template  struct Ptr {
+  T *operator->();
+};
+
+struct Struct {
+  int len;
+};
+
+template 
+struct TemplateStruct {
+  Ptr val(); // expected-note {{declared here}}
+};
+
+template 
+void templateFunc(const TemplateStruct &ts) {
+  Ptr ptr = ts.val(); // expected-error {{function is not marked 
const}}
+  auto foo = ptr->len;
+}
+
+template void templateFunc<0>(const TemplateStruct<0> &); // expected-note 
{{requested here}}
+
+} // namespace clangd_issue_1073_no_crash_dependent_type
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14757,6 +14757,10 @@
   return getSema().CreateBuiltinArraySubscriptExpr(
   First, Callee->getBeginLoc(), Second, OpLoc);
   } else if (Op == OO_Arrow) {
+// It is possible that the type refers to a RecoveryExpr created earlier
+// in the tree transformation.
+if (First->getType()->isDependentType())
+  return ExprError();
 // -> is never a builtin operation.
 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   } else if (Second == nullptr || isPostIncDec) {


Index: clang/test/SemaCXX/arrow-operator.cpp
===
--- clang/test/SemaCXX/arrow-operator.cpp
+++ clang/test/SemaCXX/arrow-operator.cpp
@@ -65,3 +65,51 @@
 }
 
 } // namespace arrow_suggest
+
+namespace no_crash_dependent_type {
+
+template 
+struct A {
+  void call();
+  A *operator->();
+};
+
+template 
+void foo() {
+  // The "requires an initializer" error seems unnecessary.
+  A &x = blah[7]; // expected-error {{use of undeclared identifier 'blah'}} \
+// expected-error {{requires an initializer}}
+  // x is dependent.
+  x->call();
+}
+
+void test() {
+  foo(); // expected-note {{requested here}}
+}
+
+} // namespace no_crash_dependent_type
+
+namespace clangd_issue_1073_no_crash_dependent_type {
+
+template  struct Ptr {
+  T *operator->();
+};
+
+struct Struct {
+  int len;
+};
+
+template 
+struct TemplateStruct {
+  Ptr val(); // expected-note {{declared here}}
+};
+
+template 
+void templateFunc(const TemplateStruct &ts) {
+  Ptr ptr = ts.val(); // expected-error {{function is not marked const}}
+  auto foo = ptr->len;
+}
+
+template void templateFunc<0>(const TemplateStruct<0> &); // expected-note {{requested here}}
+
+} // namespace clangd_issue_1073_no_crash_dependent_type
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14757,6 +14757,10 @@
   return getSema().CreateBuiltinArraySubscriptExpr(
   First, Callee->getBeginLoc(), Second, OpLoc);
   } else if (Op == OO_Arrow) {
+// It is possible that the type refers to a RecoveryExpr created earlier
+// in the tree transformation.
+if (First->getType()->isDependentType())
+  return ExprError();
 // -> is never a builtin operation.
 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   } else if (Second == nullptr || isPostIncDec) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118680: [Intrinsics] Add `nocallback` to the default intrinsic attributes

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert closed this revision.
jdoerfert added a comment.

closed by a81fff8afd06fab8818db521cc79bf933c700e24 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118680

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


[clang] cf396c5 - [C++20][Modules] Correct an assert for modules-ts.

2022-03-25 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-03-25T14:55:13Z
New Revision: cf396c56e7df756d460a456f99ceab1b5d2c2e37

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

LOG: [C++20][Modules] Correct an assert for modules-ts.

When adding the support for modules partitions we added an assert that the
actual status of Global Module Fragments matches the state machine that is
driven by the module; keyword.

That does not apply to the modules-ts case, where there is an implicit GMF.

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

Added: 


Modified: 
clang/lib/Sema/SemaModule.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index a115834d334c4..e28de8c79b273 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -206,7 +206,7 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, 
SourceLocation ModuleLoc,
   ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
 GlobalModuleFragment = ModuleScopes.back().Module;
 
-  assert((!getLangOpts().CPlusPlusModules ||
+  assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
   SeenGMF == (bool)GlobalModuleFragment) &&
  "mismatched global module state");
 



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


[PATCH] D122394: [C++20][Modules] Correct an assert for modules-ts.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcf396c56e7df: [C++20][Modules] Correct an assert for 
modules-ts. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122394

Files:
  clang/lib/Sema/SemaModule.cpp


Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -206,7 +206,7 @@
   ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
 GlobalModuleFragment = ModuleScopes.back().Module;
 
-  assert((!getLangOpts().CPlusPlusModules ||
+  assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
   SeenGMF == (bool)GlobalModuleFragment) &&
  "mismatched global module state");
 


Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -206,7 +206,7 @@
   ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
 GlobalModuleFragment = ModuleScopes.back().Module;
 
-  assert((!getLangOpts().CPlusPlusModules ||
+  assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
   SeenGMF == (bool)GlobalModuleFragment) &&
  "mismatched global module state");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122271: [Clang] -Wunused-but-set-variable warning - handle also pre/post unary operators

2022-03-25 Thread Kamau Bridgeman via Phabricator via cfe-commits
kamaub added a comment.

This option appears to incorrectly warn warning that `unsigned NumEntries = 
getNumEntries();` is "set but not used" in llvm/include/llvm/ADT/DenseMap.h:129 
 
and so it is breaking the ppc64le-lld-multistage-test 
 bot. 
This could be because the only use is in an assert which is in a corner case 
maybe?

  const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
  if (std::is_trivially_destructible::value) {
// Use a simpler loop when values don't need destruction.
for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
  P->getFirst() = EmptyKey;
  } else {
unsigned NumEntries = getNumEntries();
for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
  if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  P->getSecond().~ValueT();
  --NumEntries;
}
P->getFirst() = EmptyKey;
  }
}
assert(NumEntries == 0 && "Node count imbalance!");
  }

I noticed you were commit NFCI changes to makes sure you did not break any 
builds before reapplying but it appears you missed 
llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:3924 
 
which is causing build breaks to both the sanitizer-ppc64be-linux 
 and sanitizer-ppc64le-linux 
 bots. Is there an NFCI planned 
for it by you? If not I'll submit an NFC change myself in a few minutes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122271

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


[PATCH] D122271: [Clang] -Wunused-but-set-variable warning - handle also pre/post unary operators

2022-03-25 Thread Kamau Bridgeman via Phabricator via cfe-commits
kamaub added a comment.

I'm sorry I took so long to notify you but I need to bring these bots back to 
green as soon as possible, they have been broken too long.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122271

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


[PATCH] D122069: [Clang] Add binary format for bundling offloading metadata

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418227.
jhuber6 added a comment.

Splitting this out into a patch for the format. Adding a unit test and changing
strings to now be an arbitrary string map. Hopefully the move to LLVM proper
won't draw ire for creating another binary format in LLVM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122069

Files:
  llvm/include/llvm/Object/OffloadBinary.h
  llvm/lib/Object/CMakeLists.txt
  llvm/lib/Object/OffloadBinary.cpp
  llvm/unittests/Object/CMakeLists.txt
  llvm/unittests/Object/OffloadingTest.cpp

Index: llvm/unittests/Object/OffloadingTest.cpp
===
--- /dev/null
+++ llvm/unittests/Object/OffloadingTest.cpp
@@ -0,0 +1,66 @@
+#include "llvm/Object/OffloadBinary.h"
+
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+#include 
+
+TEST(OffloadingTest, checkOffloadingBinary) {
+  // Create random data to fill the image.
+  std::mt19937 Rng(std::random_device{}());
+  std::uniform_int_distribution SizeDist(0, 256);
+  std::uniform_int_distribution KindDist(0);
+  std::uniform_int_distribution BinaryDist(0);
+  std::uniform_int_distribution StringDist('!', '~');
+  std::vector Image(SizeDist(Rng));
+  std::generate(Image.begin(), Image.end(), [&]() { return BinaryDist(Rng); });
+  std::vector> Strings(SizeDist(Rng));
+  for (auto &KeyAndValue : Strings) {
+std::string Key(SizeDist(Rng), '\0');
+std::string Value(SizeDist(Rng), '\0');
+
+std::generate(Key.begin(), Key.end(), [&]() { return StringDist(Rng); });
+std::generate(Value.begin(), Value.end(),
+  [&]() { return StringDist(Rng); });
+
+KeyAndValue = std::make_pair(Key, Value);
+  }
+
+  // Create the image.
+  llvm::StringMap StringData;
+  for (auto &KeyAndValue : Strings)
+StringData[KeyAndValue.first] = KeyAndValue.second;
+  std::unique_ptr ImageData =
+  llvm::MemoryBuffer::getMemBuffer(
+  {reinterpret_cast(Image.data()), Image.size()}, "", false);
+
+  llvm::OffloadBinary::OffloadingImage Data;
+  Data.TheImageKind = static_cast(KindDist(Rng));
+  Data.TheOffloadKind = static_cast(KindDist(Rng));
+  Data.Flags = KindDist(Rng);
+  Data.StringData = StringData;
+  Data.Image = *ImageData;
+
+  auto BinaryBuffer = llvm::OffloadBinary::write(Data);
+
+  auto BinaryOrErr = llvm::OffloadBinary::read(*BinaryBuffer);
+  if (!BinaryOrErr)
+FAIL();
+
+  // Make sure we get the same data out.
+  auto &Binary = **BinaryOrErr;
+  ASSERT_EQ(Data.TheImageKind,
+static_cast(Binary.getImageKind()));
+  ASSERT_EQ(Data.TheOffloadKind,
+static_cast(Binary.getOffloadKind()));
+  ASSERT_EQ(Data.Flags, Binary.getFlags());
+
+  for (auto &KeyAndValue : Strings)
+ASSERT_TRUE(StringData[KeyAndValue.first] ==
+Binary.getString(KeyAndValue.first));
+
+  EXPECT_TRUE(Data.Image.getBuffer() == Binary.getImage());
+
+  // Ensure the size and alignment of the data is correct.
+  EXPECT_TRUE(Binary.getSize() % llvm::OffloadBinary::getAlignment() == 0);
+  EXPECT_TRUE(Binary.getSize() == BinaryBuffer->getBuffer().size());
+}
Index: llvm/unittests/Object/CMakeLists.txt
===
--- llvm/unittests/Object/CMakeLists.txt
+++ llvm/unittests/Object/CMakeLists.txt
@@ -11,6 +11,7 @@
   ELFTest.cpp
   MinidumpTest.cpp
   ObjectFileTest.cpp
+  OffloadingTest.cpp
   SymbolSizeTest.cpp
   SymbolicFileTest.cpp
   XCOFFObjectFileTest.cpp
Index: llvm/lib/Object/OffloadBinary.cpp
===
--- /dev/null
+++ llvm/lib/Object/OffloadBinary.cpp
@@ -0,0 +1,144 @@
+//===- Offloading.cpp - Utilities for handling offloading code  -*- 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 "llvm/Object/OffloadBinary.h"
+
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/MC/StringTableBuilder.h"
+#include "llvm/Object/Error.h"
+#include "llvm/Support/FileOutputBuffer.h"
+
+using namespace llvm;
+
+namespace llvm {
+
+Expected>
+OffloadBinary::read(MemoryBufferRef Buf) {
+  if (Buf.getBufferSize() < sizeof(Header) + sizeof(Entry))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  // Check for 0x10FF1OAD magic bytes.
+  if (!Buf.getBuffer().startswith("\x10\xFF\x10\xAD"))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  const char *Start = Buf.getBufferStart();
+  const Header *TheHeader = reinterpret_cast(Start);
+  const Entry *TheEntry =
+  reinterpret_cast(&Start[TheHeader->EntryOffset]);
+
+  return std::unique_ptr(
+  new OffloadBinary(Buf.getBufferStart(), TheHead

[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Godbold seems to not have included this:

  $ cat test.cpp
  int main(){return 0;}
  $ clang++ -fopenmp -fopenmp-targets=nvptx64 -Xopenmp-target -march=sm_80 
test.cpp
  ... static bool llvm::isa_impl_cl::doit(const From *) [To = llvm::ConstantAsMetadata, From = 
const llvm::Metadata *]: Assertion `Val && "isa<> used on a null pointer"' 
failed.




Comment at: llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp:4327
+  case GlobalValue::InternalLinkage:
+  case GlobalValue::PrivateLinkage: {
+// Check that if a function has internal or private linkage

FWIW, `if (!F->hasLocalLinkage()) { return Align(ABITypeAlign); } `.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D122078: [clang-tidy] Ignore concepts in `misc-redundant-expression`

2022-03-25 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D122078#3407984 , @aaron.ballman 
wrote:

> Okie dokie, thanks for weighing in! This LGTM (feel free to add the release 
> note when landing). If @alexfh has some technical concerns with 
> `hasAncestor()`, we can always revert and address them once we know more.

I feel like this is another issue which could be solved with traversal scopes. 
`isInEvaluationContext` This traversal scope wouldn't traverse things like 
concepts, static_asserts(?), Noexcept & explicit specifiers, sizeof, decltype 
etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122078

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


[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-03-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 418235.
erichkeane added a comment.

Apply clang-format


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

https://reviews.llvm.org/D119544

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,61 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};  // #FOO
+
+template 
+void TrailingReturn(T) // #TRAILING
+requires(sizeof(T) > 2) || // #TRAILING_REQ
+T::value{};// #TRAILING_REQ_VAL
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -40,6 +40,18 @@
 
 static_assert(S::f(1));
 
+// Similar to the 'S' test, but tries to use 'U' in the requires clause.
+template 
+struct S1 {
+  // expected-note@+3 {{candidate template ignored: constraints not satisfied [with U = int]}}
+  // expected-note@+2 {{because substituted constraint expression is ill-formed: type 'int' cannot be used prior to '::' because it has no members}}
+  template 
+  static constexpr auto f(U const index) requires(U::foo) { return true; }
+};
+
+// expected-error@+1 {{no matching function for call to 'f'}}
+static_assert(S1::f(1));
+
 constexpr auto value = 0;
 
 template
Index: clang/test/SemaTemplate/deferred-concept-inst.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/deferred-concept-inst.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify -Wno-unused-value
+// expected-no-diagnostics
+
+namespace GithubBug44178 {
+template 
+struct CRTP {
+  void call_foo() requires
+  require

[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2022-03-25 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I share @aaron.ballman option that given the flakiness of the guidelines, the 
check shouldn't mention that it addresses the c++core guidelines. Instead 
moving the check into another module(misc) would still provide immense value, 
with the side effect that it is still able to help teams enforce parts of the 
core guidelines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 added a comment.

In D120129#3408088 , @jdoerfert wrote:

> Godbold seems to not have included this:
>
>   $ cat test.cpp
>   int main(){return 0;}
>   $ clang++ -fopenmp -fopenmp-targets=nvptx64 -Xopenmp-target -march=sm_80 
> test.cpp
>   ... static bool llvm::isa_impl_cl llvm::Metadata *>::doit(const From *) [To = llvm::ConstantAsMetadata, From = 
> const llvm::Metadata *]: Assertion `Val && "isa<> used on a null pointer"' 
> failed.

Thanks for the reproducer! Is the problem specific for sm_80 or not? I am 
unable to reproduce the issue with sm_75 and lower.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D122443: [OpenMP] Replace device kernel linkage with weak_odr

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb9f67d44ba37: [OpenMP] Replace device kernel linkage with 
weak_odr (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122443

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/amdgcn_target_codegen.cpp
  clang/test/OpenMP/assumes_include_nvptx.cpp
  clang/test/OpenMP/declare_target_codegen.cpp
  clang/test/OpenMP/declare_target_link_codegen.cpp
  clang/test/OpenMP/metadirective_device_isa_codegen_amdgcn.cpp
  clang/test/OpenMP/nvptx_target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_private_codegen.cpp
  clang/test/OpenMP/target_reduction_codegen.cpp

Index: clang/test/OpenMP/target_reduction_codegen.cpp
===
--- clang/test/OpenMP/target_reduction_codegen.cpp
+++ clang/test/OpenMP/target_reduction_codegen.cpp
@@ -45,7 +45,7 @@
   {
   }
 
-  // TCHECK: define weak void @__omp_offloading_{{.+}}(i32*{{.+}} %{{.+}})
+  // TCHECK: define weak_odr void @__omp_offloading_{{.+}}(i32*{{.+}} %{{.+}})
   // TCHECK: [[A:%.+]] = alloca i{{[0-9]+}}*,
   // TCHECK: store {{.+}}, {{.+}} [[A]],
   // TCHECK: load i32*, i32** [[A]],
@@ -56,7 +56,7 @@
 a = 1;
   }
 
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}(i32*{{.+}} %{{.+}})
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}(i32*{{.+}} %{{.+}})
   // TCHECK: [[A:%.+]] = alloca i{{[0-9]+}}*,
   // TCHECK: store {{.+}}, {{.+}} [[A]],
   // TCHECK: [[REF:%.+]] = load i32*, i32** [[A]],
@@ -69,7 +69,7 @@
 aa = 1;
   }
 
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}(i32*{{.+}} [[A:%.+]], i16*{{.+}} [[AA:%.+]])
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}(i32*{{.+}} [[A:%.+]], i16*{{.+}} [[AA:%.+]])
   // TCHECK:  [[A:%.+]] = alloca i{{[0-9]+}}*,
   // TCHECK:  [[AA:%.+]] = alloca i{{[0-9]+}}*,
   // TCHECK: store {{.+}}, {{.+}} [[A]],
@@ -118,7 +118,7 @@
   return a;
 }
 
-// TCHECK: define weak void @__omp_offloading_{{.+}}(i32*{{.+}}, i16*{{.+}}, i8*{{.+}}, [10 x i32]*{{.+}})
+// TCHECK: define weak_odr void @__omp_offloading_{{.+}}(i32*{{.+}}, i16*{{.+}}, i8*{{.+}}, [10 x i32]*{{.+}})
 // TCHECK:  [[A:%.+]] = alloca i{{[0-9]+}}*,
 // TCHECK:  [[A2:%.+]] = alloca i{{[0-9]+}}*,
 // TCHECK:  [[A3:%.+]] = alloca i{{[0-9]+}}*,
@@ -154,7 +154,7 @@
 return c[1][1] + (int)b;
   }
 
-  // TCHECK: define weak void @__omp_offloading_{{.+}}([[S1]]* noundef [[TH:%.+]], i32*{{.+}}, i{{[0-9]+}} noundef [[VLA:%.+]], i{{[0-9]+}} noundef [[VLA1:%.+]], i16*{{.+}})
+  // TCHECK: define weak_odr void @__omp_offloading_{{.+}}([[S1]]* noundef [[TH:%.+]], i32*{{.+}}, i{{[0-9]+}} noundef [[VLA:%.+]], i{{[0-9]+}} noundef [[VLA1:%.+]], i16*{{.+}})
   // TCHECK: [[TH_ADDR:%.+]] = alloca [[S1]]*,
   // TCHECK: [[B_ADDR:%.+]] = alloca i{{[0-9]+}}*,
   // TCHECK: [[VLA_ADDR:%.+]] = alloca i{{[0-9]+}},
@@ -206,7 +206,7 @@
 }
 
 // template
-// TCHECK: define weak void @__omp_offloading_{{.+}}(i{{[0-9]+}}*{{.+}}, i{{[0-9]+}}*{{.+}}, [10 x i32]*{{.+}})
+// TCHECK: define weak_odr void @__omp_offloading_{{.+}}(i{{[0-9]+}}*{{.+}}, i{{[0-9]+}}*{{.+}}, [10 x i32]*{{.+}})
 // TCHECK: [[A:%.+]] = alloca i{{[0-9]+}}*,
 // TCHECK: [[A2:%.+]] = alloca i{{[0-9]+}}*,
 // TCHECK: [[B:%.+]] = alloca [10 x i{{[0-9]+}}]*,
Index: clang/test/OpenMP/target_private_codegen.cpp
===
--- clang/test/OpenMP/target_private_codegen.cpp
+++ clang/test/OpenMP/target_private_codegen.cpp
@@ -45,7 +45,7 @@
   {
   }
 
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}()
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}()
   // TCHECK:  [[A:%.+]] = alloca i{{[0-9]+}},
   // TCHECK-NOT: store {{.+}}, {{.+}} [[A]],
   // TCHECK:  ret void
@@ -55,7 +55,7 @@
 a = 1;
   }
 
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}()
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}()
   // TCHECK:  [[A:%.+]] = alloca i{{[0-9]+}},
   // TCHECK:  store i{{[0-9]+}} 1, i{{[0-9]+}}* [[A]],
   // TCHECK:  ret void
@@ -66,7 +66,7 @@
 aa = 1;
   }
 
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}()
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}()
   // TCHECK:  [[A:%.+]] = alloca i{{[0-9]+}},
   // TCHECK:  [[A2:%.+]] = alloca i{{[0-9]+}},
   // TCHECK:  store i{{[0-9]+}} 1, i{{[0-9]+}}* [[A]],
@@ -85,7 +85,7 @@
   }
   // make sure that private variables are generated in all cases and that we use those instances for operations inside the
   // target region
-  // TCHECK:  define weak void @__omp_offloading_{{.+}}(i{{[0-9]+}} noundef [[VLA:%.+]], i{{[0-9]+}} noundef [[VLA1:%.+]], i{{[0-9]+}} noundef [[VLA3:%.+]])
+  // TCHECK:  define weak_odr void @__omp_offloading_{{.+}}(i{{[0-9]+}} noundef [[VLA:%.+]], i{{[0-9]+}} noundef [[VLA1:%.+]

[clang] b9f67d4 - [OpenMP] Replace device kernel linkage with weak_odr

2022-03-25 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-03-25T11:29:15-04:00
New Revision: b9f67d44ba37f3012f892a65550ec941f13626c0

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

LOG: [OpenMP] Replace device kernel linkage with weak_odr

Currently the device kernels all have weak linkage to prevent linkage
errors on multiple defintions. However, this prevents some optimizations
from adequately analyzing them because of the nature of weak linkage.
This patch replaces the weak linkage with weak_odr linkage so we can
statically assert that multiple declarations of the same kernel will
have the same definition.

Reviewed By: jdoerfert

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/test/OpenMP/amdgcn_target_codegen.cpp
clang/test/OpenMP/assumes_include_nvptx.cpp
clang/test/OpenMP/declare_target_codegen.cpp
clang/test/OpenMP/declare_target_link_codegen.cpp
clang/test/OpenMP/metadirective_device_isa_codegen_amdgcn.cpp
clang/test/OpenMP/nvptx_target_firstprivate_codegen.cpp
clang/test/OpenMP/target_firstprivate_codegen.cpp
clang/test/OpenMP/target_private_codegen.cpp
clang/test/OpenMP/target_reduction_codegen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index eb547be057cb9..84527eb884cfd 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6537,7 +6537,7 @@ void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
 
   if (CGM.getLangOpts().OpenMPIsDevice) {
 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
-OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
+OutlinedFn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
 OutlinedFn->setDSOLocal(false);
 if (CGM.getTriple().isAMDGCN())
   OutlinedFn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);

diff  --git a/clang/test/OpenMP/amdgcn_target_codegen.cpp 
b/clang/test/OpenMP/amdgcn_target_codegen.cpp
index 9118af92fc613..2a4ce8a81235e 100644
--- a/clang/test/OpenMP/amdgcn_target_codegen.cpp
+++ b/clang/test/OpenMP/amdgcn_target_codegen.cpp
@@ -9,7 +9,7 @@
 #define N 1000
 
 int test_amdgcn_target_tid_threads() {
-// CHECK-LABEL: define weak amdgpu_kernel void 
@{{.*}}test_amdgcn_target_tid_threads
+// CHECK-LABEL: define weak_odr amdgpu_kernel void 
@{{.*}}test_amdgcn_target_tid_threads
 
   int arr[N];
 
@@ -23,7 +23,7 @@ int test_amdgcn_target_tid_threads() {
 }
 
 int test_amdgcn_target_tid_threads_simd() {
-// CHECK-LABEL: define weak amdgpu_kernel void 
@{{.*}}test_amdgcn_target_tid_threads_simd
+// CHECK-LABEL: define weak_odr amdgpu_kernel void 
@{{.*}}test_amdgcn_target_tid_threads_simd
 
   int arr[N];
 

diff  --git a/clang/test/OpenMP/assumes_include_nvptx.cpp 
b/clang/test/OpenMP/assumes_include_nvptx.cpp
index 0829f857eae47..8b720f3d334b8 100644
--- a/clang/test/OpenMP/assumes_include_nvptx.cpp
+++ b/clang/test/OpenMP/assumes_include_nvptx.cpp
@@ -11,11 +11,11 @@
 
 // TODO: Think about teaching the OMPIRBuilder about default attributes as 
well so the __kmpc* declarations are annotated.
 
-// CHECK: define weak void 
@__omp_offloading_{{.*}}__Z17complex_reductionIfEvv_{{.*}}() [[attr0:#[0-9]]]
+// CHECK: define weak_odr void 
@__omp_offloading_{{.*}}__Z17complex_reductionIfEvv_{{.*}}() [[attr0:#[0-9]]]
 // CHECK: call i32 @__kmpc_target_init(
 // CHECK: declare noundef float @_Z3sinf(float noundef) [[attr1:#[0-9]*]]
 // CHECK: declare void @__kmpc_target_deinit(
-// CHECK: define weak void 
@__omp_offloading_{{.*}}__Z17complex_reductionIdEvv_{{.*}}() [[attr0]]
+// CHECK: define weak_odr void 
@__omp_offloading_{{.*}}__Z17complex_reductionIdEvv_{{.*}}() [[attr0]]
 // CHECK: %call = call noundef double @_Z3sind(double noundef 0.00e+00) 
[[attr2:#[0-9]]]
 // CHECK: declare noundef double @_Z3sind(double noundef) [[attr1]]
 

diff  --git a/clang/test/OpenMP/declare_target_codegen.cpp 
b/clang/test/OpenMP/declare_target_codegen.cpp
index 991d6aa67f539..8a52d55b69f81 100644
--- a/clang/test/OpenMP/declare_target_codegen.cpp
+++ b/clang/test/OpenMP/declare_target_codegen.cpp
@@ -140,7 +140,7 @@ int bar() { return 1 + foo() + bar() + baz1() + baz2(); }
 int maini1() {
   int a;
   static long aa = 32 + bbb + ccc + fff + ggg;
-// CHECK-DAG: define weak void 
@__omp_offloading_{{.*}}maini1{{.*}}_l[[@LINE+1]](i32* noundef nonnull align 
{{[0-9]+}} dereferenceable({{[0-9]+}}) %{{.*}}, i64 {{.*}}, i64 {{.*}})
+// CHECK-DAG: define weak_odr void 
@__omp_offloading_{{.*}}maini1{{.*}}_l[[@LINE+1]](i32* noundef nonnull align 
{{[0-9]+}} dereferenceable({{[0-9]+}}) %{{.*}}, i64 {{.*}}, i64 {{.*}})
 #pragma omp target map(tofrom \
: a, b)
   {
@@ -153,7 +153,7

[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

2022-03-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 418238.
balazske marked 11 inline comments as done.
balazske added a comment.

Address review comments.

- Removed caching of errno-related values from the checker.
- Added note tags.
- Added documentation comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122150

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp
  clang/test/Analysis/errno-notes.c
  clang/test/Analysis/errno.c

Index: clang/test/Analysis/errno.c
===
--- clang/test/Analysis/errno.c
+++ clang/test/Analysis/errno.c
@@ -3,6 +3,7 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_VAR
 
 // RUN: %clang_analyze_cc1 -verify %s \
@@ -10,8 +11,10 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_FUNC
 
+#include "Inputs/system-header-simulator.h"
 #ifdef ERRNO_VAR
 #include "Inputs/errno_var.h"
 #endif
@@ -25,6 +28,26 @@
 int ErrnoTesterChecker_setErrnoIfError();
 int ErrnoTesterChecker_setErrnoIfErrorRange();
 
+// This function simulates the following:
+// * Return 0 and leave 'errno' with undefined value.
+// This is the case of a successful standard function call.
+// For example if 'ftell' returns not -1.
+// * Return 1 and sets 'errno' to a specific error code (1).
+// This is the case of a failed standard function call.
+// The function indicates the failure by a special return value
+// that is returned only at failure.
+// 'errno' can be checked but it is not required.
+// For example if 'ftell' returns -1.
+// * Return 2 and may set errno to a value (actually it does not set it).
+// This is the case of a standard function call where the failure can only be
+// checked by reading from 'errno'. The value of 'errno' is changed by the
+// function only at failure, the user should set 'errno' to 0 before the call
+// (ErrnoChecker does not check for this rule).
+// 'strtol' is an example of this case, if it returns LONG_MIN (or LONG_MAX)
+// This case applies only if LONG_MIN or LONG_MAX is returned,
+// otherwise the first case in this list applies.
+int ErrnoTesterChecker_setErrnoCheckState();
+
 void something();
 
 void test() {
@@ -61,3 +84,107 @@
 clang_analyzer_eval(errno == 1); // expected-warning{{FALSE}} expected-warning{{TRUE}}
   }
 }
+
+void testErrnoCheck0() {
+  // If the function returns a success result code, value of 'errno'
+  // is unspecified and it is unsafe to make any decision with it.
+  // The function did not promise to not change 'errno' if no failure happens.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+if (errno) { // no warning for second time (analysis stops at the first warning)
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+errno = 0;
+if (errno) { // no warning after overwritten 'errno'
+}
+  }
+}
+
+void testErrnoCheck1() {
+  // If the function returns error result code that is out-of-band (not a valid
+  // non-error return value) the value of 'errno' can be checked but it is not
+  // required to do so.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+if (errno) { // no warning
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+errno = 0; // no warning
+  }
+}
+
+void testErrnoCheck2() {
+  // If the function returns an in-band error result the value of 'errno' is
+  // required to be checked to verify if error happened.
+  // The same applies to other functions that can indicate failure only by
+  // change of 'errno'.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+if (errno) {
+}
+errno = 0; // no warning after 'errno' was read
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value of 'errno' was not checked and is overwritten here [alpha.unix.Errno]}}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value o

[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

2022-03-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked 2 inline comments as done.
balazske added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:545
+  Dependencies<[ErrnoModeling]>,
+  Documentation;
+

steakhal wrote:
> Then we should have documentation, and examples for it.
Yes this is missing. But currently the errno value is not set by any non-debug 
checker, if there is any real example in the documentation it will not work 
(until the function is modeled correctly). Adding errno support for the 
functions (or some of them) is a separate change, we can add documentation here 
and commit the changes together (as close as possible).



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:68-71
+  if (ErrnoLoc) {
+ErrnoRegion = ErrnoLoc->getAsRegion();
+assert(ErrnoRegion && "The 'errno' location should be a memory region.");
+  }

steakhal wrote:
> NoQ wrote:
> > steakhal wrote:
> > > `Loc` always wrap a memregion of some sort.
> > Nope; null pointer is a `Loc` but doesn't correspond to any memory region.
> > 
> > I usually print out doxygen inheritance graphs:
> > 
> > - 
> > https://clang.llvm.org/doxygen/classclang_1_1ento_1_1SVal__inherit__graph.png
> > - 
> > https://clang.llvm.org/doxygen/classclang_1_1ento_1_1SymExpr__inherit__graph.png
> > - 
> > https://clang.llvm.org/doxygen/classclang_1_1ento_1_1MemRegion__inherit__graph.png
> > 
> > and hang them on the wall near my desk. They're really handy.
> > 
> > 
> > On a separate note, why not make this assertion part of `getErrnoLoc()`?
> ah true
This assert is not needed, the errno value has always a place that is a 
`MemRegion` according to how the `ErrnoModeling` works.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:104
+void ErrnoChecker::checkBeginFunction(CheckerContext &C) const {
+  // The errno location must be refreshed at every new function.
+  ErrnoInitialized = false;

NoQ wrote:
> Note that `checkBeginFunction()` is every time a nested stack frame is 
> entered. This happens much more often than an update to the variable is 
> needed.
The "cached" errno values are removed, this function is not needed.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h:24
 
+enum ErrnoCheckState : unsigned {
+  Errno_Irrelevant = 0,

steakhal wrote:
> Did you consider enum classes?
Originally it was enum class but I had to change it for some reason. Probably 
it did not have a default value.



Comment at: clang/test/Analysis/errno.c:170
+clang_analyzer_eval(errno); // expected-warning{{TRUE}}
+something();
+clang_analyzer_eval(errno); // expected-warning{{UNKNOWN}}

steakhal wrote:
> So this is the case when `errno` gets indirectly invalidated by some opaque 
> function call.  I see.
> However, it will test that the value associated with the errno region gets 
> invalidated, that's fine. However, you should test if the metadata (the enum 
> value) attached to memregion also gets invalidated.
> Please make sure you have tests for that as well.
> A `ErrnoTesterChecker_dumpCheckState()` should be perfect for this.
The check is now done indirectly by checking that no warning is produced.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122150

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


[clang-tools-extra] 39b80c8 - [clang-tidy] Add modernize-macro-to-enum check

2022-03-25 Thread via cfe-commits

Author: Richard
Date: 2022-03-25T09:45:55-06:00
New Revision: 39b80c8380c86539de391600efaa17184b5a52b4

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

LOG: [clang-tidy] Add modernize-macro-to-enum check

This check performs basic analysis of macros and replaces them
with an anonymous unscoped enum.  Using an unscoped anonymous enum
ensures that everywhere the macro token was used previously, the
enumerator name may be safely used.

Potential macros for replacement must meet the following constraints:
- Macros must expand only to integral literal tokens.  The unary
  operators plus, minus and tilde are recognized to allow for positive,
  negative and bitwise negated integers.
- Macros must be defined on sequential source file lines, or with
  only comment lines in between macro definitions.
- Macros must all be defined in the same source file.
- Macros must not be defined within a conditional compilation block.
- Macros must not be defined adjacent to other preprocessor directives.
- Macros must not be used in preprocessor conditions

Each cluster of macros meeting the above constraints is presumed to
be a set of values suitable for replacement by an anonymous enum.
>From there, a developer can give the anonymous enum a name and
continue refactoring to a scoped enum if desired.  Comments on the
same line as a macro definition or between subsequent macro definitions
are preserved in the output.  No formatting is assumed in the provided
replacements.

The check cppcoreguidelines-macro-to-enum is an alias for this check.

Fixes #27408

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

Added: 
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-macro-to-enum.rst
clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum2.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum3.h
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 147c2741d59e4..6bf20552e0182 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangTidyModernizeModule
   DeprecatedIosBaseAliasesCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
+  MacroToEnumCheck.cpp
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp

diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
new file mode 100644
index 0..834943483cffb
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -0,0 +1,482 @@
+//===--- MacroToEnumCheck.cpp - clang-tidy 
===//
+//
+// 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 "MacroToEnumCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options,
+StringRef Text) {
+  // Use a lexer to look for tokens; if we find something other than a single
+  // hash, then there were intervening tokens between macro definitions.
+  std::string Buffer{Text};
+  Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
+Buffer.c_str() + Buffer.size());
+  Token Tok;
+  bool SeenHash = false;
+  while (!Lex.LexFromRawLexer(Tok)) {
+if (Tok.getKind() == tok::hash && !SeenHash) {
+  SeenHash = true;
+  continue;
+}
+return false;
+  }
+
+  // Everything in between was whitespace, so now just look for two blank 
lines,
+  // consisting of two consecutive E

[PATCH] D117522: [clang-tidy] Add modernize-macro-to-enum check

2022-03-25 Thread Richard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG39b80c8380c8: [clang-tidy] Add modernize-macro-to-enum check 
(authored by LegalizeAdulthood).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117522

Files:
  clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-macro-to-enum.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum2.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum3.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -0,0 +1,239 @@
+// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/modernize-macro-to-enum
+// C++14 or later required for binary literals.
+
+#if 1
+#include "modernize-macro-to-enum.h"
+
+// These macros are skipped due to being inside a conditional compilation block.
+#define GOO_RED 1
+#define GOO_GREEN 2
+#define GOO_BLUE 3
+
+#endif
+
+#define RED 0xFF
+#define GREEN 0x00FF00
+#define BLUE 0xFF
+// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: replace macro with enum [modernize-macro-to-enum]
+// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'RED' defines an integral constant; prefer an enum instead
+// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'GREEN' defines an integral constant; prefer an enum instead
+// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'BLUE' defines an integral constant; prefer an enum instead
+// CHECK-FIXES: enum {
+// CHECK-FIXES-NEXT: RED = 0xFF,
+// CHECK-FIXES-NEXT: GREEN = 0x00FF00,
+// CHECK-FIXES-NEXT: BLUE = 0xFF
+// CHECK-FIXES-NEXT: };
+
+// Verify that comments are preserved.
+#define CoordModeOrigin 0   /* relative to the origin */
+#define CoordModePrevious   1   /* relative to previous point */
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: replace macro with enum
+// CHECK-MESSAGES: :[[@LINE-3]]:9: warning: macro 'CoordModeOrigin' defines an integral constant; prefer an enum instead
+// CHECK-MESSAGES: :[[@LINE-3]]:9: warning: macro 'CoordModePrevious' defines an integral constant; prefer an enum instead
+// CHECK-FIXES: enum {
+// CHECK-FIXES-NEXT: CoordModeOrigin = 0,   /* relative to the origin */
+// CHECK-FIXES-NEXT: CoordModePrevious =   1   /* relative to previous point */
+// CHECK-FIXES-NEXT: };
+
+// Verify that multiline comments are preserved.
+#define BadDrawable 9   /* parameter not a Pixmap or Window */
+#define BadAccess   10  /* depending on context:
+- key/button already grabbed
+- attempt to free an illegal 
+  cmap entry 
+- attempt to store into a read-only 
+  color map entry. */
+// - attempt to modify the access control
+//   list from other than the local host.
+//
+#define BadAlloc11  /* insufficient resources */
+// CHECK-MESSAGES: :[[@LINE-11]]:1: warning: replace macro with enum
+// CHECK-MESSAGES: :[[@LINE-12]]:9: warning: macro 'BadDrawable' defines an integral constant; prefer an enum instead
+// CHECK-MESSAGES: :[[@LINE-12]]:9: warning: macro 'BadAccess' defines an integral constant; prefer an enum instead
+// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'BadAlloc' defines an integral constant; prefer an enum instead
+// CHECK-FIXES: enum {
+// CHECK-FIXES-NEXT: BadDrawable = 9,   /* parameter not a Pixmap or Window */
+// CHECK-FIXES-NEXT: BadAccess =   10,  /* depending on context:
+// CHECK-FIXES-NEXT: - key/button already grabbed
+// CHECK-FIXES-NEXT: - attempt to free an illegal 
+// CHECK-FIXES-NEXT:   cmap entry 
+// CHECK-FIXES-NEXT: - attempt to store into a read-only 
+// CHECK-FIXES-NEXT:   color map entry. */
+// CHECK-FIXES-NEXT: // - a

[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

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

This errno check will work if a state split is added at every standard function 
that may set `errno` at failure. (The success and failure branches have 
different //errno check state//, and probably different return value for the 
function.) Probably this is too many state splits. But a correct program should 
have anyway checks for the return value that make the same state splits.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122150

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D120129#3408116 , @kovdan01 wrote:

> In D120129#3408088 , @jdoerfert 
> wrote:
>
>> Godbold seems to not have included this:
>>
>>   $ cat test.cpp
>>   int main(){return 0;}
>>   $ clang++ -fopenmp -fopenmp-targets=nvptx64 -Xopenmp-target -march=sm_80 
>> test.cpp
>>   ... static bool llvm::isa_impl_cl> llvm::Metadata *>::doit(const From *) [To = llvm::ConstantAsMetadata, From = 
>> const llvm::Metadata *]: Assertion `Val && "isa<> used on a null pointer"' 
>> failed.
>
> Thanks for the reproducer! Is the problem specific for sm_80 or not? I am 
> unable to reproduce the issue with sm_75 and lower.

You don't need to run it. If you use this command line it doesn't crash?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 added a comment.

In D120129#3408168 , @jdoerfert wrote:

> You don't need to run it. If you use this command line it doesn't crash?

Yes, I run the same command (with sm_75 instead of sm_80 because I don't have 
libomptarget-nvptx-sm_80.bc), and it doesn't crash.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Ranjeet Singh via Phabricator via cfe-commits
rs created this revision.
rs added reviewers: tstellar, lenary.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
rs requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Make the warning more specific as downstream compilers could produce other 
warnings that might produce other warnings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D122487

Files:
  clang/test/Driver/aarch64-security-options.c


Index: clang/test/Driver/aarch64-security-options.c
===
--- clang/test/Driver/aarch64-security-options.c
+++ clang/test/Driver/aarch64-security-options.c
@@ -52,4 +52,4 @@
 
 // Check that the linker driver doesn't warn about -mbranch-protection=standard
 // as an unused option.
-// LINKER-DRIVER-NOT: warning:
+// LINKER-DRIVER-NOT: warning: argument unused during compilation: 
'-mbranch-protection=standard'


Index: clang/test/Driver/aarch64-security-options.c
===
--- clang/test/Driver/aarch64-security-options.c
+++ clang/test/Driver/aarch64-security-options.c
@@ -52,4 +52,4 @@
 
 // Check that the linker driver doesn't warn about -mbranch-protection=standard
 // as an unused option.
-// LINKER-DRIVER-NOT: warning:
+// LINKER-DRIVER-NOT: warning: argument unused during compilation: '-mbranch-protection=standard'
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

The reason I used a minimal check string is because if the warning text changes 
at all, then the test becomes useful (this is the downside of using -NOT).  I 
wonder if there is another way to test this that might be robust?  If not, then 
I think this change is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122487

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


[PATCH] D122271: [Clang] -Wunused-but-set-variable warning - handle also pre/post unary operators

2022-03-25 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

In D122271#3408060 , @kamaub wrote:

> This option appears to incorrectly warn warning that `unsigned NumEntries = 
> getNumEntries();` is "set but not used" in 
> llvm/include/llvm/ADT/DenseMap.h:129 
> 
>  and so it is breaking the ppc64le-lld-multistage-test 
>  bot. 
> This could be because the only use is in an assert which is in a corner case 
> maybe?
>
>   const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
>   if (std::is_trivially_destructible::value) {
> // Use a simpler loop when values don't need destruction.
> for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
>   P->getFirst() = EmptyKey;
>   } else {
> unsigned NumEntries = getNumEntries();
> for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
>   if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
> if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
>   P->getSecond().~ValueT();
>   --NumEntries;
> }
> P->getFirst() = EmptyKey;
>   }
> }
> assert(NumEntries == 0 && "Node count imbalance!");
>   }
>
> I noticed you were commit NFCI changes to makes sure you did not break any 
> builds before reapplying but it appears you missed 
> llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp:3924 
>  
> which is causing build breaks to both the sanitizer-ppc64be-linux 
>  and sanitizer-ppc64le-linux 
>  bots. Is there an NFCI planned 
> for it by you? If not I'll submit an NFC change myself in a few minutes.



>> This option appears to incorrectly warn warning that

Warns correctly in configurations where assert is removed. (void) trick will 
solve that.
Sorry, I missed this one, as this was outside common code + X86. Will push fix 
soon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122271

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D120129#3408174 , @kovdan01 wrote:

> In D120129#3408168 , @jdoerfert 
> wrote:
>
>> You don't need to run it. If you use this command line it doesn't crash?
>
> Yes, I run the same command (with sm_75 instead of sm_80 because I don't have 
> libomptarget-nvptx-sm_80.bc), and it doesn't crash.

So it's not sm_80 but the cuda version that is important. 11.4.0 works fine for 
me, 11.0.2 breaks also for sm_70.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D120129: [NVPTX] Enhance vectorization of ld.param & st.param

2022-03-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Here are the null pointers that cause the assertion:

  !nvvm.annotations = !{!8, !9, !8, !10, !10, !10, !10, !11, !11, !10}
  
  !8 = !{null, !"align", i32 8}
  !9 = !{null, !"align", i32 8, !"align", i32 65544, !"align", i32 131080}
  !10 = !{null, !"align", i32 16}
  !11 = !{null, !"align", i32 16, !"align", i32 65552, !"align", i32 131088}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120129

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


[PATCH] D120185: [ASTMatchers] Output currently processing match and nodes on crash

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

That bot sets ENABLE_BACKTRACES=1.

It seems to work for clang-cl (foo.cc contains `#pragma clang __debug 
parser_crash`):

  >out\gn\bin\clang-cl /c foo.cc
  PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ 
and include the crash backtrace, preprocessed source, and associated run script.
  Stack dump:
  0.  Program arguments: out\\gn\\bin\\clang-cl /c foo.cc
  1.  foo.cc:1:23: at annotation token
   #0 0x7ff6653b7395 (C:\src\llvm-project\out\gn\bin\clang-cl.exe+0x3997395)

I tried setting up a local cmake build, but cmake complains that it can't find 
py3 even though I have it installed. I also have today off, so I don't want to 
spend a lot of time debugging it.

I'd suggest you land this with the test disabled on Win, and I'll debug it on 
Windows next week.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120185

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


[PATCH] D117522: [clang-tidy] Add modernize-macro-to-enum check

2022-03-25 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:216
+  MacroToEnumCheck *Check;
+  const LangOptions &LangOptions;
+  const SourceManager &SM;

@LegalizeAdulthood  I'm seeing errors in 
https://lab.llvm.org/buildbot/#/builders/93/builds/7956

```
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:216:22:
 error: declaration of ‘const clang::LangOptions& 
clang::tidy::modernize::{anonymous}::MacroToEnumCallbacks::LangOptions’ changes 
meaning of ‘LangOptions’ [-fpermissive]
  216 |   const LangOptions &LangOptions;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117522

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


[PATCH] D122377: [PowerPC][Linux] Support 16-byte lock free atomics on pwr8 and up

2022-03-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/Basic/Targets/PPC.h:451
+  MaxAtomicPromoteWidth = 128;
+  MaxAtomicInlineWidth = 128;
+}

MaxAtomicPromoteWidth should not depend on whether quadword-atomics is present, 
only the target OS.  It determines the layout of `_Atomic(__int128_t)`.

(MaxAtomicInlineWidth is allowed to adjust as necessary.)



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:2140
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-ppc-quadword-atomics");
+  }

Please avoid using "-mllvm" options like this; among other issues, it doesn't 
work with LTO.  If we need to indicate this, please use a function attribute in 
the IR.

(Yes, there are other cases where we translate flags to -mllvm options, but 
it's not something you should copy.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

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


[PATCH] D122444: [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for LLVM_ENABLE_RUNTIMES builds

2022-03-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay marked an inline comment as done.
MaskRay added inline comments.



Comment at: clang/lib/Driver/ToolChains/Linux.cpp:316
+  if (StringRef(D.Dir).startswith(SysRoot) &&
+  D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
 addPathIfExists(D, D.Dir + "/../lib", Paths);

mgorny wrote:
> I wonder if this still wouldn't get in the way of some (non-Gentoo) people 
> who have clang in `/usr/bin/clang` and 32-bit libc++ in `/usr/lib/libc++.so`.
It won't. /lib and /usr/lib follow this search directory. Since /lib and 
/usr/lib are usually the same, or at least include different sets of files, the 
user will not observe different behaviors.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122444

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


[PATCH] D122069: [Object] Add binary format for bundling offloading metadata

2022-03-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 418255.
jhuber6 added a comment.

Changing test, `uniform_int_distribution` doesn't support `char` or `uint8_t` 
according to the standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122069

Files:
  llvm/include/llvm/Object/OffloadBinary.h
  llvm/lib/Object/CMakeLists.txt
  llvm/lib/Object/OffloadBinary.cpp
  llvm/unittests/Object/CMakeLists.txt
  llvm/unittests/Object/OffloadingTest.cpp

Index: llvm/unittests/Object/OffloadingTest.cpp
===
--- /dev/null
+++ llvm/unittests/Object/OffloadingTest.cpp
@@ -0,0 +1,67 @@
+#include "llvm/Object/OffloadBinary.h"
+
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+#include 
+
+TEST(OffloadingTest, checkOffloadingBinary) {
+  // Create random data to fill the image.
+  std::mt19937 Rng(std::random_device{}());
+  std::uniform_int_distribution SizeDist(0, 256);
+  std::uniform_int_distribution KindDist(0);
+  std::uniform_int_distribution BinaryDist(
+  std::numeric_limits::min(), std::numeric_limits::max());
+  std::uniform_int_distribution StringDist('!', '~');
+  std::vector Image(SizeDist(Rng));
+  std::generate(Image.begin(), Image.end(), [&]() { return BinaryDist(Rng); });
+  std::vector> Strings(SizeDist(Rng));
+  for (auto &KeyAndValue : Strings) {
+std::string Key(SizeDist(Rng), '\0');
+std::string Value(SizeDist(Rng), '\0');
+
+std::generate(Key.begin(), Key.end(), [&]() { return StringDist(Rng); });
+std::generate(Value.begin(), Value.end(),
+  [&]() { return StringDist(Rng); });
+
+KeyAndValue = std::make_pair(Key, Value);
+  }
+
+  // Create the image.
+  llvm::StringMap StringData;
+  for (auto &KeyAndValue : Strings)
+StringData[KeyAndValue.first] = KeyAndValue.second;
+  std::unique_ptr ImageData =
+  llvm::MemoryBuffer::getMemBuffer(
+  {reinterpret_cast(Image.data()), Image.size()}, "", false);
+
+  llvm::OffloadBinary::OffloadingImage Data;
+  Data.TheImageKind = static_cast(KindDist(Rng));
+  Data.TheOffloadKind = static_cast(KindDist(Rng));
+  Data.Flags = KindDist(Rng);
+  Data.StringData = StringData;
+  Data.Image = *ImageData;
+
+  auto BinaryBuffer = llvm::OffloadBinary::write(Data);
+
+  auto BinaryOrErr = llvm::OffloadBinary::create(*BinaryBuffer);
+  if (!BinaryOrErr)
+FAIL();
+
+  // Make sure we get the same data out.
+  auto &Binary = **BinaryOrErr;
+  ASSERT_EQ(Data.TheImageKind,
+static_cast(Binary.getImageKind()));
+  ASSERT_EQ(Data.TheOffloadKind,
+static_cast(Binary.getOffloadKind()));
+  ASSERT_EQ(Data.Flags, Binary.getFlags());
+
+  for (auto &KeyAndValue : Strings)
+ASSERT_TRUE(StringData[KeyAndValue.first] ==
+Binary.getString(KeyAndValue.first));
+
+  EXPECT_TRUE(Data.Image.getBuffer() == Binary.getImage());
+
+  // Ensure the size and alignment of the data is correct.
+  EXPECT_TRUE(Binary.getSize() % llvm::OffloadBinary::getAlignment() == 0);
+  EXPECT_TRUE(Binary.getSize() == BinaryBuffer->getBuffer().size());
+}
Index: llvm/unittests/Object/CMakeLists.txt
===
--- llvm/unittests/Object/CMakeLists.txt
+++ llvm/unittests/Object/CMakeLists.txt
@@ -11,6 +11,7 @@
   ELFTest.cpp
   MinidumpTest.cpp
   ObjectFileTest.cpp
+  OffloadingTest.cpp
   SymbolSizeTest.cpp
   SymbolicFileTest.cpp
   XCOFFObjectFileTest.cpp
Index: llvm/lib/Object/OffloadBinary.cpp
===
--- /dev/null
+++ llvm/lib/Object/OffloadBinary.cpp
@@ -0,0 +1,144 @@
+//===- Offloading.cpp - Utilities for handling offloading code  -*- 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 "llvm/Object/OffloadBinary.h"
+
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/MC/StringTableBuilder.h"
+#include "llvm/Object/Error.h"
+#include "llvm/Support/FileOutputBuffer.h"
+
+using namespace llvm;
+
+namespace llvm {
+
+Expected>
+OffloadBinary::create(MemoryBufferRef Buf) {
+  if (Buf.getBufferSize() < sizeof(Header) + sizeof(Entry))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  // Check for 0x10FF1OAD magic bytes.
+  if (!Buf.getBuffer().startswith("\x10\xFF\x10\xAD"))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  const char *Start = Buf.getBufferStart();
+  const Header *TheHeader = reinterpret_cast(Start);
+  const Entry *TheEntry =
+  reinterpret_cast(&Start[TheHeader->EntryOffset]);
+
+  return std::unique_ptr(
+  new OffloadBinary(Buf.getBufferStart(), TheHeader, TheEntry));
+}
+
+std::unique_ptr
+Offloa

[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think this is a sufficient stopgap measure to keep clang from crashing, and I 
appreciate the FIXME comment. Should the cxx_status page also be updated, or is 
P0315R4 still partial (and if it is, can we add information to the status page 
about what's partial if you know it)? Also, this could use a release note about 
the fixes. So almost LGTM!




Comment at: clang/lib/Sema/TreeTransform.h:12934
+  // substituting an unevaluated lambda inside of a function's parameter's type
+  // - as parameter type are not instanciated from within a function's DC. We
+  // use isUnevaluatedContext() to distinguish the function parameter case.

aaron.ballman wrote:
> 
Still need to fix the typos here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

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


[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

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

Don't forget about Release notes!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

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


[PATCH] D120185: [ASTMatchers] Output currently processing match and nodes on crash

2022-03-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120185#3408258 , @thakis wrote:

> That bot sets ENABLE_BACKTRACES=1.
>
> It seems to work for clang-cl (foo.cc contains `#pragma clang __debug 
> parser_crash`):
>
>   >out\gn\bin\clang-cl /c foo.cc
>   PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ 
> and include the crash backtrace, preprocessed source, and associated run 
> script.
>   Stack dump:
>   0.  Program arguments: out\\gn\\bin\\clang-cl /c foo.cc
>   1.  foo.cc:1:23: at annotation token
>#0 0x7ff6653b7395 
> (C:\src\llvm-project\out\gn\bin\clang-cl.exe+0x3997395)
>
> I tried setting up a local cmake build, but cmake complains that it can't 
> find py3 even though I have it installed. I also have today off, so I don't 
> want to spend a lot of time debugging it.
>
> I'd suggest you land this with the test disabled on Win, and I'll debug it on 
> Windows next week.

Okay, that works for me, this definitely sounds more involved than "bot 
configured wrong" but doesn't sound like "functionality is incorrect with the 
patch". Thanks for digging into this next week @thakis (and enjoy your day 
off!), and thanks for the discussion @njames93 while we figured out what to do 
next.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120185

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


[clang] a184a0d - [clang][dataflow] Add support for disabling warnings on smart pointers.

2022-03-25 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2022-03-25T16:44:34Z
New Revision: a184a0d8aae6efc1d7f19a900155b8694178d617

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

LOG: [clang][dataflow] Add support for disabling warnings on smart pointers.

This patch provides the user with the ability to disable all checked of accesses
to optionals that are the pointees of smart pointers. Since smart pointers are
not modeled (yet), the system cannot distinguish safe from unsafe accesses to
optionals through smart pointers. This results in false positives whenever
optionals are used through smart pointers. The patch gives the user the choice
of ignoring all positivess in these cases.

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

Added: 


Modified: 

clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
index 05a9165e59dde..235121b2e5759 100644
--- 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -24,6 +24,18 @@
 namespace clang {
 namespace dataflow {
 
+// FIXME: Explore using an allowlist-approach, where constructs supported by 
the
+// analysis are always enabled and additional constructs are enabled through 
the
+// `Options`.
+struct UncheckedOptionalAccessModelOptions {
+  /// Ignore optionals reachable through overloaded `operator*` or `operator->`
+  /// (other than those of the optional type itself). The analysis does not
+  /// equate the results of such calls, so it can't identify when their results
+  /// are used safely (across calls), resulting in false positives in all such
+  /// cases. Note: this option does not cover access through `operator[]`.
+  bool IgnoreSmartPointerDereference = false;
+};
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
@@ -34,7 +46,8 @@ class UncheckedOptionalAccessModel
 : public DataflowAnalysis {
 public:
-  explicit UncheckedOptionalAccessModel(ASTContext &AstContext);
+  UncheckedOptionalAccessModel(
+  ASTContext &AstContext, UncheckedOptionalAccessModelOptions Options = 
{});
 
   static SourceLocationsLattice initialElement() {
 return SourceLocationsLattice();

diff  --git 
a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp 
b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
index bf325b04967c2..b775698dafb5d 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -45,15 +45,23 @@ auto optionalClass() {
 
 auto hasOptionalType() { return hasType(optionalClass()); }
 
-auto isOptionalMemberCallWithName(llvm::StringRef MemberName) {
+auto isOptionalMemberCallWithName(
+llvm::StringRef MemberName,
+llvm::Optional Ignorable = llvm::None) {
+  auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr()))
+: cxxThisExpr());
   return cxxMemberCallExpr(
-  on(expr(unless(cxxThisExpr(,
+  on(expr(Exception)),
   callee(cxxMethodDecl(hasName(MemberName), ofClass(optionalClass();
 }
 
-auto isOptionalOperatorCallWithName(llvm::StringRef OperatorName) {
-  return cxxOperatorCallExpr(hasOverloadedOperatorName(OperatorName),
- callee(cxxMethodDecl(ofClass(optionalClass();
+auto isOptionalOperatorCallWithName(
+llvm::StringRef operator_name,
+llvm::Optional Ignorable = llvm::None) {
+  return cxxOperatorCallExpr(
+  hasOverloadedOperatorName(operator_name),
+  callee(cxxMethodDecl(ofClass(optionalClass(,
+  Ignorable ? callExpr(unless(hasArgument(0, *Ignorable))) : callExpr());
 }
 
 auto isMakeOptionalCall() {
@@ -333,10 +341,22 @@ void transferStdSwapCall(const CallExpr *E, const 
MatchFinder::MatchResult &,
   transferSwap(*OptionalLoc1, *OptionalLoc2, State);
 }
 
-auto buildTransferMatchSwitch() {
+llvm::Optional
+ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) {
+  if (Options.IgnoreSmartPointerDereference)
+return memberExpr(hasObjectExpression(ignoringParenImpCasts(
+cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("->"),
+  hasOverloadedOperatorName("*")),
+

[PATCH] D122143: [clang][dataflow] Add support for disabling warnings on smart pointers.

2022-03-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
ymandel marked 3 inline comments as done.
Closed by commit rGa184a0d8aae6: [clang][dataflow] Add support for disabling 
warnings on smart pointers. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122143

Files:
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1219,7 +1219,9 @@
 llvm::Error Error = checkDataflow(
 SourceCode, FuncMatcher,
 [](ASTContext &Ctx, Environment &) {
-  return UncheckedOptionalAccessModel(Ctx);
+  return UncheckedOptionalAccessModel(
+  Ctx, UncheckedOptionalAccessModelOptions{
+   /*IgnoreSmartPointerDereference=*/true});
 },
 [&MatchesLatticeChecks](
 llvm::ArrayRef
+struct smart_ptr {
+  T& operator*() &;
+  T* operator->();
+};
+
+struct Foo {
+  $ns::$optional opt;
+};
+
+void target() {
+  smart_ptr foo;
+  *foo->opt;
+  /*[[check-1]]*/
+  *(*foo).opt;
+  /*[[check-2]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("check-1", "safe"), Pair("check-2", "safe")));
+}
+
 // FIXME: Add support for:
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -45,15 +45,23 @@
 
 auto hasOptionalType() { return hasType(optionalClass()); }
 
-auto isOptionalMemberCallWithName(llvm::StringRef MemberName) {
+auto isOptionalMemberCallWithName(
+llvm::StringRef MemberName,
+llvm::Optional Ignorable = llvm::None) {
+  auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr()))
+: cxxThisExpr());
   return cxxMemberCallExpr(
-  on(expr(unless(cxxThisExpr(,
+  on(expr(Exception)),
   callee(cxxMethodDecl(hasName(MemberName), ofClass(optionalClass();
 }
 
-auto isOptionalOperatorCallWithName(llvm::StringRef OperatorName) {
-  return cxxOperatorCallExpr(hasOverloadedOperatorName(OperatorName),
- callee(cxxMethodDecl(ofClass(optionalClass();
+auto isOptionalOperatorCallWithName(
+llvm::StringRef operator_name,
+llvm::Optional Ignorable = llvm::None) {
+  return cxxOperatorCallExpr(
+  hasOverloadedOperatorName(operator_name),
+  callee(cxxMethodDecl(ofClass(optionalClass(,
+  Ignorable ? callExpr(unless(hasArgument(0, *Ignorable))) : callExpr());
 }
 
 auto isMakeOptionalCall() {
@@ -333,10 +341,22 @@
   transferSwap(*OptionalLoc1, *OptionalLoc2, State);
 }
 
-auto buildTransferMatchSwitch() {
+llvm::Optional
+ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) {
+  if (Options.IgnoreSmartPointerDereference)
+return memberExpr(hasObjectExpression(ignoringParenImpCasts(
+cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("->"),
+  hasOverloadedOperatorName("*")),
+unless(hasArgument(0, expr(hasOptionalType(;
+  return llvm::None;
+}
+
+auto buildTransferMatchSwitch(
+const UncheckedOptionalAccessModelOptions &Options) {
   // FIXME: Evaluate the efficiency of matchers. If using matchers results in a
   // lot of duplicated work (e.g. string comparisons), consider providing APIs
   // that avoid it through memoization.
+  auto IgnorableOptional = ignorableOptional(Options);
   return MatchSwitchBuilder()
   // Attach a symbolic "has_value" state to optional values that we see for
   // the first time.
@@ -371,19 +391,20 @@
 
   // optional::value
   .CaseOf(
-  isOptionalMemberCallWithName("value"),
+  isOptionalMemberCallWithName("value", IgnorableOptional),
   [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
  LatticeTransferState &State) {
 transferUnwrapCall(E, E->getImplicitObjectArgument(), State);
   })
 
   // optional::operator*, optional::operator->
-  .CaseOf(expr(anyOf(isOptionalOperatorCallWithName("*"),
-   isOptionalOperatorCall

[PATCH] D122444: [Driver][Linux] Remove D.Dir+"/../lib" from default search paths for LLVM_ENABLE_RUNTIMES builds

2022-03-25 Thread Michał Górny via Phabricator via cfe-commits
mgorny accepted this revision.
mgorny added a comment.
This revision is now accepted and ready to land.

Thanks. Technically, it looks good to me. However, I'd suggest waiting until 
Jannik is able to test it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122444

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


[clang] c7f91e2 - [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Gulfem Savrun Yeniceri via cfe-commits

Author: Gulfem Savrun Yeniceri
Date: 2022-03-25T17:03:03Z
New Revision: c7f91e227a799dfee05962bb108274dbfe809fee

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

LOG: [InstrProfiling] No runtime hook for unused funcs

CoverageMappingModuleGen generates a coverage mapping record
even for unused functions with internal linkage, e.g.
static int foo() { return 100; }
Clang frontend eliminates such functions, but InstrProfiling pass
still pulls in profile runtime since there is a coverage record.
Fuchsia uses runtime counter relocation, and pulling in profile
runtime for unused functions causes a linker error:
undefined hidden symbol: __llvm_profile_counter_bias.
Since 389dc94d4be7, we do not hook profile runtime for the binaries
that none of its translation units have been instrumented in Fuchsia.
This patch extends that for the instrumented binaries that
consist of only unused functions.

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

Added: 
clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp

Modified: 
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp

Removed: 




diff  --git a/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp 
b/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
new file mode 100644
index 0..5a835ae311697
--- /dev/null
+++ b/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-unknown-fuchsia -fprofile-instr-generate 
-fcoverage-mapping -emit-llvm -S %s -o - | FileCheck %s
+
+// CHECK-NOT: @__llvm_profile_runtime
+static int f0() {
+  return 100;
+}

diff  --git a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp 
b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
index 379c41ce66936..a8b013b6f2e6a 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -558,16 +558,18 @@ bool InstrProfiling::run(
   TT = Triple(M.getTargetTriple());
 
   bool MadeChange = false;
-
-  // Emit the runtime hook even if no counters are present.
-  if (needsRuntimeHookUnconditionally(TT))
+  bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
+  if (NeedsRuntimeHook)
 MadeChange = emitRuntimeHook();
 
   // Improve compile time by avoiding linear scans when there is no work.
   GlobalVariable *CoverageNamesVar =
   M.getNamedGlobal(getCoverageUnusedNamesVarName());
-  if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
-return MadeChange;
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;
+}
+  }
 
   // We did not know how many value sites there would be inside
   // the instrumented function. This is counting the number of instrumented



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


[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Gulfem Savrun Yeniceri 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 rGc7f91e227a79: [InstrProfiling] No runtime hook for unused 
funcs (authored by gulfem).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122336

Files:
  clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp


Index: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
===
--- llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -558,16 +558,18 @@
   TT = Triple(M.getTargetTriple());
 
   bool MadeChange = false;
-
-  // Emit the runtime hook even if no counters are present.
-  if (needsRuntimeHookUnconditionally(TT))
+  bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
+  if (NeedsRuntimeHook)
 MadeChange = emitRuntimeHook();
 
   // Improve compile time by avoiding linear scans when there is no work.
   GlobalVariable *CoverageNamesVar =
   M.getNamedGlobal(getCoverageUnusedNamesVarName());
-  if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
-return MadeChange;
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;
+}
+  }
 
   // We did not know how many value sites there would be inside
   // the instrumented function. This is counting the number of instrumented
Index: clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
===
--- /dev/null
+++ clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-unknown-fuchsia -fprofile-instr-generate 
-fcoverage-mapping -emit-llvm -S %s -o - | FileCheck %s
+
+// CHECK-NOT: @__llvm_profile_runtime
+static int f0() {
+  return 100;
+}


Index: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
===
--- llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -558,16 +558,18 @@
   TT = Triple(M.getTargetTriple());
 
   bool MadeChange = false;
-
-  // Emit the runtime hook even if no counters are present.
-  if (needsRuntimeHookUnconditionally(TT))
+  bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
+  if (NeedsRuntimeHook)
 MadeChange = emitRuntimeHook();
 
   // Improve compile time by avoiding linear scans when there is no work.
   GlobalVariable *CoverageNamesVar =
   M.getNamedGlobal(getCoverageUnusedNamesVarName());
-  if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
-return MadeChange;
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;
+}
+  }
 
   // We did not know how many value sites there would be inside
   // the instrumented function. This is counting the number of instrumented
Index: clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
===
--- /dev/null
+++ clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-unknown-fuchsia -fprofile-instr-generate -fcoverage-mapping -emit-llvm -S %s -o - | FileCheck %s
+
+// CHECK-NOT: @__llvm_profile_runtime
+static int f0() {
+  return 100;
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121590: [C++20][Modules][Driver][HU 3/N] Handle foo.h with -fmodule-header and/or C++ invocation.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418267.
iains added a comment.
Herald added a subscriber: MaskRay.

rebased, addrssed review comment, amend testcase for windows.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121590

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,7 +3,10 @@
 // RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
-// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
 // RUN: %clang -### -std=c++20 -fmodule-header=system \
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2432,7 +2432,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && 
hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2457,8 +2459,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complaint about compiling things in the wrong mode.
+if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
+hasHeaderMode())
   Ty = CXXHeaderUnitType(CXX20HeaderType);
   } else {
 assert(InputTypeArg && "InputType set w/o InputTypeArg");


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,7 +3,10 @@
 // RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
-// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
 // RUN: %clang -### -std=c++20 -fmodule-header=system \
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2432,7 +2432,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2457,8 +2459,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complaint about compiling things in the wrong mode.
+

[PATCH] D121590: [C++20][Modules][Driver][HU 3/N] Handle foo.h with -fmodule-header and/or C++ invocation.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418268.
iains added a comment.

another testcase ajustment for windows.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121590

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,6 +3,9 @@
 // RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
 // RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2432,7 +2432,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && 
hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2457,8 +2459,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complaint about compiling things in the wrong mode.
+if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
+hasHeaderMode())
   Ty = CXXHeaderUnitType(CXX20HeaderType);
   } else {
 assert(InputTypeArg && "InputType set w/o InputTypeArg");


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,6 +3,9 @@
 // RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
 // RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2432,7 +2432,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2457,8 +2459,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complaint about compiling things in the wrong mode.
+if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
+hasHeaderMode())
   Ty = CXXHeaderUnitType(CXX20HeaderType);
   } else {
 assert(InputTypeArg && "InputType set w/o InputTypeArg");
___
cfe-commits mailing list
cfe-commits@

[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

2022-03-25 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 418269.
cor3ntin added a comment.

- Fix a typo (sorry Aaron, I completely missed that)
- Add a release note
- Clarify why the implementation status is still partial.

This is a bit of a drive-by change but I agree it's a good thing
to clarify.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/SemaCXX/lambda-unevaluated.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1024,7 +1024,11 @@
 
   Lambdas in unevaluated contexts
   https://wg21.link/p0315r4";>P0315R4
-  Partial
+  
+Partial
+  temp.deduct/9 is not implemented yet.
+
+  
 
 
 
Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5824,6 +5824,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_FALSE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
@@ -5843,6 +5844,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_TRUE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInGlobalScope) {
Index: clang/test/SemaCXX/lambda-unevaluated.cpp
===
--- clang/test/SemaCXX/lambda-unevaluated.cpp
+++ clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -30,6 +30,27 @@
 auto e = g(0); // expected-error{{no matching function for call}}
 // expected-note@-2 {{substitution failure}}
 
+template 
+auto foo(decltype([] {
+  return [] { return T(); }();
+})) {}
+
+void test() {
+  foo({});
+}
+
+template 
+struct C {
+  template 
+  auto foo(decltype([] {
+return [] { return T(); }();
+  })) {}
+};
+
+void test2() {
+  C{}.foo({});
+}
+
 namespace PR52073 {
 // OK, these are distinct functions not redefinitions.
 template void f(decltype([]{})) {} // expected-note {{candidate}}
@@ -40,6 +61,62 @@
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 // FIXME: We instantiate the lambdas into the context of the function template,
-// so we think they're dependent and can't evaluate a call to them.
+//  so we think they're dependent and can't evaluate a call to them.
 void use_g() { g<6>(&"hello"); } // expected-error {{no matching function}}
 }
+
+namespace GH51416 {
+
+template 
+struct A {
+  void spam(decltype([] {}));
+};
+
+template 
+void A::spam(decltype([] {})) // expected-error{{out-of-line definition of 'spam' does not match}}
+{}
+
+struct B {
+  template 
+  void spam(decltype([] {}));
+};
+
+template 
+void B::spam(decltype([] {})) {} // expected-error{{out-of-line definition of 'spam' does not match}}
+
+} // namespace GH51416
+
+namespace GH50376 {
+
+template 
+struct foo_t {// expected-note 2{{candidate constructor}}
+  foo_t(T ptr) {} // expected-note{{candidate constructor}}
+};
+
+template 
+using alias = foo_t;
+
+template 
+auto fun(T const &t) -> alias {
+  return alias{t}; // expected-error{{no viable conversion from returned value of type 'alias<...>'}}
+}
+
+void f() {
+  int i;
+  auto const error = fun(i); // expected-note{{in instantiation}}
+}
+
+} // namespace GH50376
+
+namespace GH51414 {
+template  void spam(decltype([] {}) (*s)[sizeof(T)] = nullptr) {}
+void foo() {
+  spam();
+}
+} // namespace GH51414
+
+namespace GH51641 {
+template 
+void foo(decltype(+[](T) {}) lambda, T param);
+static_assert(!__is_same(decltype(foo), void));
+} // namespace GH51641
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -5727,7 +5727,7 @@
   // Add lambda-specific data.
   if (Data.IsLambda) {
 auto &Lambda = D->getLambdaData();
-Record->push_back(Lambda.Dependent);
+Record->push_back(Lambda.DependencyKind);
 Record->push_back(Lambda.IsGenericLambda);
 Record->push_back(Lambda.CaptureDefault);
 Record->push_

[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp:569
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;

https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements

That said, nested if is usually written as a single if with `&&`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122336

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


[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Ranjeet Singh via Phabricator via cfe-commits
rs added a comment.

@tstellar thanks for the review. I can't really think of any other way to test 
this. I'll wait till Monday if no one else has suggested anything else then 
I'll commit it. Thanks again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122487

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


[PATCH] D122336: [InstrProfiling] No runtime hook for unused funcs

2022-03-25 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp:569
+  if (!containsProfilingIntrinsics(M)) {
+if (!CoverageNamesVar || !NeedsRuntimeHook) {
+  return MadeChange;

MaskRay wrote:
> https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements
> 
> That said, nested if is usually written as a single if with `&&`
Thanks for the tip @MaskRay, and I'm going to fix that in a following patch. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122336

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


[PATCH] D121532: [Clang] Fix Unevaluated Lambdas

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

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


[PATCH] D121591: [C++20][Modules][Driver][HU 4/N] Add fdirectives-only mode for preprocessing output.

2022-03-25 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 418274.
iains added a comment.
Herald added a subscriber: MaskRay.

rebased, adjusted testcases to avoid using clang++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121591

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cxx20-fdirectives-only.cpp


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4618,6 +4618,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_back("-P");
+  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
+CmdArgs.push_back("-fdirectives-only");
 }
   } else if (isa(JA)) {
 CmdArgs.push_back("-emit-obj");
@@ -6769,6 +6771,10 @@
   if (RewriteImports)
 CmdArgs.push_back("-frewrite-imports");
 
+  if (Args.hasFlag(options::OPT_fdirectives_only,
+   options::OPT_fno_directives_only, false))
+CmdArgs.push_back("-fdirectives-only");
+
   // Enable rewrite includes if the user's asked for it or if we're generating
   // diagnostics.
   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4279,10 +4279,14 @@
   OutputTy = types::TY_Dependencies;
 } else {
   OutputTy = Input->getType();
+  // For these cases, the preprocessor is only translating forms, the 
Output
+  // still needs preprocessing.
   if (!Args.hasFlag(options::OPT_frewrite_includes,
 options::OPT_fno_rewrite_includes, false) &&
   !Args.hasFlag(options::OPT_frewrite_imports,
 options::OPT_fno_rewrite_imports, false) &&
+  !Args.hasFlag(options::OPT_fdirectives_only,
+options::OPT_fno_directives_only, false) &&
   !CCGenDiagnostics)
 OutputTy = types::getPreprocessedType(OutputTy);
   assert(OutputTy != types::TY_INVALID &&


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4618,6 +4618,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_back("-P");
+  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
+CmdArgs.push_back("-fdirectives-only");
 }
   } else if (isa(JA)) {
 CmdArgs.push_back("-emit-obj");
@@ -6769,6 +6771,10 @@
   if (RewriteImports)
 CmdArgs.push_back("-frewrite-imports");
 
+  if (Args.hasFlag(options::OPT_fdirectives_only,
+   options::OPT_fno_directives_only, false))
+CmdArgs.push_back("-fdirectives-only");
+
   // Enable rewrite includes if the us

[clang] b97f260 - Reland "[ASTMatchers] Output currently processing match and nodes on crash"

2022-03-25 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-25T17:53:58Z
New Revision: b97f26083bd04ccbdd63b0c726e047496e5b847a

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

LOG: Reland "[ASTMatchers] Output currently processing match and nodes on crash"

This reverts commit cff34ccb605aa78030cd51cfe44362ed1c1fb80b.

This relands commit d89f9e963e4979466193dc6a15fe091bf7ca5c47

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b54fca707eda8..282cf1d0a4cc1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,6 +96,9 @@ The improvements are...
 Improvements to clang-tidy
 --
 
+- Added trace code to help narrow down any checks and the relevant source code
+  that result in crashes.
+
 New checks
 ^^
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index b19a7fe3be04c..70598460151ae 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Timer.h"
 #include 
 #include 
@@ -760,11 +761,67 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+  class TraceReporter : llvm::PrettyStackTraceEntry {
+  public:
+TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
+void print(raw_ostream &OS) const override {
+  if (!MV.CurMatched) {
+OS << "ASTMatcher: Not currently matching\n";
+return;
+  }
+  assert(MV.ActiveASTContext &&
+ "ActiveASTContext should be set if there is a matched callback");
+
+  OS << "ASTMatcher: Processing '" << MV.CurMatched->getID() << "'\n";
+  const BoundNodes::IDToNodeMap &Map = MV.CurBoundNodes->getMap();
+  if (Map.empty()) {
+OS << "No bound nodes\n";
+return;
+  }
+  OS << "--- Bound Nodes Begin ---\n";
+  for (const auto &Item : Map) {
+OS << "" << Item.first << " - { ";
+if (const auto *D = Item.second.get()) {
+  OS << D->getDeclKindName() << "Decl ";
+  if (const auto *ND = dyn_cast(D)) {
+ND->printQualifiedName(OS);
+OS << " : ";
+  } else
+OS << ": ";
+  D->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *S = Item.second.get()) {
+  OS << S->getStmtClassName() << " : ";
+  S->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *T = Item.second.get()) {
+  OS << T->getTypeClassName() << "Type : ";
+  QualType(T, 0).print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else if (const auto *QT = Item.second.get()) {
+  OS << "QualType : ";
+  QT->print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else {
+  OS << Item.second.getNodeKind().asStringRef() << " : ";
+  Item.second.getSourceRange().print(
+  OS, MV.ActiveASTContext->getSourceManager());
+}
+OS << " }\n";
+  }
+  OS << "--- Bound Nodes End ---\n";
+}
+
+  private:
+const MatchASTVisitor &MV;
+  };
+
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
+  const MatchCallback *CurMatched = nullptr;
+  const BoundNodes *CurBoundNodes = nullptr;
+
   struct ASTNodeNotSpelledInSourceScope {
 ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
 : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
@@ -831,7 +888,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Timer.setBucket(&TimeByBucket[MP.second->getID()]);
   BoundNodesTreeBuilder Builder;
   if (MP.first.matches(Node, this, &Builder)) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);
   }
 }
@@ -863,7 +920,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   }
 
   if (MP.first.matches(DynNode, this, &Builder)) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);

[PATCH] D122487: [ARM] Make testcase warning pattern match more specific

2022-03-25 Thread Tom Stellard via Phabricator via cfe-commits
tstellar accepted this revision.
tstellar added a comment.
This revision is now accepted and ready to land.

In D122487#3408425 , @rs wrote:

> @tstellar thanks for the review. I can't really think of any other way to 
> test this. I'll wait till Monday if no one else has suggested anything else 
> then I'll commit it. Thanks again.

OK, sounds good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122487

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


[PATCH] D121951: [AMDGPU][OpenCL] Add "amdgpu-no-hostcall-ptr" in Clang codegen pre-COV_5

2022-03-25 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9381
+  M.getTarget().getTargetOpts().CodeObjectVersion != 500) {
+F->addFnAttr("amdgpu-no-hostcall-ptr");
+  }

arsenm wrote:
> sameerds wrote:
> > The frontend does not need to worry about this attribute. See the comment 
> > in the MetadataStreamer. A worthwhile check would be to generate an error 
> > if we are able to detect that some hostcall service is being used in OpenCL 
> > on code-object-v4 or lower. None exists right now, but we should add the 
> > check if such services show up. But those checks are likely to be in a 
> > different place. For example, enabling asan on OpenCL for code-object-v4 
> > should result in an error in the place where asan commandline options are 
> > parsed.
> Should be all opencl, not just kernels. Also < instead of !=?
> The frontend does not need to worry about this attribute. See the comment in 
> the MetadataStreamer. 

The reason I went this route is that otherwise the MetadataStreamer can only go 
off of the presence of the OCL printf metadata to infer that hostcall argument 
metadata is invalid and will be ignored by the runtime. Ideally, the 
MetadataStreamer or Verifier or something would actually //require// that a 
module does not have both OCL printf metadata and functions which are not 
"amdgpu-no-hostcall-ptr", but I didn't go that far as it would break old 
IR/bitcode that relies on the implicit behavior.

I'm OK with removing this code, and the rest of the patch remains essentially 
unchanged. We will still have an implicit rule based on code-object-version and 
presence of printf metadata, and at least conceptually you will still be able 
to compile OCL for pre-V5 and end up with hostcall argument metadata. That case 
is benign if the runtime just ignores it, but it still seems needlessly relaxed 
when we can just add the correct attribute in Clang codegen.

> Should be all opencl, not just kernels. Also < instead of !=?

Yes, my mistake, I'll update this



Comment at: llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp:406-408
 if (Func.getParent()->getNamedMetadata("llvm.printf.fmts"))
   emitKernelArg(DL, Int8PtrTy, Align(8), ValueKind::HiddenPrintfBuffer);
+else if (!Func.hasFnAttribute("amdgpu-no-hostcall-ptr"))

sameerds wrote:
> I would structure this differently: If this is code-object-v4 or lower, then 
> if  "llvm.printf.fmts" is present, then this kernel clearly contains OpenCL 
> bits, and cannot use hostcall. So it's okay to just assume that the 
> no-hostcall-ptr attribute is always present in this situation, which means 
> the only metadata generated is for ValueKind::HiddenPrintfBuffer. Else if 
> this is code-object-v5, then proceed to emit both metadata.
> 
> 
I'm not sure I follow; doesn't the code as-is implement what you're describing?

If the printf metadata is present, this will only ever emit the 
`HiddenPrintfBuffer`, irrespective of the hostcall attribute. Otherwise, this 
respects `amdgpu-no-hostcall-ptr` (i.e. for HIP and other languages).

The "if this is code-object-v4 or lower" portion is implicit, as this is just 
the `MetadataStreamerV2` impl. The `MetadataStreamerV3` (below) and 
`MetadataStreamerV4` (inherits from V3) impls below are similar. The 
`MetadataStreamerV5` impl is already correct for V5 (i.e. supports both 
argument kinds for the same kernel).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121951

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


[clang] 35b89bc - [clang][driver] Disable non-functional --version option for clang -cc1

2022-03-25 Thread Emil Kieri via cfe-commits

Author: Emil Kieri
Date: 2022-03-25T19:04:27+01:00
New Revision: 35b89bc24ca58d5b3a87578f69936afb26ef3b69

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

LOG: [clang][driver] Disable non-functional --version option for clang -cc1

This patch removes --version as a clang -cc1 option.
  clang --version
and
  clang --cc1 -version
remain valid. This behaviour is consistent with clang -cc1as.

Previously, clang -cc1 accepted both --version and -version, but
only -version was acted upon. The call
  clang -cc1 --version
stalled without any message: --version was an accepted option but
triggered no action, and the driver waited for standard input.

Reviewed By: thakis

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/test/Frontend/unknown-arg.c

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 784751a1a6863..488692e16145f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4203,7 +4203,7 @@ def _serialize_diags : Separate<["-", "--"], 
"serialize-diagnostics">, Flags<[No
   HelpText<"Serialize compiler diagnostics to a file">;
 // We give --version 
diff erent semantics from -version.
 def _version : Flag<["--"], "version">,
-  Flags<[CoreOption, CC1Option, FC1Option, FlangOption]>,
+  Flags<[CoreOption, FC1Option, FlangOption]>,
   HelpText<"Print version information">;
 def _signed_char : Flag<["--"], "signed-char">, Alias;
 def _std : Separate<["--"], "std">, Alias;

diff  --git a/clang/test/Frontend/unknown-arg.c 
b/clang/test/Frontend/unknown-arg.c
index eb2fb1aee2dd5..74a6c842da908 100644
--- a/clang/test/Frontend/unknown-arg.c
+++ b/clang/test/Frontend/unknown-arg.c
@@ -4,6 +4,9 @@
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
 // RUN: not %clang %s -E -Xclang --hel[ 2>&1 | \
 // RUN: FileCheck %s --check-prefix=DID-YOU-MEAN
+// RUN: not %clang_cc1 --version 2>&1 | \
+// RUN: FileCheck %s --check-prefix=DID-YOU-MEAN-VER
 
 // CHECK: error: unknown argument: '--helium'
 // DID-YOU-MEAN: error: unknown argument '--hel['; did you mean '--help'?
+// DID-YOU-MEAN-VER: error: unknown argument '--version'; did you mean 
'-version'?



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


  1   2   >