[PATCH] D158055: [clang][AST] Added some missing setter methods

2023-08-16 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 created this revision.
Herald added a project: All.
strimo378 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158055

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/Expr.h


Index: clang/include/clang/AST/Expr.h
===
--- clang/include/clang/AST/Expr.h
+++ clang/include/clang/AST/Expr.h
@@ -1199,6 +1199,8 @@
   /// place.
   Expr *getSourceExpr() const { return SourceExpr; }
 
+  void setSourceExpr(Expr *E) { SourceExpr = E; }
+
   void setIsUnique(bool V) {
 assert((!V || SourceExpr) &&
"unique OVEs are expected to have source expressions");
@@ -1332,6 +1334,11 @@
 return *getTrailingObjects();
   }
 
+  void setQualifierLoc(NestedNameSpecifierLoc QL) {
+assert(hasQualifier());
+*getTrailingObjects() = QL;
+  }
+
   /// If the name was qualified, retrieves the nested-name-specifier
   /// that precedes the name. Otherwise, returns NULL.
   NestedNameSpecifier *getQualifier() const {
@@ -1354,6 +1361,11 @@
 return hasFoundDecl() ? *getTrailingObjects() : D;
   }
 
+  void setFoundDecl(NamedDecl *ND) {
+assert(hasFoundDecl());
+*getTrailingObjects() = ND;
+  }
+
   bool hasTemplateKWAndArgsInfo() const {
 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
   }
@@ -3296,6 +3308,11 @@
 return getTrailingObjects()->QualifierLoc;
   }
 
+  void setQualifierLoc(NestedNameSpecifierLoc QL) {
+assert(hasQualifierOrFoundDecl());
+getTrailingObjects()->QualifierLoc = QL;
+  }
+
   /// If the member name was qualified, retrieves the
   /// nested-name-specifier that precedes the member name. Otherwise, returns
   /// NULL.
@@ -3370,6 +3387,10 @@
MemberLoc, MemberDNLoc);
   }
 
+  void setMemberDeclNameLoc(const DeclarationNameLoc &Loc) {
+MemberDNLoc = Loc;
+  }
+
   SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
 
   bool isArrow() const { return MemberExprBits.IsArrow; }
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -2118,6 +2118,8 @@
 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
   }
 
+  void setDeclNameLoc(const DeclarationNameLoc &Loc) { DNLoc = Loc; }
+
   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
 bool Qualified) const override;
 
@@ -3046,6 +3048,8 @@
   /// Determines whether this field is mutable (C++ only).
   bool isMutable() const { return Mutable; }
 
+  void setMutable(bool Mutable) { this->Mutable = Mutable; }
+
   /// Determines whether this field is a bitfield.
   bool isBitField() const { return BitField; }
 


Index: clang/include/clang/AST/Expr.h
===
--- clang/include/clang/AST/Expr.h
+++ clang/include/clang/AST/Expr.h
@@ -1199,6 +1199,8 @@
   /// place.
   Expr *getSourceExpr() const { return SourceExpr; }
 
+  void setSourceExpr(Expr *E) { SourceExpr = E; }
+
   void setIsUnique(bool V) {
 assert((!V || SourceExpr) &&
"unique OVEs are expected to have source expressions");
@@ -1332,6 +1334,11 @@
 return *getTrailingObjects();
   }
 
+  void setQualifierLoc(NestedNameSpecifierLoc QL) {
+assert(hasQualifier());
+*getTrailingObjects() = QL;
+  }
+
   /// If the name was qualified, retrieves the nested-name-specifier
   /// that precedes the name. Otherwise, returns NULL.
   NestedNameSpecifier *getQualifier() const {
@@ -1354,6 +1361,11 @@
 return hasFoundDecl() ? *getTrailingObjects() : D;
   }
 
+  void setFoundDecl(NamedDecl *ND) {
+assert(hasFoundDecl());
+*getTrailingObjects() = ND;
+  }
+
   bool hasTemplateKWAndArgsInfo() const {
 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
   }
@@ -3296,6 +3308,11 @@
 return getTrailingObjects()->QualifierLoc;
   }
 
+  void setQualifierLoc(NestedNameSpecifierLoc QL) {
+assert(hasQualifierOrFoundDecl());
+getTrailingObjects()->QualifierLoc = QL;
+  }
+
   /// If the member name was qualified, retrieves the
   /// nested-name-specifier that precedes the member name. Otherwise, returns
   /// NULL.
@@ -3370,6 +3387,10 @@
MemberLoc, MemberDNLoc);
   }
 
+  void setMemberDeclNameLoc(const DeclarationNameLoc &Loc) {
+MemberDNLoc = Loc;
+  }
+
   SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
 
   bool isArrow() const { return MemberExprBits.IsArrow; }
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -2118,6 +2118,8 @@
 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
   }
 
+  void setD

[PATCH] D158055: [clang][AST] Added some missing setter methods

2023-08-16 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 added a comment.

I added some missing (simple) setter methods to Decl and Expr classes. I did 
not comment them since typically simple setter methods are uncommented.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158055

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


[clang] ae84ad1 - [Driver] Select newest GCC installation on Solaris

2023-08-16 Thread Rainer Orth via cfe-commits

Author: Rainer Orth
Date: 2023-08-16T09:57:59+02:00
New Revision: ae84ad15efd7ef7da95146e900ec72ceadf98058

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

LOG: [Driver] Select newest GCC installation on Solaris

As described in Issue #53709
, since
28d58d8fe2094af6902dee7b4d68ec30a3e9d737

`clang` doesn't find the latest of several parallel GCC installations on
Solaris, but only the first in directory order, which is pretty random.

This patch sorts GCC installations in reverse version order so the latest
is picked.

Tested on `sparcv9-sun-solaris2.11`, `amd64-pc-solaris2.11`, and
`x86_64-pc-linux-gnu`.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index c8fb05d238782e..508ff1d8b9ae12 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2227,6 +2227,7 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
 // /usr/gcc/ as a prefix.
 
+SmallVector, 8> SolarisPrefixes;
 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
 std::error_code EC;
 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, 
EC),
@@ -2244,8 +2245,13 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   if (!D.getVFS().exists(CandidateLibPath))
 continue;
 
-  Prefixes.push_back(CandidatePrefix);
+  SolarisPrefixes.emplace_back(
+  std::make_pair(CandidateVersion, CandidatePrefix));
 }
+// Sort in reverse order so GCCInstallationDetector::init picks the latest.
+std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend());
+for (auto p : SolarisPrefixes)
+  Prefixes.emplace_back(p.second);
 return;
   }
 

diff  --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index 8d3853a7b4a6de..bf61d428448289 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -168,6 +168,155 @@ TEST(ToolChainTest, VFSGCCInstallationRelativeDir) {
 S);
 }
 
+TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  const char *EmptyFiles[] = {
+  // Sort entries so the latest version doesn't come first.
+  "/usr/gcc/7/lib/gcc/sparcv9-sun-solaris2.11/7.5.0/32/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/sparcv9-sun-solaris2.11/7.5.0/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/32/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/sparcv8plus/"
+  "crtbegin.o",
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/32/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/i386-pc-solaris2.11/4.7.3/amd64/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/i386-pc-solaris2.11/4.7.3/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/sparc-sun-solaris2.11/4.7.3/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/sparc-sun-solaris2.11/4.7.3/sparcv9/crtbegin.o",
+  };
+
+  for (const char *Path : EmptyFiles)
+InMemoryFileSystem->addFile(Path, 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  {
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "i386-pc-solaris2.11", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(
+TheDriver.BuildCompilation({"-v", "--gcc-toolchain=", "--sysroot="}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Selected GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Candidate multilib: .;@m64\n"
+  "Candidate multilib: 

[PATCH] D157275: [Driver] Select newest GCC installation on Solaris

2023-08-16 Thread Rainer Orth 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 rGae84ad15efd7: [Driver] Select newest GCC installation on 
Solaris (authored by ro).

Changed prior to commit:
  https://reviews.llvm.org/D157275?vs=550226&id=550651#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157275

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/ToolChainTest.cpp

Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -168,6 +168,155 @@
 S);
 }
 
+TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  const char *EmptyFiles[] = {
+  // Sort entries so the latest version doesn't come first.
+  "/usr/gcc/7/lib/gcc/sparcv9-sun-solaris2.11/7.5.0/32/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/sparcv9-sun-solaris2.11/7.5.0/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/32/crtbegin.o",
+  "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/sparcv8plus/"
+  "crtbegin.o",
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/32/crtbegin.o",
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/i386-pc-solaris2.11/4.7.3/amd64/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/i386-pc-solaris2.11/4.7.3/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/sparc-sun-solaris2.11/4.7.3/crtbegin.o",
+  "/usr/gcc/4.7/lib/gcc/sparc-sun-solaris2.11/4.7.3/sparcv9/crtbegin.o",
+  };
+
+  for (const char *Path : EmptyFiles)
+InMemoryFileSystem->addFile(Path, 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  {
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "i386-pc-solaris2.11", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(
+TheDriver.BuildCompilation({"-v", "--gcc-toolchain=", "--sysroot="}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Selected GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Candidate multilib: .;@m64\n"
+  "Candidate multilib: 32;@m32\n"
+  "Selected multilib: 32;@m32\n",
+  S);
+  }
+
+  {
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "amd64-pc-solaris2.11", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(
+TheDriver.BuildCompilation({"-v", "--gcc-toolchain=", "--sysroot="}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Selected GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Candidate multilib: .;@m64\n"
+  "Candidate multilib: 32;@m32\n"
+  "Selected multilib: .;@m64\n",
+  S);
+  }
+
+  {
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "x86_64-pc-solaris2.11", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(
+TheDriver.BuildCompilation({"-v", "--gcc-toolchain=", "--sysroot="}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0\n"
+  "Selected GCC installation: "
+  "/usr/gcc/11/lib/gcc/x86_6

[PATCH] D158056: [clang] Implement constexpr operator[] for vectors

2023-08-16 Thread Joey Rabil via Phabricator via cfe-commits
DaPorkchop_ created this revision.
DaPorkchop_ added reviewers: erichkeane, rsmith, efriedma, void.
Herald added a project: All.
DaPorkchop_ requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This implements the array subscript operator for vector types.

As vectors don't decay into pointers, I've opted to evaluate the vector
operand as an LValue, which still gives the expected behavior.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158056

Files:
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/State.h
  clang/test/SemaCXX/constexpr-vectors.cpp

Index: clang/test/SemaCXX/constexpr-vectors.cpp
===
--- clang/test/SemaCXX/constexpr-vectors.cpp
+++ clang/test/SemaCXX/constexpr-vectors.cpp
@@ -1,10 +1,4 @@
-// RUN: %clang_cc1 -std=c++14 -Wno-unused-value %s -disable-llvm-passes -triple x86_64-linux-gnu -emit-llvm -o - | FileCheck %s
-
-// FIXME: Unfortunately there is no good way to validate that our values are
-// correct since Vector types don't have operator [] implemented for constexpr.
-// Instead, we need to use filecheck to ensure the emitted IR is correct. Once
-// someone implements array subscript operator for these types as constexpr,
-// this test should modified to jsut use static asserts.
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-linux-gnu -Wno-unused-value %s
 
 using FourCharsVecSize __attribute__((vector_size(4))) = char;
 using FourIntsVecSize __attribute__((vector_size(16))) = int;
@@ -50,6 +44,12 @@
 a != b;   \
 a &&b;\
 a || b;   \
+a += a[1];\
+a[1] += 1;\
+a[1] = 1; \
+a[1] = b[1];  \
+a[1]++;   \
+++a[1];   \
 auto c = (a, b);  \
 return c; \
   }
@@ -92,6 +92,15 @@
 MathShiftOpsInts(FourIntsExtVec);
 MathShiftOpsInts(FourLongLongsExtVec);
 
+template
+constexpr bool VectorsEqual(T a, U b) {
+  for (unsigned I = 0; I < 4; ++I) {
+if (a[I] != b[I])
+  return false;
+  }
+  return true;
+}
+
 template 
 constexpr auto CmpMul(T t, U u) {
   t *= u;
@@ -150,564 +159,711 @@
   return t;
 }
 
+template 
+constexpr auto UpdateElementsInPlace(T t, U u) {
+  t[0] += u[0];
+  t[1]++;
+  t[2] = 1;
+  return t;
+}
+
 // Only int vs float makes a difference here, so we only need to test 1 of each.
 // Test Char to make sure the mixed-nature of shifts around char is evident.
 void CharUsage() {
   constexpr auto a = FourCharsVecSize{6, 3, 2, 1} +
  FourCharsVecSize{12, 15, 5, 7};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(a, FourCharsVecSize{18, 18, 7, 8}), "");
+
   constexpr auto b = FourCharsVecSize{19, 15, 13, 12} -
  FourCharsVecSize{13, 14, 5, 3};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(b, FourCharsVecSize{6, 1, 8, 9}), "");
+
   constexpr auto c = FourCharsVecSize{8, 4, 2, 1} *
  FourCharsVecSize{3, 4, 5, 6};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(c, FourCharsVecSize{24, 16, 10, 6}), "");
+
   constexpr auto d = FourCharsVecSize{12, 12, 10, 10} /
  FourCharsVecSize{6, 4, 5, 2};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(d, FourCharsVecSize{2, 3, 2, 5}), "");
+
   constexpr auto e = FourCharsVecSize{12, 12, 10, 10} %
  FourCharsVecSize{6, 4, 4, 3};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(e, FourCharsVecSize{0, 0, 2, 1}), "");
 
   constexpr auto f = FourCharsVecSize{6, 3, 2, 1} + 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(f, FourCharsVecSize{9, 6, 5, 4}), "");
+
   constexpr auto g = FourCharsVecSize{19, 15, 12, 10} - 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(g, FourCharsVecSize{16, 12, 9, 7}), "");
+
   constexpr auto h = FourCharsVecSize{8, 4, 2, 1} * 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(h, FourCharsVecSize{24, 12, 6, 3}), "");
+
   constexpr auto j = FourCharsVecSize{12, 15, 18, 21} / 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(j, FourCharsVecSize{4, 5, 6, 7}), "");
+
   constexpr auto k = FourCharsVecSize{12, 17, 19, 22} % 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(k, FourCharsVecSize{0, 2, 1, 1}), "");
 
   constexpr auto l = 3 + FourCharsVecSize{6, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(l, FourCharsVecSize{9, 6, 5, 4}), "");
+
   constexpr auto m = 20 - FourCharsVecSize{19, 15, 12, 10};
-  // CHECK: 

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

hey @victorkingi , I am still unsure about parsing these remarks options in two 
places:

- CompilerInvocation.cpp
- ExecuteCompilerInvocation.cpp

I think that it is important to clarify the relations between the two. In 
particular, it's normally the job of CompilerInvocaiton to make sure that e.g. 
`-Rpass -Rno-pass -Rpass` == `-Rpass` (so that `DiagnosticOptions::Remarks` 
only contains `-Rpass`). This might be tricky in practice if we want to support 
Regex, but would be good to document when e.g. populating 
`DiagnosticOptions::Remarks`.

I am also under the impression that extra complexity comes from the fact that 
this patch strives to support `-R` on top of 
`-R{no}pass`, `-R{no}pass-missed`, `-R{no}pass-analysis`. I also see some code 
left to support regex versions of the flags. Can you clean that up?




Comment at: flang/include/flang/Frontend/CodeGenOptions.h:76-81
+RK_Missing,// Remark argument not present on the command line.
+RK_Enabled,// Remark enabled via '-Rgroup'.
+RK_EnabledEverything,  // Remark enabled via '-Reverything'.
+RK_Disabled,   // Remark disabled via '-Rno-group'.
+RK_DisabledEverything, // Remark disabled via '-Rno-everything'.
+RK_WithPattern,// Remark pattern specified via '-Rgroup=regexp'.

I only see `RK_Enabled` and `RK_Disabled` being used, though I don't see 
`-Rgroup` nor `-Rno-group` being tested 🤔 .



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:227
 
+  // Specifies, using a regex, which successful optimization passes done,
+  // to include in the final optimization record file generated. If not 
provided

Do you know whether that only includes middle-end, or also back-end passes?



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:240
+  // OptimizationRemark, OptimizationRemarkMissed and 
OptimizationRemarkAnalysis
+  // contain regex values which are used in optimizationRemarkHandler in
+  // FrontendActions.cpp to determine which remarks generated should be 
outputed

`optimizationRemarkHandler` is a member method of `DiagnosticHandler`, that you 
specialise in FrontendActions.cpp, right?



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:1034-1037
+  // Add the remark option requested i.e. pass, pass-missed or pass-analysis.
+  // This will be used later during processing warnings and remarks to give
+  // messages specific to a remark argument. That happens in
+  // processWarningOptions in ExecuteCompilerInvocation.cpp

How about:
```
Preserve all the remark options requested, e.g. -Rpass, -Rpass-missed or 
-Rpass-analysis. This will be used later when processing and outputting the 
remarks generated by LLVM in  ExecuteCompilerInvocation.cpp.
```



Comment at: flang/lib/Frontend/FrontendActions.cpp:976-1011
+  void
+  optimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &d) {
+if (d.isPassed()) {
+  // Optimization remarks are active only if the -Rpass flag has a regular
+  // expression that matches the name of the pass name in \p d.
+  if (codeGenOpts.OptimizationRemark.patternMatches(d.getPassName()))
+emitOptimizationMessage(

victorkingi wrote:
> awarzynski wrote:
> > 
> The if statement still needs to return if the pattern doesn't match, should I 
> leave it the way it is?
Sorry, my bad, I missed that. Yeah, then leave it as is, but could you replace 
`const llvm::DiagnosticInfoOptimizationBase &d` with something with more 
descriptive name? (I am referring to `d`)



Comment at: flang/lib/Frontend/TextDiagnosticPrinter.cpp:18
 #include "flang/Frontend/TextDiagnosticPrinter.h"
+#include "filesystem"
 #include "flang/Frontend/TextDiagnostic.h"

WOuld you be able to use 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/Support/Path.h 
instead?



Comment at: flang/lib/Frontend/TextDiagnosticPrinter.cpp:21
+#include "string"
+#include "vector"
 #include "clang/Basic/DiagnosticOptions.h"

Would you be able to use 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/SmallVector.h
 instead?



Comment at: flang/lib/Frontend/TextDiagnosticPrinter.cpp:23
 #include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/ADT/SmallString.h"

Is this needed?



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:122-146
+static void processRemarkOptions(clang::DiagnosticsEngine &diags,
+ const clang::DiagnosticOptions &opts,
+ bool reportDiags = true) {
+  llvm::SmallVector _diags;
+  const llvm::IntrusiveRefCntPtr diagIDs =
+  diags.getDiagnosticIDs();
+

I am suggest

[clang] 373fcd5 - [clang] Use RecoveryExprs for broken defaultargs, instead of OpaqueValueExprs

2023-08-16 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-08-16T10:22:16+02:00
New Revision: 373fcd5d73a3ed5bedff771bcf6a3aba981155cc

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

LOG: [clang] Use RecoveryExprs for broken defaultargs, instead of 
OpaqueValueExprs

This makes sure we can preserve invalid-ness for consumers of this
node, it prevents crashes. It also aligns better with rest of the places that
store invalid expressions.

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

Added: 
clang/test/AST/ast-dump-default-arg-recovery.cpp

Modified: 
clang-tools-extra/clangd/unittests/HoverTests.cpp
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseCXXInlineMethods.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/Index/complete-optional-params.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 2ad7f0ee55d726..9cab9a086958d6 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -2543,6 +2543,19 @@ TEST(Hover, All) {
 HI.Type = "Test &&";
 HI.Definition = "Test &&test = {}";
   }},
+  {
+  R"cpp(// Shouldn't crash when evaluating the initializer.
+struct Bar {}; // error-ok
+struct Foo { void foo(Bar x = y); }
+void Foo::foo(Bar [[^x]]) {})cpp",
+  [](HoverInfo &HI) {
+HI.Name = "x";
+HI.Kind = index::SymbolKind::Parameter;
+HI.NamespaceScope = "";
+HI.LocalScope = "Foo::foo::";
+HI.Type = "Bar";
+HI.Definition = "Bar x = ()";
+  }},
   {
   R"cpp(// auto on alias
   typedef int int_type;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 8a63f10a6e1561..05a0e43b5b73d9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3022,7 +3022,8 @@ class Sema final {
  Expr *defarg);
   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
  SourceLocation ArgLoc);
-  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
+  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
+  Expr* DefaultArg);
   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
  SourceLocation EqualLoc);
   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,

diff  --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp 
b/clang/lib/Parse/ParseCXXInlineMethods.cpp
index 4951eb9aa2802a..573c90a36eeab3 100644
--- a/clang/lib/Parse/ParseCXXInlineMethods.cpp
+++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp
@@ -395,9 +395,10 @@ void 
Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
 DefArgResult = ParseBraceInitializer();
   } else
 DefArgResult = ParseAssignmentExpression();
-  DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
+  DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult, Param);
   if (DefArgResult.isInvalid()) {
-Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
+Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
+   /*DefaultArg=*/nullptr);
   } else {
 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
   // The last two tokens are the terminator and the saved value of

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index b5a3ee1eaf076d..cd7c5dcf275c04 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7548,7 +7548,8 @@ void Parser::ParseParameterDeclarationClause(
   } else {
 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
   Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
-  Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
+  Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
+ /*DefaultArg=*/nullptr);
   // Skip the statement expression and continue parsing
   SkipUntil(tok::comma, StopBeforeMatch);
   continue;
@@ -7557,7 +7558,8 @@ void Parser::ParseParameterDeclarationClause(
   }
   DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
   if (DefArgResult.isInvalid()) {
-Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
+Actions.ActOnParamDefaul

[PATCH] D157868: [clang] Use RecoveryExprs for broken defaultargs, instead of OpaqueValueExprs

2023-08-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
kadircet marked 3 inline comments as done.
Closed by commit rG373fcd5d73a3: [clang] Use RecoveryExprs for broken 
defaultargs, instead of OpaqueValueExprs (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D157868?vs=549939&id=550659#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157868

Files:
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/AST/ast-dump-default-arg-recovery.cpp
  clang/test/Index/complete-optional-params.cpp

Index: clang/test/Index/complete-optional-params.cpp
===
--- clang/test/Index/complete-optional-params.cpp
+++ clang/test/Index/complete-optional-params.cpp
@@ -79,7 +79,7 @@
 // CHECK-CC5-NEXT: Objective-C interface
 
 // RUN: c-index-test -code-completion-at=%s:17:11 %s | FileCheck -check-prefix=CHECK-CC6 %s
-// CHECK-CC6: FunctionDecl:{ResultType void}{TypedText foo_2}{LeftParen (}{Optional {Placeholder Bar1 b1 = Bar1()}{Optional {Comma , }{Placeholder Bar2 b2}}}{RightParen )} (50)
+// CHECK-CC6: FunctionDecl:{ResultType void}{TypedText foo_2}{LeftParen (}{Optional {Placeholder Bar1 b1 = Bar1()}{Optional {Comma , }{Placeholder Bar2 b2 = Bar2()}}}{RightParen )} (50)
 // CHECK-CC6: Completion contexts:
 // CHECK-CC6-NEXT: Any type
 // CHECK-CC6-NEXT: Any value
Index: clang/test/AST/ast-dump-default-arg-recovery.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-default-arg-recovery.cpp
@@ -0,0 +1,8 @@
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -ast-dump -frecovery-ast %s | FileCheck %s
+
+void foo();
+void fun(int arg = foo());
+//  CHECK: -ParmVarDecl {{.*}}  col:14 invalid arg 'int' cinit
+// CHECK-NEXT:   -RecoveryExpr {{.*}}  'int' contains-errors
+// Make sure we also preserve structure of the errorneous expression
+//  CHECK: -DeclRefExpr {{.*}}  'void ()' {{.*}} 'foo'
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/RecursiveASTVisitor.h"
@@ -37,11 +38,13 @@
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/Ownership.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/Template.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallString.h"
@@ -329,23 +332,16 @@
   ParmVarDecl *Param = cast(param);
   UnparsedDefaultArgLocs.erase(Param);
 
-  auto Fail = [&] {
-Param->setInvalidDecl();
-Param->setDefaultArg(new (Context) OpaqueValueExpr(
-EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
-  };
-
   // Default arguments are only permitted in C++
   if (!getLangOpts().CPlusPlus) {
 Diag(EqualLoc, diag::err_param_default_argument)
   << DefaultArg->getSourceRange();
-return Fail();
+return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
   }
 
   // Check for unexpanded parameter packs.
-  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
-return Fail();
-  }
+  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
+return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
 
   // C++11 [dcl.fct.default]p3
   //   A default argument expression [...] shall not be specified for a
@@ -360,14 +356,14 @@
 
   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
   if (Result.isInvalid())
-return Fail();
+return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
 
   DefaultArg = Result.getAs();
 
   // Check that the default argument is well-formed
   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
   if (DefaultArgChecker.Visit(DefaultArg))
-return Fail();
+return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
 
   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
 }
@@ -389,16 +385,23 @@
 
 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
 /// the default argument for the parameter param failed.
-void Sema::ActOnParamDefaultArgumentError(Decl *par

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread Thorsten via Phabricator via cfe-commits
tschuett added inline comments.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:227
 
+  // Specifies, using a regex, which successful optimization passes done,
+  // to include in the final optimization record file generated. If not 
provided

awarzynski wrote:
> Do you know whether that only includes middle-end, or also back-end passes?
I use -Rpass-missed='gisel*'  for GlobalIsel aka backend. I am interested in 
doing that exercise with Flang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[clang] 18252e6 - [Driver][unittest] Unbreak ToolChainTest.cpp compilation with -Werror

2023-08-16 Thread Rainer Orth via cfe-commits

Author: Rainer Orth
Date: 2023-08-16T10:37:14+02:00
New Revision: 18252e6c8e2b1bb9901b5cca9e9a75edfeda2c4e

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

LOG: [Driver][unittest] Unbreak ToolChainTest.cpp compilation with -Werror

D157275 broke some buildbots that run with -Werror:

https://lab.llvm.org/buildbot#builders/36/builds/36604
https://lab.llvm.org/buildbot#builders/57/builds/29201

Avoid this by using an overlong line rather than appeasing `clang-format`.

Added: 


Modified: 
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index bf61d428448289..ae567abb81a9bb 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -183,8 +183,7 @@ TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
   "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/32/crtbegin.o",
   "/usr/gcc/7/lib/gcc/x86_64-pc-solaris2.11/7.5.0/crtbegin.o",
   "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/crtbegin.o",
-  "/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/sparcv8plus/"
-  "crtbegin.o",
+  
"/usr/gcc/11/lib/gcc/sparcv9-sun-solaris2.11/11.4.0/sparcv8plus/crtbegin.o",
   "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/32/crtbegin.o",
   "/usr/gcc/11/lib/gcc/x86_64-pc-solaris2.11/11.4.0/crtbegin.o",
   "/usr/gcc/4.7/lib/gcc/i386-pc-solaris2.11/4.7.3/amd64/crtbegin.o",



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


[PATCH] D157963: [clang-format] Annotate constructor/destructor names

2023-08-16 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3103
+  if (!Next)
+return Next;
+  if (Next->is(tok::comment))

HazardyKnusperkeks wrote:
> Is a bit clearer.
I moved this function up to here from below and only removed a couple of 
`const`s. I can clean it up in another patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157963

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


[PATCH] D157905: [include-cleaner] Filter references to identity macros

2023-08-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 550662.
kadircet marked an inline comment as done.
kadircet added a comment.

- Rename helper, update comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157905

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


Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -483,5 +483,29 @@
 Pair(Code.point("partial"), UnorderedElementsAre(Partial);
 }
 
+TEST_F(WalkUsedTest, IgnoresIdentityMacros) {
+  llvm::Annotations Code(R"cpp(
+  #include "header.h"
+  void $bar^bar() {
+$stdin^stdin();
+  }
+  )cpp");
+  Inputs.Code = Code.code();
+  Inputs.ExtraFiles["header.h"] = guard(R"cpp(
+  #include "inner.h"
+  void stdin();
+  )cpp");
+  Inputs.ExtraFiles["inner.h"] = guard(R"cpp(
+  #define stdin stdin
+  )cpp");
+
+  TestAST AST(Inputs);
+  auto &SM = AST.sourceManager();
+  auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
+  EXPECT_THAT(offsetToProviders(AST, SM),
+  UnorderedElementsAre(
+  // FIXME: we should have a reference from stdin to header.h
+  Pair(Code.point("bar"), UnorderedElementsAre(MainFile;
+}
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/lib/Analysis.cpp
===
--- clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -28,10 +28,29 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 #include 
 
 namespace clang::include_cleaner {
 
+namespace {
+bool shouldIgnoreMacroReference(const Macro &M) {
+  static const auto *MacroNamesToIgnore = new llvm::StringSet<>{
+  // C standard says these are implementation defined macros, hence most of
+  // the standard library providers implement it by defining these as 
macros
+  // that resolve to themselves.
+  // This results in surprising behavior from users point of view (we
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false negatives by treating declarations
+  // resulting from these expansions as used.
+  "stdin",
+  "stdout",
+  "stderr",
+  };
+  return MacroNamesToIgnore->contains(M.Name->getName());
+}
+} // namespace
+
 void walkUsed(llvm::ArrayRef ASTRoots,
   llvm::ArrayRef MacroRefs,
   const PragmaIncludes *PI, const SourceManager &SM,
@@ -51,7 +70,8 @@
   }
   for (const SymbolReference &MacroRef : MacroRefs) {
 assert(MacroRef.Target.kind() == Symbol::Macro);
-if (!SM.isWrittenInMainFile(SM.getSpellingLoc(MacroRef.RefLocation)))
+if (!SM.isWrittenInMainFile(SM.getSpellingLoc(MacroRef.RefLocation)) ||
+shouldIgnoreMacroReference(MacroRef.Target.macro()))
   continue;
 CB(MacroRef, headersForSymbol(MacroRef.Target, SM, PI));
   }


Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -483,5 +483,29 @@
 Pair(Code.point("partial"), UnorderedElementsAre(Partial);
 }
 
+TEST_F(WalkUsedTest, IgnoresIdentityMacros) {
+  llvm::Annotations Code(R"cpp(
+  #include "header.h"
+  void $bar^bar() {
+$stdin^stdin();
+  }
+  )cpp");
+  Inputs.Code = Code.code();
+  Inputs.ExtraFiles["header.h"] = guard(R"cpp(
+  #include "inner.h"
+  void stdin();
+  )cpp");
+  Inputs.ExtraFiles["inner.h"] = guard(R"cpp(
+  #define stdin stdin
+  )cpp");
+
+  TestAST AST(Inputs);
+  auto &SM = AST.sourceManager();
+  auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
+  EXPECT_THAT(offsetToProviders(AST, SM),
+  UnorderedElementsAre(
+  // FIXME: we should have a reference from stdin to header.h
+  Pair(Code.point("bar"), UnorderedElementsAre(MainFile;
+}
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/lib/Analysis.cpp
===
--- clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -28,10 +28,29 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 #include 
 
 namespace clang::include_cleaner {
 
+namespace {
+bool shouldIgnoreMacroReference(const Macro &M) {
+ 

[PATCH] D157905: [include-cleaner] Filter references to identity macros

2023-08-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:43
+  // This results in surprising behavior from users point of view (we
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false positives by treating declarations

sammccall wrote:
> Comment nit: I'm having trouble imagining cases that are actually*unrelated* 
> to the stdlib.
> 
> If `stderr` is an impl-defined macro, then the only way to use the name to 
> refer to something else is if it's not defined (inside ifndef stderr, or if 
> you can be sure your TU doesn't include stdio first). Seems implausible...
> 
> That said I feel like we've had this conversation before and I've just 
> forgotten the details.
> If stderr is an impl-defined macro, then the only way to use the name to 
> refer to something else is if it's not defined

That's absolutely right. The issue here is macro expansion triggers independent 
of the context, e.g.
```
#include 
namespace ns { void stderr(); }
void foo() { ns::stderr(); }
```

here we have a (well two) reference to `stderr` macro from stdandard library, 
which is not user's intent, but rather a quirk of the language.



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:44
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false positives by treating declarations
+  // resulting from these expansions as used.

sammccall wrote:
> Nit: "false positives" is a little unclear: positives for this function are 
> negatives for walkAST and could be either for diagnostics.
> 
> Also, I think you mean *references* rather than declarations?
> 
this should've been "false negatives" from the "usedness perspective", we 
basically drop the reference to `ns::stderr` in above example, because the name 
is not spelled in the main file (but rather spelled inside a macro body).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157905

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


[PATCH] D157680: [X86]Support options -mno-gather -mno-scatter

2023-08-16 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei 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/D157680/new/

https://reviews.llvm.org/D157680

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


[PATCH] D157905: [include-cleaner] Filter references to identity macros

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.

still LG, comments are still confusing me a little




Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:43
+  // This results in surprising behavior from users point of view (we
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false positives by treating declarations

kadircet wrote:
> sammccall wrote:
> > Comment nit: I'm having trouble imagining cases that are 
> > actually*unrelated* to the stdlib.
> > 
> > If `stderr` is an impl-defined macro, then the only way to use the name to 
> > refer to something else is if it's not defined (inside ifndef stderr, or if 
> > you can be sure your TU doesn't include stdio first). Seems implausible...
> > 
> > That said I feel like we've had this conversation before and I've just 
> > forgotten the details.
> > If stderr is an impl-defined macro, then the only way to use the name to 
> > refer to something else is if it's not defined
> 
> That's absolutely right. The issue here is macro expansion triggers 
> independent of the context, e.g.
> ```
> #include 
> namespace ns { void stderr(); }
> void foo() { ns::stderr(); }
> ```
> 
> here we have a (well two) reference to `stderr` macro from stdandard library, 
> which is not user's intent, but rather a quirk of the language.
Sure, but this code is not valid C++ (since `stderr` is not guaranteed to 
expand to a single identifier). Is this actually a common/motivating case?



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:44
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false positives by treating declarations
+  // resulting from these expansions as used.

kadircet wrote:
> sammccall wrote:
> > Nit: "false positives" is a little unclear: positives for this function are 
> > negatives for walkAST and could be either for diagnostics.
> > 
> > Also, I think you mean *references* rather than declarations?
> > 
> this should've been "false negatives" from the "usedness perspective", we 
> basically drop the reference to `ns::stderr` in above example, because the 
> name is not spelled in the main file (but rather spelled inside a macro body).
And now it's backwards if your perspective is this function itself!

just avoid "false positives"/"false negatives" terminology and describe the 
actual effect?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157905

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

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

In D156312#4589251 , @steakhal wrote:

> I don't think we should do anything about it unless it's frequent enough.
> Try to come up with a heuristic to be able to measure how often this happens, 
> if you really care.
> Once you have a semi-working heuristic for determining if that bugpath 
> suffers from this, you can as well use it for marking the bugreport invalid 
> if that's the case to lean towards suppressing those FPs.

Minor clarification: these are not FPs, these are true positives with a bad 
error message. I was annoyed when I found this surprising bug on the 
almost-ready checker that I was working on; but I wouldn't say that this is an 
especially severe issue.

In D156312#4589251 , @steakhal wrote:

> I don't think it's completely necessary to fix those FPs to land this. I 
> think of that as an improvement, on top of this one.
> I hope I clarified my standpoint.

I agree, I'll create a new revision which mentions this checker in the release 
notes, and I hope that I'll be able to merge that. Later I'll try to return to 
this question with either an engine improvement or a heuristic mitigation.




Comment at: clang/test/Analysis/bitwise-shift-sanity-checks.c:70-74
+  if (right < 0)
+return 0;
+  return left << (right + 32);
+  // expected - warning@-1 {{Left shift overflows the capacity of 'int'}}
+  // expected-warning@-2 {{Right operand is negative in left shift}}

steakhal wrote:
> Let's be explicit about the actual assumed value range, and use 
> `clang_analyzer_value()`.
> I also recommend using an explicit FIXME for calling out what should be 
> there, instead of abusing a non-matching `expected` pattern. I know I used 
> that in the past, and probably seen it from me. I feel ashamed that I did 
> that. I know I did that to have cleaner diffs, once fixed, but I honestly 
> think it does more harm than good.
I already tried calling `clang_analyzer_value()` at that point when I was 
investigating, but unfortunately it won't say anything useful because the 
actual range corresponding to the symbolic expression is only calculated when 
the `evalBinOp()` calls examine it.

I'll change the "expected - warning" to a FIXME.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156312

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


[PATCH] D157837: [flang][driver] Update the visibility of Clang options in Flang

2023-08-16 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 550668.
awarzynski added a comment.

Rebase on top of main


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157837

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fast_math.f90

Index: flang/test/Driver/fast_math.f90
===
--- flang/test/Driver/fast_math.f90
+++ flang/test/Driver/fast_math.f90
@@ -70,7 +70,7 @@
 ! UNSUPPORTED: system-windows
 ! UNSUPPORTED: target=powerpc{{.*}}
 ! RUN: %flang -ffast-math -### %s -o %t 2>&1 \
-! RUN:   --target=x86_64-unknown-linux -no-pie --gcc-toolchain="" \
+! RUN:   --target=x86_64-unknown-linux -no-pie \
 ! RUN:   --sysroot=%S/../../../clang/test/Driver/Inputs/basic_linux_tree \
 ! RUN: | FileCheck --check-prefix=CHECK-CRT %s
 ! CHECK-CRT: {{crtbegin.?\.o}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -14,224 +14,242 @@
 ! HELP:USAGE: flang
 ! HELP-EMPTY:
 ! HELP-NEXT:OPTIONS:
-! HELP-NEXT: -###   Print (but do not run) the commands to run for this compilation
-! HELP-NEXT: -cpp   Enable predefined and command line preprocessor macros
-! HELP-NEXT: -c Only run preprocess, compile, and assemble steps
-! HELP-NEXT: -D = Define  to  (or 1 if  omitted)
-! HELP-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
-! HELP-NEXT: -E Only run the preprocessor
+! HELP-NEXT: -###Print (but do not run) the commands to run for this compilation
+! HELP-NEXT: -cppEnable predefined and command line preprocessor macros
+! HELP-NEXT: -c  Only run preprocess, compile, and assemble steps
+! HELP-NEXT: -D =  Define  to  (or 1 if  omitted)
+! HELP-NEXT: -emit-llvm  Use the LLVM representation for assembler and object files
+! HELP-NEXT: -E  Only run the preprocessor
 ! HELP-NEXT: -falternative-parameter-statement
-! HELP-NEXT: Enable the old style PARAMETER statement
-! HELP-NEXT: -fapprox-func  Allow certain math function calls to be replaced with an approximately equivalent calculation
-! HELP-NEXT: -fbackslashSpecify that backslash in string introduces an escape character
-! HELP-NEXT: -fcolor-diagnosticsEnable colors in diagnostics
-! HELP-NEXT: -fconvert=  Set endian conversion of data for unformatted files
-! HELP-NEXT: -fdefault-double-8 Set the default double precision kind to an 8 byte wide type
-! HELP-NEXT: -fdefault-integer-8Set the default integer and logical kind to an 8 byte wide type
-! HELP-NEXT: -fdefault-real-8   Set the default real kind to an 8 byte wide type
-! HELP-NEXT: -ffast-mathAllow aggressive, lossy floating-point optimizations
-! HELP-NEXT: -ffixed-form   Process source files in fixed form
+! HELP-NEXT: Enable the old style PARAMETER statement
+! HELP-NEXT: -fapprox-func   Allow certain math function calls to be replaced with an approximately equivalent calculation
+! HELP-NEXT: -fbackslash Specify that backslash in string introduces an escape character
+! HELP-NEXT: -fcolor-diagnostics Enable colors in diagnostics
+! HELP-NEXT: -fconvert=   Set endian conversion of data for unformatted files
+! HELP-NEXT: -fdefault-double-8  Set the default double precision kind to an 8 byte wide type
+! HELP-NEXT: -fdefault-integer-8 Set the default integer and logical kind to an 8 byte wide type
+! HELP-NEXT: -fdefault-real-8Set the default real kind to an 8 byte wide type
+! HELP-NEXT: -ffast-math Allow aggressive, lossy floating-point optimizations
+! HELP-NEXT: -ffixed-formProcess source files in fixed form
 ! HELP-NEXT: -ffixed-line-length=
-! HELP-NEXT: Use  as character line width in fixed mode
-! HELP-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
-! HELP-NEXT: -ffree-formProcess source files in free form
-! HELP-NEXT: -fimplicit-noneNo implicit typing allowed unless overridden by IMPLICIT statements
+! HELP-NEXT: Use  as character line width in fixed mode
+! HELP-NEXT: -ffp-contract=   Form fused FP ops (e.g. FMAs)
+! HELP-NEXT: -ffree-form Process source files in free form
+! HELP-NEXT: -fhonor-infinities  Specify that floating-point optimizations are not allowed that assume arguments and results are not +-inf.
+! HELP-NEXT: -fhonor-nansSpecify that floating-point optimizations are not allowed that assume arguments and results are not NANs.
+! HELP-NEXT: -fimpl

[PATCH] D157485: [X86][RFC] Support new feature AVX10

2023-08-16 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 550669.
pengfei marked an inline comment as done.
pengfei added a comment.

Address comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157485

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/X86.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/Targets/X86.cpp
  clang/lib/Driver/ToolChains/Arch/X86.cpp
  clang/test/CodeGen/X86/avx10-error.c
  clang/test/CodeGen/attr-target-x86.c
  clang/test/CodeGen/target-avx-abi-diag.c
  clang/test/Driver/x86-target-features.c
  clang/test/Preprocessor/x86_target_features.c
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/TargetParser/X86TargetParser.def
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp
  llvm/lib/Target/X86/X86.td
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/lib/Target/X86/X86Subtarget.h
  llvm/lib/TargetParser/Host.cpp
  llvm/lib/TargetParser/X86TargetParser.cpp
  llvm/test/CodeGen/X86/avx512-arith.ll
  llvm/test/CodeGen/X86/avx512-broadcast-arith.ll
  llvm/test/CodeGen/X86/avx512bw-arith.ll
  llvm/test/CodeGen/X86/avx512bwvl-arith.ll
  llvm/test/CodeGen/X86/avx512fp16-arith.ll
  llvm/test/CodeGen/X86/avx512vl-arith.ll

Index: llvm/test/CodeGen/X86/avx512vl-arith.ll
===
--- llvm/test/CodeGen/X86/avx512vl-arith.ll
+++ llvm/test/CodeGen/X86/avx512vl-arith.ll
@@ -1,5 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc < %s -mtriple=x86_64-apple-darwin -mcpu=knl -mattr=+avx512vl --show-mc-encoding| FileCheck %s
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -mattr=+avx10.1 --show-mc-encoding| FileCheck %s
 
 ; 256-bit
 
Index: llvm/test/CodeGen/X86/avx512fp16-arith.ll
===
--- llvm/test/CodeGen/X86/avx512fp16-arith.ll
+++ llvm/test/CodeGen/X86/avx512fp16-arith.ll
@@ -1,5 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc < %s -mtriple=x86_64-apple-darwin -mcpu=skx -mattr=+avx512fp16 | FileCheck %s
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -mattr=+avx10.1,+avx10-512bit | FileCheck %s
 
 define <32 x half> @vaddph_512_test(<32 x half> %i, <32 x half> %j) nounwind readnone {
 ; CHECK-LABEL: vaddph_512_test:
Index: llvm/test/CodeGen/X86/avx512bwvl-arith.ll
===
--- llvm/test/CodeGen/X86/avx512bwvl-arith.ll
+++ llvm/test/CodeGen/X86/avx512bwvl-arith.ll
@@ -1,5 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512bw,+avx512vl | FileCheck %s
+; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx10.1 | FileCheck %s
 
 ; 256-bit
 
Index: llvm/test/CodeGen/X86/avx512bw-arith.ll
===
--- llvm/test/CodeGen/X86/avx512bw-arith.ll
+++ llvm/test/CodeGen/X86/avx512bw-arith.ll
@@ -1,5 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512bw | FileCheck %s
+; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx10.1,+avx10-512bit | FileCheck %s
 
 define <64 x i8> @vpaddb512_test(<64 x i8> %i, <64 x i8> %j) nounwind readnone {
 ; CHECK-LABEL: vpaddb512_test:
Index: llvm/test/CodeGen/X86/avx512-broadcast-arith.ll
===
--- llvm/test/CodeGen/X86/avx512-broadcast-arith.ll
+++ llvm/test/CodeGen/X86/avx512-broadcast-arith.ll
@@ -1,6 +1,7 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc < %s -mtriple=x86_64-- -mattr=+avx512f   | FileCheck %s --check-prefixes=AVX512F
 ; RUN: llc < %s -mtriple=x86_64-- -mattr=+avx512f,+avx512bw | FileCheck %s --check-prefixes=AVX512BW
+; RUN: llc < %s -mtriple=x86_64-- -mattr=+avx10.1,+avx10-512bit | FileCheck %s --check-prefixes=AVX512BW
 
 ; PR34666
 define <64 x i8> @add_v64i8_broadcasts(<64 x i8> %a0, i64 %a1, i8 %a2) {
Index: llvm/test/CodeGen/X86/avx512-arith.ll
===
--- llvm/test/CodeGen/X86/avx512-arith.ll
+++ llvm/test/CodeGen/X86/avx512-arith.ll
@@ -4,6 +4,7 @@
 ; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512bw | FileCheck %s --check-prefix=CHECK --check-prefix=AVX512BW
 ; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512dq | FileCheck %s --check-prefix=CHECK --check-prefix=AVX512DQ
 ; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512dq,+avx512bw,+avx512vl | FileCheck %s --check-prefix=CHECK --check-prefix=SKX
+; R

[PATCH] D157485: [X86][RFC] Support new feature AVX10

2023-08-16 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:2581
+ unsigned VectorWidth) {
+  if (!getTarget().getTriple().isX86() || VectorWidth < 512)
+return;

skan wrote:
> Minor suggestion. The code here may be refined to be better extended by other 
> targets, like
> ```
>   llvm::Triple::ArchType ArchType =
>   getContext().getTargetInfo().getTriple().getArch();
> 
>   switch (ArchType) {
>   case llvm::Triple::x86:
>   case llvm::Triple::x86_64: {
>  
>}
>default:
> return;
> 
> ```
We have a few place code using `isX86`. I think it's more convenient to use a 
single condition. We can refactor when necessary.



Comment at: llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp:927
+  !STI.hasFeature(X86::FeatureAVX10_512bit))
+report_fatal_error("ZMM registers are not supported without AVX10-512BIT");
   switch (TSFlags & X86II::OpPrefixMask) {

skan wrote:
> skan wrote:
> > -mavx10.1 does not work for assembler. So if such instruction is generated 
> > w/o AVX10-512BIT support, it must be compiler's issue instead of user's. An 
> > `assert` should be more appropriate here.
> > -mavx10.1 does not work for assembler. So if such instruction is generated 
> > w/o AVX10-512BIT support, it must be compiler's issue instead of user's. An 
> > `assert` should be more appropriate here.
> 
> Reference: https://llvm.org/docs/CodingStandards.html#assert-liberally
We need to report fatal error for this case even if it's a compiler bug. 
Otherwise, user may observe the crash issue in runtime and hard to find the 
reason.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157485

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


[clang] d77cba6 - [Clang][DebugInfo] Emit narrower base types for structured binding declarations that bind to struct bitfields

2023-08-16 Thread Victor Campos via cfe-commits

Author: Victor Campos
Date: 2023-08-16T10:45:01+01:00
New Revision: d77cba6d474ab8ce5ece126499522de414c8089c

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

LOG: [Clang][DebugInfo] Emit narrower base types for structured binding 
declarations that bind to struct bitfields

In cases where a structured binding declaration is made to a struct with
bitfields:

struct A {
  unsigned int x : 16;
  unsigned int y : 16;
} g;

auto [a, b] = g; // structured binding declaration

Clang assigns the 'unsigned int' DWARF base type to 'a' and 'b' because
this is their deduced C++ type in the structured binding declaration.

However, their actual type in memory is 'unsigned short' as they have 16
bits allocated for each.

This is a problem for debug information consumers: if the debug
information for 'a' has the 'unsigned int' base type, a debugger will
assume it has 4 bytes, whereas it actually has a length of 2, resulting
in a read (or write) past its length.

This patch mimics GCC's behaviour: in case of structured bindings to
bitfields, the binding declaration's DWARF base type is of the target's
integer type with the same bitwidth as the bitfield.

If no suitable integer type is found in the target, no debug information
is emitted anymore in order to prevent wrong debug output.

Reviewed By: tmatheson

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

Added: 
clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDebugInfo.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index f049a682cfed6f..54e31bec0cc5bc 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4744,6 +4744,40 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const 
VarDecl *VD,
   return D;
 }
 
+llvm::DIType *CGDebugInfo::CreateBindingDeclType(const BindingDecl *BD) {
+  llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
+
+  // If the declaration is bound to a bitfield struct field, its type may have 
a
+  // size that is 
diff erent from its deduced declaration type's.
+  if (const MemberExpr *ME = dyn_cast(BD->getBinding())) {
+if (const FieldDecl *FD = dyn_cast(ME->getMemberDecl())) {
+  if (FD->isBitField()) {
+ASTContext &Context = CGM.getContext();
+const CGRecordLayout &RL =
+CGM.getTypes().getCGRecordLayout(FD->getParent());
+const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
+
+// Find an integer type with the same bitwidth as the bitfield size. If
+// no suitable type is present in the target, give up on producing 
debug
+// information as it would be wrong. It is certainly possible to 
produce
+// correct debug info, but the logic isn't currently implemented.
+uint64_t BitfieldSizeInBits = Info.Size;
+QualType IntTy =
+Context.getIntTypeForBitwidth(BitfieldSizeInBits, Info.IsSigned);
+if (IntTy.isNull())
+  return nullptr;
+Qualifiers Quals = BD->getType().getQualifiers();
+QualType FinalTy = Context.getQualifiedType(IntTy, Quals);
+llvm::DIType *Ty = getOrCreateType(FinalTy, Unit);
+assert(Ty);
+return Ty;
+  }
+}
+  }
+
+  return getOrCreateType(BD->getType(), Unit);
+}
+
 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
 llvm::Value *Storage,
 std::optional ArgNo,
@@ -4758,8 +4792,7 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const 
BindingDecl *BD,
   if (isa(BD->getBinding()))
 return nullptr;
 
-  llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
-  llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
+  llvm::DIType *Ty = CreateBindingDeclType(BD);
 
   // If there is no debug info for this type then do not emit debug info
   // for this variable.
@@ -4785,6 +4818,7 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const 
BindingDecl *BD,
   unsigned Column = getColumnNumber(BD->getLocation());
   StringRef Name = BD->getName();
   auto *Scope = cast(LexicalBlockStack.back());
+  llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
   // Create the descriptor for the variable.
   llvm::DILocalVariable *D = DBuilder.createAutoVariable(
   Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
@@ -4800,6 +4834,11 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const 
BindingDecl *BD,
   const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
 
   if (fieldOffset != 0) {
+// Currently if the field offset is not a multiple of byte, the 
produced
+// location would not be acc

[PATCH] D157479: [Clang][DebugInfo] Emit narrower base types for structured binding declarations that bind to struct bitfields

2023-08-16 Thread Victor Campos via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
vhscampos marked an inline comment as done.
Closed by commit rGd77cba6d474a: [Clang][DebugInfo] Emit narrower base types 
for structured binding declarations… (authored by vhscampos).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157479

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp

Index: clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
@@ -0,0 +1,285 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone -triple aarch64-arm-none-eabi %s -o - | FileCheck %s
+
+struct S0 {
+  unsigned int x : 16;
+  unsigned int y : 16;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS0v
+// CHECK:alloca %struct.S0, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S0_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+//
+void fS0() {
+  S0 s0;
+  auto [a, b] = s0;
+}
+
+struct S1 {
+  volatile unsigned int x : 16;
+  volatile unsigned int y : 16;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS1v
+// CHECK:alloca %struct.S1, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S1, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S1_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S1_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+//
+void fS1() {
+  S1 s1;
+  auto [a, b] = s1;
+}
+
+struct S2 {
+  unsigned int x : 8;
+  unsigned int y : 8;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS2v
+// CHECK:alloca %struct.S2, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S2, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S2_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S2_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 1))
+//
+void fS2() {
+  S2 s2;
+  auto [a, b] = s2;
+}
+
+struct S3 {
+  volatile unsigned int x : 8;
+  volatile unsigned int y : 8;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS3v
+// CHECK:alloca %struct.S3, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S3, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S3_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S3_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 1))
+//
+void fS3() {
+  S3 s3;
+  auto [a, b] = s3;
+}
+
+struct S4 {
+  unsigned int x : 8;
+  unsigned int y : 16;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS4v
+// CHECK:alloca %struct.S4, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S4, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S4_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S4_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 1))
+//
+void fS4() {
+  S4 s4;
+  auto [a, b] = s4;
+}
+
+struct S5 {
+  volatile unsigned int x : 8;
+  volatile unsigned int y : 16;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS5v
+// CHECK:alloca %struct.S5, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S5, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S5_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S5_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 1))
+//
+void fS5() {
+  S5 s5;
+  auto [a, b] = s5;
+}
+
+struct S6 {
+  unsigned int x : 16;
+  unsigned int y : 8;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS6v
+// CHECK:alloca %struct.S6, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S6, align 4
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S6_A:![0-9]+]], metadata !DIExpression())
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata [[S6_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+//
+void fS6() {
+  S6 s6;
+  auto [a, b] = s6;
+}
+
+struct S7 {
+  volatile unsigned int x : 16;
+  volatile unsigned int y : 8;
+};
+
+// CHECK-LABEL: define dso_local void @_Z3fS7v
+// CHECK:

[PATCH] D158061: [clang] Construct ExprRequirement with SubstitutionDiagnostic on SubstFailure

2023-08-16 Thread Younan Zhang via Phabricator via cfe-commits
zyounan created this revision.
zyounan added reviewers: saar.raz, erichkeane, ilya-biryukov, aaron.ballman.
Herald added a subscriber: kadircet.
Herald added a project: All.
zyounan published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We're expecting a SubstitutionDiagnostic in diagnoseUnsatisfiedRequirement
if the status of ExprRequirement is SubstFailure. Previously, the Requirement
was created with Expr on SubstFailure by mistake, which could lead to the
assertion failure in the subsequent diagnosis.

Fixes https://github.com/clangd/clangd/issues/1726
Fixes https://github.com/llvm/llvm-project/issues/64723
Fixes https://github.com/llvm/llvm-project/issues/64172

In addition, this patch also fixes an invalid test from D129499 
.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158061

Files:
  clang/include/clang/AST/ExprConcepts.h
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
  clang/test/SemaCXX/concept-fatal-error.cpp

Index: clang/test/SemaCXX/concept-fatal-error.cpp
===
--- clang/test/SemaCXX/concept-fatal-error.cpp
+++ clang/test/SemaCXX/concept-fatal-error.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
 
 template 
 concept f = requires { 42; };
@@ -6,5 +6,5 @@
   // The missing semicolon will trigger an error and -ferror-limit=1 will make it fatal
   // We test that we do not crash in such cases (#55401)
   int i = requires { { i } f } // expected-error {{expected ';' at end of declaration list}}
-   // expected-error@* {{too many errros emitted}}
+   // expected-error@* {{too many errors emitted}}
 };
Index: clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+
+template  class normal_iterator {};
+
+template  struct is_convertible {};
+
+template 
+inline constexpr bool is_convertible_v = is_convertible::value; // #1
+
+// expected-error@#1 {{no member named 'value' in 'is_convertible'}}
+
+template 
+concept convertible_to = is_convertible_v; // expected-note 0+{{}}
+template 
+  requires requires(IteratorL lhs, IteratorR rhs) { // expected-note 0+{{}}
+{ lhs == rhs } -> convertible_to; // #2
+  }
+constexpr bool compare(normal_iterator lhs, normal_iterator rhs) {
+  return false;
+}
+
+// We don't know exactly the substituted type for `lhs == rhs`, thus a placeholder 'expr-type' is emitted.
+// expected-note@#2 {{'convertible_to'}}
+
+// Consume remaining notes/errors.
+// expected-note@* 0+{{}}
+// expected-error@* 0+{{}}
+class Object;
+
+void function() {
+  normal_iterator begin, end;
+  compare(begin, end);
+}
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2276,9 +2276,9 @@
   getPackIndex(Pack), Arg, TL.getNameLoc());
 }
 
-template
 static concepts::Requirement::SubstitutionDiagnostic *
-createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
+createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
+concepts::EntityPrinter Printer) {
   SmallString<128> Message;
   SourceLocation ErrorLoc;
   if (Info.hasSFINAEDiagnostic()) {
@@ -2302,6 +2302,19 @@
   StringRef(MessageBuf, Message.size())};
 }
 
+concepts::Requirement::SubstitutionDiagnostic *
+concepts::createSubstDiagAt(Sema &S, SourceLocation Location,
+EntityPrinter Printer) {
+  SmallString<128> Entity;
+  llvm::raw_svector_ostream OS(Entity);
+  Printer(OS);
+  char *EntityBuf = new (S.Context) char[Entity.size()];
+  llvm::copy(Entity, EntityBuf);
+  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
+  /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
+  /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
+}
+
 ExprResult TemplateInstantiator::TransformRequiresTypeParams(
 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
 RequiresExprBodyDecl *Body, ArrayRef Params,
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.

[PATCH] D158061: [clang] Construct ExprRequirement with SubstitutionDiagnostic on SubstFailure

2023-08-16 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 550683.
zyounan added a comment.

Rebase and format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158061

Files:
  clang/include/clang/AST/ExprConcepts.h
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
  clang/test/SemaCXX/concept-fatal-error.cpp

Index: clang/test/SemaCXX/concept-fatal-error.cpp
===
--- clang/test/SemaCXX/concept-fatal-error.cpp
+++ clang/test/SemaCXX/concept-fatal-error.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
 
 template 
 concept f = requires { 42; };
@@ -6,5 +6,5 @@
   // The missing semicolon will trigger an error and -ferror-limit=1 will make it fatal
   // We test that we do not crash in such cases (#55401)
   int i = requires { { i } f } // expected-error {{expected ';' at end of declaration list}}
-   // expected-error@* {{too many errros emitted}}
+   // expected-error@* {{too many errors emitted}}
 };
Index: clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+
+template  class normal_iterator {};
+
+template  struct is_convertible {};
+
+template 
+inline constexpr bool is_convertible_v = is_convertible::value; // #1
+
+// expected-error@#1 {{no member named 'value' in 'is_convertible'}}
+
+template 
+concept convertible_to = is_convertible_v; // expected-note 0+{{}}
+template 
+  requires requires(IteratorL lhs, IteratorR rhs) { // expected-note 0+{{}}
+{ lhs == rhs } -> convertible_to; // #2
+  }
+constexpr bool compare(normal_iterator lhs, normal_iterator rhs) {
+  return false;
+}
+
+// We don't know exactly the substituted type for `lhs == rhs`, thus a placeholder 'expr-type' is emitted.
+// expected-note@#2 {{'convertible_to'}}
+
+// Consume remaining notes/errors.
+// expected-note@* 0+{{}}
+// expected-error@* 0+{{}}
+class Object;
+
+void function() {
+  normal_iterator begin, end;
+  compare(begin, end);
+}
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2271,9 +2271,9 @@
   getPackIndex(Pack), Arg, TL.getNameLoc());
 }
 
-template
 static concepts::Requirement::SubstitutionDiagnostic *
-createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
+createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
+concepts::EntityPrinter Printer) {
   SmallString<128> Message;
   SourceLocation ErrorLoc;
   if (Info.hasSFINAEDiagnostic()) {
@@ -2297,6 +2297,19 @@
   StringRef(MessageBuf, Message.size())};
 }
 
+concepts::Requirement::SubstitutionDiagnostic *
+concepts::createSubstDiagAt(Sema &S, SourceLocation Location,
+EntityPrinter Printer) {
+  SmallString<128> Entity;
+  llvm::raw_svector_ostream OS(Entity);
+  Printer(OS);
+  char *EntityBuf = new (S.Context) char[Entity.size()];
+  llvm::copy(Entity, EntityBuf);
+  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
+  /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
+  /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
+}
+
 ExprResult TemplateInstantiator::TransformRequiresTypeParams(
 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
 RequiresExprBodyDecl *Body, ArrayRef Params,
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
@@ -9078,12 +9079,18 @@
 SubstExpr(TC->getImmediatelyDeclaredConstraint(), MLTAL);
 if (Constraint.isInvalid()) {
   Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
-} else {
-  SubstitutedConstraintExpr =
-  cast(Constraint.get());
-  if (!SubstitutedConstraintExpr->isSatisfied())
-Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
-}
+  return new (Context) concepts::ExprRequirement(
+  concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
+  [IDC, this](llvm::raw_ostream &OS) {
+IDC->printPretty(O

[PATCH] D158065: [PowerPC] Implement builtin for mffsl

2023-08-16 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: nemanjai, stefanp, shchenz, PowerPC.
Herald added subscribers: kbarton, hiraditya.
Herald added a project: All.
qiucf requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

`mffsl` is available since ISA 3.0.

GCC emits extra code to support `__builtin_mffsl` on targets earlier than 
Power9, while this patch doesn't do it. In this patch it is actually named 
`__builtin_ppc_mffsl` to follow our convention.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158065

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/test/CodeGen/PowerPC/builtins-ppc.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCInstrInfo.td
  llvm/test/CodeGen/PowerPC/read-set-flm.ll


Index: llvm/test/CodeGen/PowerPC/read-set-flm.ll
===
--- llvm/test/CodeGen/PowerPC/read-set-flm.ll
+++ llvm/test/CodeGen/PowerPC/read-set-flm.ll
@@ -148,8 +148,19 @@
   ret void
 }
 
+define double @mffsl() {
+; CHECK-LABEL: mffsl:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:mffsl 1
+; CHECK-NEXT:blr
+entry:
+  %x = call double @llvm.ppc.mffsl()
+  ret double %x
+}
+
 declare void @effect_func()
 declare void @readonly_func() #1
+declare double @llvm.ppc.mffsl()
 declare double @llvm.ppc.readflm()
 declare double @llvm.ppc.setflm(double)
 declare double @llvm.experimental.constrained.fadd.f64(double, double, 
metadata, metadata)
Index: llvm/lib/Target/PowerPC/PPCInstrInfo.td
===
--- llvm/lib/Target/PowerPC/PPCInstrInfo.td
+++ llvm/lib/Target/PowerPC/PPCInstrInfo.td
@@ -3180,6 +3180,7 @@
   (TCRETURNri CTRRC:$dst, imm:$imm)>;
 
 def : Pat<(int_ppc_readflm), (MFFS)>;
+def : Pat<(int_ppc_mffsl), (MFFSL)>;
 
 // Hi and Lo for Darwin Global Addresses.
 def : Pat<(PPChi tglobaladdr:$in, 0), (LIS tglobaladdr:$in)>;
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -33,6 +33,10 @@
   def int_ppc_readflm : ClangBuiltin<"__builtin_readflm">,
 DefaultAttrsIntrinsic<[llvm_double_ty], [],
   [IntrNoMerge, 
IntrHasSideEffects]>;
+  def int_ppc_mffsl : ClangBuiltin<"__builtin_ppc_mffsl">,
+  DefaultAttrsIntrinsic<[llvm_double_ty], [],
+[IntrNoMerge, IntrHasSideEffects]>;
+
   // Set FPSCR register, and return previous content
   def int_ppc_setflm : ClangBuiltin<"__builtin_setflm">,
DefaultAttrsIntrinsic<[llvm_double_ty], 
[llvm_double_ty],
Index: clang/test/CodeGen/PowerPC/builtins-ppc.c
===
--- clang/test/CodeGen/PowerPC/builtins-ppc.c
+++ clang/test/CodeGen/PowerPC/builtins-ppc.c
@@ -35,6 +35,11 @@
 
   // CHECK: call double @llvm.ppc.setflm(double %1)
   res = __builtin_setflm(res);
+
+#ifdef _ARCH_PWR9
+  // P9: call double @llvm.ppc.mffsl()
+  res = __builtin_ppc_mffsl();
+#endif
 }
 
 double test_builtin_unpack_ldbl(long double x) {
Index: clang/include/clang/Basic/BuiltinsPPC.def
===
--- clang/include/clang/Basic/BuiltinsPPC.def
+++ clang/include/clang/Basic/BuiltinsPPC.def
@@ -151,6 +151,7 @@
 TARGET_BUILTIN(__builtin_ppc_extract_sig, "ULLid", "", "power9-vector")
 BUILTIN(__builtin_ppc_mtfsb0, "vUIi", "")
 BUILTIN(__builtin_ppc_mtfsb1, "vUIi", "")
+TARGET_BUILTIN(__builtin_ppc_mffsl, "d", "", "isa-v30-instructions")
 BUILTIN(__builtin_ppc_mtfsf, "vUIiUi", "")
 BUILTIN(__builtin_ppc_mtfsfi, "vUIiUIi", "")
 TARGET_BUILTIN(__builtin_ppc_insert_exp, "ddULLi", "", "power9-vector")


Index: llvm/test/CodeGen/PowerPC/read-set-flm.ll
===
--- llvm/test/CodeGen/PowerPC/read-set-flm.ll
+++ llvm/test/CodeGen/PowerPC/read-set-flm.ll
@@ -148,8 +148,19 @@
   ret void
 }
 
+define double @mffsl() {
+; CHECK-LABEL: mffsl:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:mffsl 1
+; CHECK-NEXT:blr
+entry:
+  %x = call double @llvm.ppc.mffsl()
+  ret double %x
+}
+
 declare void @effect_func()
 declare void @readonly_func() #1
+declare double @llvm.ppc.mffsl()
 declare double @llvm.ppc.readflm()
 declare double @llvm.ppc.setflm(double)
 declare double @llvm.experimental.constrained.fadd.f64(double, double, metadata, metadata)
Index: llvm/lib/Target/PowerPC/PPCInstrInfo.td
===
--- llvm/lib/Target/PowerPC/PPCInstrInfo.td
+++ llvm/lib/Target/PowerPC/PPCInstrInfo.td
@@ -3180,6 +3180,7 @@
   (TCRETURNri CTRRC:$dst, imm:$imm)>;
 
 def : Pat<(int_ppc_readflm), (MFFS)>;
+def : Pat<(int_ppc_mffsl), (

[clang] ec483c2 - [clang][ASTMatcher] Add matcher for 'MacroQualifiedType'

2023-08-16 Thread via cfe-commits

Author: dingfei
Date: 2023-08-16T18:03:16+08:00
New Revision: ec483c29a95cbaef460e3c8523af91ee1cc43e55

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

LOG: [clang][ASTMatcher] Add matcher for 'MacroQualifiedType'

Add matcher for 'MacroQualifiedType'

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/docs/ReleaseNotes.rst
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/ASTMatchersInternal.cpp
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 4b87f157a9c2ce..a526751f0116f5 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -2648,6 +2648,18 @@ Node Matchers
 
 
 
+MatcherType>macroQualifiedTypeMatcherMacroQualifiedType>...
+Matches 
qualified types when the qualifier is applied via a macro.
+
+Given
+  #define CDECL __attribute__((cdecl))
+  typedef void (CDECL *X)();
+  typedef void (__attribute__((cdecl)) *Y)();
+macroQualifiedType()
+  matches the type of the typedef declaration of X but not Y.
+
+
+
 MatcherType>memberPointerTypeMatcherMemberPointerType>...
 Matches member 
pointer types.
 Given

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 56eef72c8a2835..2c4131ad7b4c89 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -252,6 +252,7 @@ AST Matchers
 
 - Add ``convertVectorExpr``.
 - Add ``dependentSizedExtVectorType``.
+- Add ``macroQualifiedType``.
 
 clang-format
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 620f0cb7872f1f..bdc9a5624ce3af 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7258,6 +7258,18 @@ AST_TYPELOC_TRAVERSE_MATCHER_DECL(
 ///   matches "typedef int X"
 extern const AstTypeMatcher typedefType;
 
+/// Matches qualified types when the qualifier is applied via a macro.
+///
+/// Given
+/// \code
+///   #define CDECL __attribute__((cdecl))
+///   typedef void (CDECL *X)();
+///   typedef void (__attribute__((cdecl)) *Y)();
+/// \endcode
+/// macroQualifiedType()
+///   matches the type of the typedef declaration of \c X but not \c Y.
+extern const AstTypeMatcher macroQualifiedType;
+
 /// Matches enum types.
 ///
 /// Given

diff  --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index 6a2c85ef2b5176..40688107215f28 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -1058,6 +1058,7 @@ const AstTypeMatcher functionType;
 const AstTypeMatcher functionProtoType;
 const AstTypeMatcher parenType;
 const AstTypeMatcher blockPointerType;
+const AstTypeMatcher macroQualifiedType;
 const AstTypeMatcher memberPointerType;
 const AstTypeMatcher pointerType;
 const AstTypeMatcher objcObjectPointerType;

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 0cd65d4c95cbcd..2e43dec331b75f 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -485,6 +485,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(lambdaCapture);
   REGISTER_MATCHER(lambdaExpr);
   REGISTER_MATCHER(linkageSpecDecl);
+  REGISTER_MATCHER(macroQualifiedType);
   REGISTER_MATCHER(materializeTemporaryExpr);
   REGISTER_MATCHER(member);
   REGISTER_MATCHER(memberExpr);

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
index bb7d8cc771a349..7a6d6ef0a95554 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1838,6 +1838,20 @@ TEST_P(ASTMatchersTest, TypedefType) {
 namesType(typedefType()));
 }
 
+TEST_P(ASTMatchersTest, MacroQualifiedType) {
+  EXPECT_TRUE(matches(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  typedefDecl(hasType(pointerType(pointee(macroQualifiedType()));
+  EXPECT_TRUE(notMatches(
+  R"(
+typedef void (__attribute__((cdecl)) *Y)();
+  )",
+  typedefDecl(has

[clang] 3b0eeb6 - [clang][ASTImporter] Add import of 'MacroQualifiedType'

2023-08-16 Thread via cfe-commits

Author: dingfei
Date: 2023-08-16T18:03:16+08:00
New Revision: 3b0eeb6cdbd7d8f662f12c4d90bdaee7a01a6354

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

LOG: [clang][ASTImporter] Add import of 'MacroQualifiedType'

Add import of 'MacroQualifiedType'.

Reviewed By: balazske

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

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 6da39ca2778bd1..cf8f23c305824d 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -419,6 +419,7 @@ namespace clang {
 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
+ExpectedType VisitMacroQualifiedType(const MacroQualifiedType *T);
 
 // Importing declarations
 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
@@ -1701,6 +1702,17 @@ ASTNodeImporter::VisitObjCObjectPointerType(const 
ObjCObjectPointerType *T) {
   return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
 }
 
+ExpectedType
+ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
+  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
+  if (!ToUnderlyingTypeOrErr)
+return ToUnderlyingTypeOrErr.takeError();
+
+  IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
+  return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
+   ToIdentifier);
+}
+
 //
 // Import Declarations
 //

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 9094ff4f25e7be..3aa9a458ef93ba 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -8638,6 +8638,24 @@ TEST_P(ImportInjectedClassNameType, ImportTypedefType) {
   EXPECT_TRUE(ToCtx.hasSameType(ToInjTypedef, ToInjParmVar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportMacroQualifiedType) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromTy =
+  FirstDeclMatcher().match(From, macroQualifiedType());
+  auto *ToTy =
+  FirstDeclMatcher().match(To, macroQualifiedType());
+
+  EXPECT_TRUE(isa(FromTy->getUnderlyingType()));
+  EXPECT_TRUE(isa(ToTy->getUnderlyingType()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplateName) {
   constexpr auto TestCode = R"(
   template 



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


[PATCH] D157777: [ASTMatcher] Add matcher for 'MacroQualifiedType'

2023-08-16 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGec483c29a95c: [clang][ASTMatcher] Add matcher for 
'MacroQualifiedType' (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D15

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1838,6 +1838,20 @@
 namesType(typedefType()));
 }
 
+TEST_P(ASTMatchersTest, MacroQualifiedType) {
+  EXPECT_TRUE(matches(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  typedefDecl(hasType(pointerType(pointee(macroQualifiedType()));
+  EXPECT_TRUE(notMatches(
+  R"(
+typedef void (__attribute__((cdecl)) *Y)();
+  )",
+  typedefDecl(hasType(pointerType(pointee(macroQualifiedType()));
+}
+
 TEST_P(ASTMatchersTest, TemplateSpecializationType) {
   if (!GetParam().isCXX()) {
 return;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -485,6 +485,7 @@
   REGISTER_MATCHER(lambdaCapture);
   REGISTER_MATCHER(lambdaExpr);
   REGISTER_MATCHER(linkageSpecDecl);
+  REGISTER_MATCHER(macroQualifiedType);
   REGISTER_MATCHER(materializeTemporaryExpr);
   REGISTER_MATCHER(member);
   REGISTER_MATCHER(memberExpr);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -1058,6 +1058,7 @@
 const AstTypeMatcher functionProtoType;
 const AstTypeMatcher parenType;
 const AstTypeMatcher blockPointerType;
+const AstTypeMatcher macroQualifiedType;
 const AstTypeMatcher memberPointerType;
 const AstTypeMatcher pointerType;
 const AstTypeMatcher objcObjectPointerType;
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7258,6 +7258,18 @@
 ///   matches "typedef int X"
 extern const AstTypeMatcher typedefType;
 
+/// Matches qualified types when the qualifier is applied via a macro.
+///
+/// Given
+/// \code
+///   #define CDECL __attribute__((cdecl))
+///   typedef void (CDECL *X)();
+///   typedef void (__attribute__((cdecl)) *Y)();
+/// \endcode
+/// macroQualifiedType()
+///   matches the type of the typedef declaration of \c X but not \c Y.
+extern const AstTypeMatcher macroQualifiedType;
+
 /// Matches enum types.
 ///
 /// Given
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -252,6 +252,7 @@
 
 - Add ``convertVectorExpr``.
 - Add ``dependentSizedExtVectorType``.
+- Add ``macroQualifiedType``.
 
 clang-format
 
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -2648,6 +2648,18 @@
 
 
 
+MatcherType>macroQualifiedTypeMatcherMacroQualifiedType>...
+Matches qualified types when the qualifier is applied via a macro.
+
+Given
+  #define CDECL __attribute__((cdecl))
+  typedef void (CDECL *X)();
+  typedef void (__attribute__((cdecl)) *Y)();
+macroQualifiedType()
+  matches the type of the typedef declaration of X but not Y.
+
+
+
 MatcherType>memberPointerTypeMatcherMemberPointerType>...
 Matches member pointer types.
 Given
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157780: [ASTImporter] Add import of MacroQualifiedType

2023-08-16 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b0eeb6cdbd7: [clang][ASTImporter] Add import of 
'MacroQualifiedType' (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157780

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8638,6 +8638,24 @@
   EXPECT_TRUE(ToCtx.hasSameType(ToInjTypedef, ToInjParmVar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportMacroQualifiedType) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromTy =
+  FirstDeclMatcher().match(From, macroQualifiedType());
+  auto *ToTy =
+  FirstDeclMatcher().match(To, macroQualifiedType());
+
+  EXPECT_TRUE(isa(FromTy->getUnderlyingType()));
+  EXPECT_TRUE(isa(ToTy->getUnderlyingType()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplateName) {
   constexpr auto TestCode = R"(
   template 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -419,6 +419,7 @@
 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
+ExpectedType VisitMacroQualifiedType(const MacroQualifiedType *T);
 
 // Importing declarations
 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
@@ -1701,6 +1702,17 @@
   return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
 }
 
+ExpectedType
+ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
+  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
+  if (!ToUnderlyingTypeOrErr)
+return ToUnderlyingTypeOrErr.takeError();
+
+  IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
+  return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
+   ToIdentifier);
+}
+
 //
 // Import Declarations
 //


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8638,6 +8638,24 @@
   EXPECT_TRUE(ToCtx.hasSameType(ToInjTypedef, ToInjParmVar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportMacroQualifiedType) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromTy =
+  FirstDeclMatcher().match(From, macroQualifiedType());
+  auto *ToTy =
+  FirstDeclMatcher().match(To, macroQualifiedType());
+
+  EXPECT_TRUE(isa(FromTy->getUnderlyingType()));
+  EXPECT_TRUE(isa(ToTy->getUnderlyingType()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplateName) {
   constexpr auto TestCode = R"(
   template 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -419,6 +419,7 @@
 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
+ExpectedType VisitMacroQualifiedType(const MacroQualifiedType *T);
 
 // Importing declarations
 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
@@ -1701,6 +1702,17 @@
   return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
 }
 
+ExpectedType
+ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
+  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
+  if (!ToUnderlyingTypeOrErr)
+return ToUnderlyingTypeOrErr.takeError();
+
+  IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
+  return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
+   ToIdentifier);
+}
+
 //
 // Import Declarations
 //---

[clang] eabc7ad - [clang][ASTImporter] Remove extra FunctionTemplateDecl introduced by templated friend

2023-08-16 Thread via cfe-commits

Author: dingfei
Date: 2023-08-16T18:03:16+08:00
New Revision: eabc7add1f96e0b580cf4acf4f42ed3eb99df47b

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

LOG: [clang][ASTImporter] Remove extra FunctionTemplateDecl introduced by 
templated friend

An extranous FunctionTemplateDecl is introduced in the following testcase:

  template  struct A {
template  friend void f();
  };

"To" Context:

  ClassTemplateDecl 0x55dae7116618  col:30 A
  |-TemplateTypeParmDecl 0x55dae7116490  col:20 typename depth 
0 index 0 T
  `-CXXRecordDecl 0x55dae7116550  col:30 struct A definition
|-DefinitionData empty aggregate standard_layout trivially_copyable pod 
trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
| |-DefaultConstructor exists trivial constexpr needs_implicit 
defaulted_is_constexpr
| |-CopyConstructor simple trivial has_const_param needs_implicit 
implicit_has_const_param
| |-MoveConstructor exists simple trivial needs_implicit
| |-CopyAssignment simple trivial has_const_param needs_implicit 
implicit_has_const_param
| |-MoveAssignment exists simple trivial needs_implicit
| `-Destructor simple irrelevant trivial needs_implicit
|-FunctionTemplateDecl 0x55dae7116a38 parent 0x55dae6fa2b68  col:69 f// extranous node
| |-TemplateTypeParmDecl 0x55dae7116860  col:54 typename 
depth 1 index 0 U
| `-FunctionDecl 0x55dae7116968 parent 0x55dae6fa2b68  
col:69 f 'void ()'
|-FriendDecl 0x55dae7116aa0  col:69
| `-FunctionTemplateDecl 0x55dae7116a38 parent 0x55dae6fa2b68  col:69 f
|   |-TemplateTypeParmDecl 0x55dae7116860  col:54 typename 
depth 1 index 0 U
|   `-FunctionDecl 0x55dae7116968 parent 0x55dae6fa2b68  
col:69 f 'void ()'
`-CXXRecordDecl 0x55dae7116ae0  col:30 implicit struct A

Reviewed By: balazske

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

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index cf8f23c305824d..736aac8a646b7a 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -6459,7 +6459,7 @@ 
ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
 
   ToFunc->setAccess(D->getAccess());
   ToFunc->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDeclInternal(ToFunc);
+  addDeclToContexts(D, ToFunc);
 
   ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
   if (LT && !OldParamDC.empty()) {

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 3aa9a458ef93ba..06b64b9f8efb47 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5634,6 +5634,43 @@ TEST_P(ImportFriendFunctionTemplates, 
LookupShouldFindPreviousFriend) {
   EXPECT_EQ(Imported->getPreviousDecl(), Friend);
 }
 
+TEST_P(ImportFriendFunctionTemplates, ImportFriendFunctionInsideClassTemplate) 
{
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  template  struct X {
+template  friend void f();
+  };
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromFriend = FirstDeclMatcher().match(From, friendDecl());
+  auto *ToFriend = FirstDeclMatcher().match(To, friendDecl());
+
+  EXPECT_TRUE(FromFriend ==
+  LastDeclMatcher().match(From, friendDecl()));
+  EXPECT_TRUE(ToFriend ==
+  LastDeclMatcher().match(To, friendDecl()));
+
+  auto *FromDecl = FromFriend->getFriendDecl();
+  auto *FromDC = FromFriend->getDeclContext();
+  auto *FromLexicalDC = FromFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(FromDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromDC->containsDecl(FromDecl));
+  EXPECT_TRUE(FromLexicalDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromLexicalDC->containsDecl(FromDecl));
+
+  auto *ToDecl = ToFriend->getFriendDecl();
+  auto *ToDC = ToFriend->getDeclContext();
+  auto *ToLexicalDC = ToFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(ToDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToDC->containsDecl(ToDecl));
+  EXPECT_TRUE(ToLexicalDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToLexicalDC->containsDecl(ToDecl));
+}
+
 struct ASTImporterWithFakeErrors : ASTImporter {
   using ASTImporter::ASTImporter;
   bool returnWithErrorInTest() override { return true; }



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


[PATCH] D157691: [ASTImporter] Remove extranous FunctionTemplateDecl introduced by templated friend

2023-08-16 Thread 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 rGeabc7add1f96: [clang][ASTImporter] Remove extra 
FunctionTemplateDecl introduced by templated… (authored by dingfei 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157691

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5634,6 +5634,43 @@
   EXPECT_EQ(Imported->getPreviousDecl(), Friend);
 }
 
+TEST_P(ImportFriendFunctionTemplates, ImportFriendFunctionInsideClassTemplate) 
{
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  template  struct X {
+template  friend void f();
+  };
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromFriend = FirstDeclMatcher().match(From, friendDecl());
+  auto *ToFriend = FirstDeclMatcher().match(To, friendDecl());
+
+  EXPECT_TRUE(FromFriend ==
+  LastDeclMatcher().match(From, friendDecl()));
+  EXPECT_TRUE(ToFriend ==
+  LastDeclMatcher().match(To, friendDecl()));
+
+  auto *FromDecl = FromFriend->getFriendDecl();
+  auto *FromDC = FromFriend->getDeclContext();
+  auto *FromLexicalDC = FromFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(FromDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromDC->containsDecl(FromDecl));
+  EXPECT_TRUE(FromLexicalDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromLexicalDC->containsDecl(FromDecl));
+
+  auto *ToDecl = ToFriend->getFriendDecl();
+  auto *ToDC = ToFriend->getDeclContext();
+  auto *ToLexicalDC = ToFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(ToDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToDC->containsDecl(ToDecl));
+  EXPECT_TRUE(ToLexicalDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToLexicalDC->containsDecl(ToDecl));
+}
+
 struct ASTImporterWithFakeErrors : ASTImporter {
   using ASTImporter::ASTImporter;
   bool returnWithErrorInTest() override { return true; }
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -6459,7 +6459,7 @@
 
   ToFunc->setAccess(D->getAccess());
   ToFunc->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDeclInternal(ToFunc);
+  addDeclToContexts(D, ToFunc);
 
   ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
   if (LT && !OldParamDC.empty()) {


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5634,6 +5634,43 @@
   EXPECT_EQ(Imported->getPreviousDecl(), Friend);
 }
 
+TEST_P(ImportFriendFunctionTemplates, ImportFriendFunctionInsideClassTemplate) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+  template  struct X {
+template  friend void f();
+  };
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromFriend = FirstDeclMatcher().match(From, friendDecl());
+  auto *ToFriend = FirstDeclMatcher().match(To, friendDecl());
+
+  EXPECT_TRUE(FromFriend ==
+  LastDeclMatcher().match(From, friendDecl()));
+  EXPECT_TRUE(ToFriend ==
+  LastDeclMatcher().match(To, friendDecl()));
+
+  auto *FromDecl = FromFriend->getFriendDecl();
+  auto *FromDC = FromFriend->getDeclContext();
+  auto *FromLexicalDC = FromFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(FromDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromDC->containsDecl(FromDecl));
+  EXPECT_TRUE(FromLexicalDC->containsDecl(FromFriend));
+  EXPECT_FALSE(FromLexicalDC->containsDecl(FromDecl));
+
+  auto *ToDecl = ToFriend->getFriendDecl();
+  auto *ToDC = ToFriend->getDeclContext();
+  auto *ToLexicalDC = ToFriend->getLexicalDeclContext();
+
+  EXPECT_TRUE(ToDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToDC->containsDecl(ToDecl));
+  EXPECT_TRUE(ToLexicalDC->containsDecl(ToFriend));
+  EXPECT_FALSE(ToLexicalDC->containsDecl(ToDecl));
+}
+
 struct ASTImporterWithFakeErrors : ASTImporter {
   using ASTImporter::ASTImporter;
   bool returnWithErrorInTest() override { return true; }
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -6459,7 +6459,7 @@
 
   ToFunc->setAccess(D->getAccess());
   ToFunc->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDeclInternal(ToFunc);
+  addDeclToContexts(D, ToFunc);
 
   ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
   if (LT && !OldParamDC.empty()) {
___
cfe-commits mailing list
c

[PATCH] D158066: [PowerPC] Fix use of FPSCR builtins in smmintrin.h

2023-08-16 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: nemanjai, shchenz, stefanp, PowerPC.
Herald added a subscriber: kbarton.
Herald added a project: All.
qiucf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`smmintrin.h` uses `__builtin_mffs`, `__builtin_mffsl`, `__builtin_mtfsf` and 
`__builtin_set_fpscr_rn`. This patch replaces the uses with `ppc` prefix and 
implement the missing ones.

This fixes issue 64664.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158066

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/ppc_wrappers/smmintrin.h
  clang/test/CodeGen/PowerPC/builtins-ppc.c
  clang/test/CodeGen/PowerPC/ppc-smmintrin.c

Index: clang/test/CodeGen/PowerPC/ppc-smmintrin.c
===
--- clang/test/CodeGen/PowerPC/ppc-smmintrin.c
+++ clang/test/CodeGen/PowerPC/ppc-smmintrin.c
@@ -239,44 +239,48 @@
 // CHECK-LABEL: @test_round
 
 // CHECK-LABEL: define available_externally <4 x float> @_mm_round_ps(<4 x float> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
-// CHECK: call signext i32 @__builtin_mffs()
-// CHECK: call signext i32 @__builtin_mtfsf(i32 noundef signext 3, double noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.readflm()
+// CHECK: call void @llvm.ppc.mtfsf(i32 3, double %{{[0-9a-zA-Z_.]+}})
 // CHECK: %{{[0-9a-zA-Z_.]+}} = call <4 x float> asm "", "=^wa,0"
-// CHECK: call signext i32 @__builtin_mffsl()
-// CHECK: call signext i32 @__builtin_set_fpscr_rn(i32 noundef signext 0)
+// CHECK: call double @llvm.ppc.readflm()
+// P10: call double @llvm.ppc.mffsl()
+// CHECK: call double @llvm.ppc.setrnd(i32 0)
 // CHECK: %{{[0-9a-zA-Z_.]+}} = call <4 x float> asm "", "=^wa,0"
 // CHECK: call <4 x float> @vec_rint(float vector[4])
 // CHECK: call void asm sideeffect "", "^wa"
-// CHECK: call signext i32 @__builtin_set_fpscr_rn(i64 noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.setrnd(i32 %{{[0-9a-zA-Z_.]+}})
 // CHECK: call <4 x float> @vec_floor(float vector[4])
 // CHECK: call <4 x float> @vec_ceil(float vector[4])
 // CHECK: call <4 x float> @vec_trunc(float vector[4])
 // CHECK: call <4 x float> @vec_rint(float vector[4])
 // CHECK: call void asm sideeffect "", "^wa"
-// CHECK: call signext i32 @__builtin_mffsl()
-// CHECK: call signext i32 @__builtin_mtfsf(i32 noundef signext 3, double noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.readflm()
+// P10: call double @llvm.ppc.mffsl()
+// CHECK: call void @llvm.ppc.mtfsf(i32 3, double %{{[0-9a-zA-Z_.]+}})
 
 // CHECK-LABEL: define available_externally <4 x float> @_mm_round_ss(<4 x float> noundef %{{[0-9a-zA-Z_.]+}}, <4 x float> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
 // CHECK: call <4 x float> @_mm_round_ps(<4 x float> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
 // CHECK: extractelement <4 x float> %{{[0-9a-zA-Z_.]+}}, i32 0
 
 // CHECK-LABEL: define available_externally <2 x double> @_mm_round_pd(<2 x double> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
-// CHECK: call signext i32 @__builtin_mffs()
-// CHECK: call signext i32 @__builtin_mtfsf(i32 noundef signext 3, double noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.readflm()
+// CHECK: call void @llvm.ppc.mtfsf(i32 3, double %{{[0-9a-zA-Z_.]+}})
 // CHECK: %{{[0-9a-zA-Z_.]+}} = call <2 x double> asm "", "=^wa,0"
-// CHECK: call signext i32 @__builtin_mffsl()
-// CHECK: call signext i32 @__builtin_set_fpscr_rn(i32 noundef signext 0)
+// CHECK: call double @llvm.ppc.readflm()
+// P10: call double @llvm.ppc.mffsl()
+// CHECK: call double @llvm.ppc.setrnd(i32 0)
 // CHECK: %{{[0-9a-zA-Z_.]+}} = call <2 x double> asm "", "=^wa,0"
 // CHECK: call <2 x double> @vec_rint(double vector[2])
 // CHECK: call void asm sideeffect "", "^wa"
-// CHECK: call signext i32 @__builtin_set_fpscr_rn(i64 noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.setrnd(i32 %{{[0-9a-zA-Z_.]+}})
 // CHECK: call <2 x double> @vec_floor(double vector[2])
 // CHECK: call <2 x double> @vec_ceil(double vector[2])
 // CHECK: call <2 x double> @vec_trunc(double vector[2])
 // CHECK: call <2 x double> @vec_rint(double vector[2])
 // CHECK: call void asm sideeffect "", "^wa"
-// CHECK: call signext i32 @__builtin_mffsl()
-// CHECK: call signext i32 @__builtin_mtfsf(i32 noundef signext 3, double noundef %{{[0-9a-zA-Z_.]+}})
+// CHECK: call double @llvm.ppc.readflm()
+// P10: call double @llvm.ppc.mffsl()
+// CHECK: call void @llvm.ppc.mtfsf(i32 3, double %{{[0-9a-zA-Z_.]+}})
 
 // CHECK-LABEL: define available_externally <2 x double> @_mm_round_sd(<2 x double> noundef %{{[0-9a-zA-Z_.]+}}, <2 x double> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
 // CHECK: call <2 x double> @_mm_round_pd(<2 x double> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{

[clang] 2459ed6 - [PowerPC] Add nmmintrin.h to copy list

2023-08-16 Thread Qiu Chaofan via cfe-commits

Author: Qiu Chaofan
Date: 2023-08-16T18:15:08+08:00
New Revision: 2459ed67805c1c6bd9d7db2f1e481b318960d7d8

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

LOG: [PowerPC] Add nmmintrin.h to copy list

nmmintrin.h was missing in the list of copied ppc_wrappers. No tests
needed since it only includes smmintrin.h.

Added: 


Modified: 
clang/lib/Headers/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Headers/CMakeLists.txt 
b/clang/lib/Headers/CMakeLists.txt
index f2b0c5cddcbbf8..05bb740f306727 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -285,6 +285,7 @@ set(ppc_wrapper_files
   ppc_wrappers/pmmintrin.h
   ppc_wrappers/tmmintrin.h
   ppc_wrappers/smmintrin.h
+  ppc_wrappers/nmmintrin.h
   ppc_wrappers/bmiintrin.h
   ppc_wrappers/bmi2intrin.h
   ppc_wrappers/immintrin.h



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


[PATCH] D119407: [PowerPC] [Clang] Add SSE4 and BMI compatible intrinsics implementation for PowerPC

2023-08-16 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf marked 2 inline comments as done.
qiucf added a comment.

Thanks, fixed by rG2459ed67805c 
. 
`nmmintrin.h` just includes `smmintrin.h` so it's not critical.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119407

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


[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, shafik, cor3ntin.
Herald added subscribers: ChuanqiXu, arphaman.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158069

Files:
  clang/lib/AST/Interp/Context.h
  clang/lib/AST/Interp/Pointer.h
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/Interp/CMakeLists.txt
  clang/unittests/AST/Interp/Descriptor.cpp

Index: clang/unittests/AST/Interp/Descriptor.cpp
===
--- /dev/null
+++ clang/unittests/AST/Interp/Descriptor.cpp
@@ -0,0 +1,368 @@
+#include "../../../lib/AST/Interp/Descriptor.h"
+#include "../../../lib/AST/Interp/Context.h"
+#include "../../../lib/AST/Interp/Program.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::interp;
+using namespace clang::ast_matchers;
+
+/// Inspect generated Descriptors as well as the pointers we create.
+///
+TEST(Descriptor, Primitives) {
+  constexpr char Code[] =
+  "struct A { bool a; bool b; };\n"
+  "struct S {\n"
+  "  float f;\n"
+  "  char s[4] = \"foo\";\n"
+  "  A a[3];\n"
+  "  short l[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};\n"
+  "};\n"
+  "constexpr S d{};";
+
+  auto AST = tooling::buildASTFromCodeWithArgs(
+  Code, {"-fexperimental-new-constant-interpreter"});
+
+  const VarDecl *D = selectFirst(
+  "d", match(varDecl().bind("d"), AST->getASTContext()));
+  ASSERT_NE(D, nullptr);
+
+  const auto &Ctx = AST->getASTContext().getInterpContext();
+  Program &Prog = Ctx.getProgram();
+  // Global is registered.
+  ASSERT_TRUE(Prog.getGlobal(D));
+
+  // Get a Pointer to the global.
+  const Pointer &GlobalPtr = Prog.getPtrGlobal(*Prog.getGlobal(D));
+
+  // Test Descriptor of the struct S.
+  const Descriptor *GlobalDesc = GlobalPtr.getFieldDesc();
+  ASSERT_TRUE(GlobalDesc == GlobalPtr.getDeclDesc());
+
+  ASSERT_TRUE(GlobalDesc->asDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asExpr());
+  ASSERT_TRUE(GlobalDesc->asValueDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asFieldDecl());
+  ASSERT_FALSE(GlobalDesc->asRecordDecl());
+
+  // Still true because this is a global variable.
+  ASSERT_TRUE(GlobalDesc->getMetadataSize() == 0);
+  ASSERT_FALSE(GlobalDesc->isPrimitiveArray());
+  ASSERT_FALSE(GlobalDesc->isCompositeArray());
+  ASSERT_FALSE(GlobalDesc->isZeroSizeArray());
+  ASSERT_FALSE(GlobalDesc->isUnknownSizeArray());
+  ASSERT_FALSE(GlobalDesc->isPrimitive());
+  ASSERT_FALSE(GlobalDesc->isArray());
+  ASSERT_TRUE(GlobalDesc->isRecord());
+
+  // Test the Record for the struct S.
+  const Record *SRecord = GlobalDesc->ElemRecord;
+  ASSERT_TRUE(SRecord);
+  ASSERT_TRUE(SRecord->getNumFields() == 4);
+  ASSERT_TRUE(SRecord->getNumBases() == 0);
+  ASSERT_FALSE(SRecord->getDestructor());
+
+  // First field.
+  const Record::Field *F1 = SRecord->getField(0u);
+  ASSERT_TRUE(F1);
+  ASSERT_FALSE(F1->isBitField());
+  ASSERT_TRUE(F1->Desc->isPrimitive());
+
+  // Second field.
+  const Record::Field *F2 = SRecord->getField(1u);
+  ASSERT_TRUE(F2);
+  ASSERT_FALSE(F2->isBitField());
+  ASSERT_TRUE(F2->Desc->isArray());
+  ASSERT_FALSE(F2->Desc->isCompositeArray());
+  ASSERT_TRUE(F2->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F2->Desc->isPrimitive());
+  ASSERT_FALSE(F2->Desc->ElemDesc);
+  ASSERT_EQ(F2->Desc->getNumElems(), 4u);
+  ASSERT_TRUE(F2->Desc->getElemSize() > 0);
+
+  // Third field.
+  const Record::Field *F3 = SRecord->getField(2u);
+  ASSERT_TRUE(F3);
+  ASSERT_FALSE(F3->isBitField());
+  ASSERT_TRUE(F3->Desc->isArray());
+  ASSERT_TRUE(F3->Desc->isCompositeArray());
+  ASSERT_FALSE(F3->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F3->Desc->isPrimitive());
+  ASSERT_TRUE(F3->Desc->ElemDesc);
+  ASSERT_EQ(F3->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F3->Desc->getElemSize() > 0);
+
+  // Fourth field.
+  // Multidimensional arrays are treated as composite arrays, even
+  // if the value type is primitive.
+  const Record::Field *F4 = SRecord->getField(3u);
+  ASSERT_TRUE(F4);
+  ASSERT_FALSE(F4->isBitField());
+  ASSERT_TRUE(F4->Desc->isArray());
+  ASSERT_TRUE(F4->Desc->isCompositeArray());
+  ASSERT_FALSE(F4->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F4->Desc->isPrimitive());
+  ASSERT_TRUE(F4->Desc->ElemDesc);
+  ASSERT_EQ(F4->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F4->Desc->getElemSize() > 0);
+  ASSERT_TRUE(F4->Desc->ElemDesc->isPrimitiveArray());
+
+  // Check pointer stuff.
+  // Global variables have no inline descriptor (yet).
+  ASSERT_TRUE(GlobalPtr.isRoot());
+  ASSERT_TRUE(GlobalPtr.isLive());
+  ASSERT_FALSE(GlobalPtr.isZero());
+  ASSERT_FALSE(GlobalPtr.isField());
+  AS

[PATCH] D156726: Make globals with mutable members non-constant, even in custom sections

2023-08-16 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 added a comment.

Hi @dblaikie,

After this revision landed yesterday one BPF kernel selftest (written in C) 
stopped building. I narrowed the issue to the following example:

  #define SEC(n) __attribute__((section(n)))
  
  const int with_init SEC("foo") = 1;
  const int no_init SEC("foo");

It fails with the following error:

  $ clang -c t.c -o -
  t.c:4:11: error: 'no_init' causes a section type conflict with 'with_init'
  4 | const int no_init SEC("foo");
|   ^
  t.c:3:11: note: declared here
  3 | const int with_init SEC("foo") = 1;
|   ^
  1 error generated.

The error occurs because clang infers `PSF_Read` attribute for section "foo" 
when `with_init` is processed and `PSF_Read | PSF_Write` attributes for section 
"foo" when `no_init` is processed, thus reporting `diag::err_section_conflict`. 
The behavior changed because of the following lines introduced in this revision:

  void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
...
if (GlobalStorage && var->isThisDeclarationADefinition() &&
!inTemplateInstantiation()) {
  ...
  if (var->hasInit() && HasConstInit && !(Reason =
  var->getType().isNonConstantStorage(Context, true, false))) {
Stack = &ConstSegStack;
  } else {
SectionFlags |= ASTContext::PSF_Write;
Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
  }
  ...
}
...
  }

Because of the `var->hasInit()` check any global w/o initializer gets a 
`PSF_Write` flag, which was not the case before this revision. So, now if one 
wants to have some `const` globals in the same section, these globals need to 
have an initializer.

I checked C language standard (N3088, section "6.7.3 Type qualifiers") and it 
does not offer much to tell if my example is correct or not, so I guess it is 
implementation dependent. GCC accepts my example w/o errors or warnings.

So, a question: might it be the case that `var->hasInit()` check is too 
restrictive?
(I do understand that w/o some custom linker behavior `const` globals w/o 
initializer don't make much sense).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156726

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


[PATCH] D156726: Make globals with mutable members non-constant, even in custom sections

2023-08-16 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 added a comment.

As an additional data point, the same example but w/o section specification 
compiles fine:

  const int with_init = 1;
  const int no_init;

And puts both globals to the same section:

  $ clang -c t.c -o - | llvm-readelf --section-headers -s -
  Section Headers:
[Nr] Name  TypeAddress  OffSize   ES 
Flg Lk Inf Al
...
[ 3] .rodata   PROGBITS 40 08 00   
A  0   0  4
...
  
  Symbol table '.symtab' contains 4 entries:
 Num:Value  Size TypeBind   Vis   Ndx Name
   ...
   2:  4 OBJECT  GLOBAL DEFAULT 3 with_init
   3: 0004 4 OBJECT  GLOBAL DEFAULT 3 no_init

(`Ndx` stands for section `Nr`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156726

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


[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 550696.

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

https://reviews.llvm.org/D158069

Files:
  clang/lib/AST/Interp/Context.h
  clang/lib/AST/Interp/Pointer.h
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/Interp/CMakeLists.txt
  clang/unittests/AST/Interp/Descriptor.cpp

Index: clang/unittests/AST/Interp/Descriptor.cpp
===
--- /dev/null
+++ clang/unittests/AST/Interp/Descriptor.cpp
@@ -0,0 +1,385 @@
+#include "../../../lib/AST/Interp/Descriptor.h"
+#include "../../../lib/AST/Interp/Context.h"
+#include "../../../lib/AST/Interp/Program.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::interp;
+using namespace clang::ast_matchers;
+
+/// Inspect generated Descriptors as well as the pointers we create.
+///
+TEST(Descriptor, Primitives) {
+  constexpr char Code[] =
+  "struct A { bool a; bool b; };\n"
+  "struct S {\n"
+  "  float f;\n"
+  "  char s[4] = \"foo\";\n"
+  "  A a[3];\n"
+  "  short l[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};\n"
+  "};\n"
+  "constexpr S d{};";
+
+  auto AST = tooling::buildASTFromCodeWithArgs(
+  Code, {"-fexperimental-new-constant-interpreter"});
+
+  const VarDecl *D = selectFirst(
+  "d", match(varDecl().bind("d"), AST->getASTContext()));
+  ASSERT_NE(D, nullptr);
+
+  const auto &Ctx = AST->getASTContext().getInterpContext();
+  Program &Prog = Ctx.getProgram();
+  // Global is registered.
+  ASSERT_TRUE(Prog.getGlobal(D));
+
+  // Get a Pointer to the global.
+  const Pointer &GlobalPtr = Prog.getPtrGlobal(*Prog.getGlobal(D));
+
+  // Test Descriptor of the struct S.
+  const Descriptor *GlobalDesc = GlobalPtr.getFieldDesc();
+  ASSERT_TRUE(GlobalDesc == GlobalPtr.getDeclDesc());
+
+  ASSERT_TRUE(GlobalDesc->asDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asExpr());
+  ASSERT_TRUE(GlobalDesc->asValueDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asFieldDecl());
+  ASSERT_FALSE(GlobalDesc->asRecordDecl());
+
+  // Still true because this is a global variable.
+  ASSERT_TRUE(GlobalDesc->getMetadataSize() == 0);
+  ASSERT_FALSE(GlobalDesc->isPrimitiveArray());
+  ASSERT_FALSE(GlobalDesc->isCompositeArray());
+  ASSERT_FALSE(GlobalDesc->isZeroSizeArray());
+  ASSERT_FALSE(GlobalDesc->isUnknownSizeArray());
+  ASSERT_FALSE(GlobalDesc->isPrimitive());
+  ASSERT_FALSE(GlobalDesc->isArray());
+  ASSERT_TRUE(GlobalDesc->isRecord());
+
+  // Test the Record for the struct S.
+  const Record *SRecord = GlobalDesc->ElemRecord;
+  ASSERT_TRUE(SRecord);
+  ASSERT_TRUE(SRecord->getNumFields() == 4);
+  ASSERT_TRUE(SRecord->getNumBases() == 0);
+  ASSERT_FALSE(SRecord->getDestructor());
+
+  // First field.
+  const Record::Field *F1 = SRecord->getField(0u);
+  ASSERT_TRUE(F1);
+  ASSERT_FALSE(F1->isBitField());
+  ASSERT_TRUE(F1->Desc->isPrimitive());
+
+  // Second field.
+  const Record::Field *F2 = SRecord->getField(1u);
+  ASSERT_TRUE(F2);
+  ASSERT_FALSE(F2->isBitField());
+  ASSERT_TRUE(F2->Desc->isArray());
+  ASSERT_FALSE(F2->Desc->isCompositeArray());
+  ASSERT_TRUE(F2->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F2->Desc->isPrimitive());
+  ASSERT_FALSE(F2->Desc->ElemDesc);
+  ASSERT_EQ(F2->Desc->getNumElems(), 4u);
+  ASSERT_TRUE(F2->Desc->getElemSize() > 0);
+
+  // Third field.
+  const Record::Field *F3 = SRecord->getField(2u);
+  ASSERT_TRUE(F3);
+  ASSERT_FALSE(F3->isBitField());
+  ASSERT_TRUE(F3->Desc->isArray());
+  ASSERT_TRUE(F3->Desc->isCompositeArray());
+  ASSERT_FALSE(F3->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F3->Desc->isPrimitive());
+  ASSERT_TRUE(F3->Desc->ElemDesc);
+  ASSERT_EQ(F3->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F3->Desc->getElemSize() > 0);
+
+  // Fourth field.
+  // Multidimensional arrays are treated as composite arrays, even
+  // if the value type is primitive.
+  const Record::Field *F4 = SRecord->getField(3u);
+  ASSERT_TRUE(F4);
+  ASSERT_FALSE(F4->isBitField());
+  ASSERT_TRUE(F4->Desc->isArray());
+  ASSERT_TRUE(F4->Desc->isCompositeArray());
+  ASSERT_FALSE(F4->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F4->Desc->isPrimitive());
+  ASSERT_TRUE(F4->Desc->ElemDesc);
+  ASSERT_EQ(F4->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F4->Desc->getElemSize() > 0);
+  ASSERT_TRUE(F4->Desc->ElemDesc->isPrimitiveArray());
+
+  // Check pointer stuff.
+  // Global variables have no inline descriptor (yet).
+  ASSERT_TRUE(GlobalPtr.isRoot());
+  ASSERT_TRUE(GlobalPtr.isLive());
+  ASSERT_FALSE(GlobalPtr.isZero());
+  ASSERT_FALSE(GlobalPtr.isField());
+  ASSERT_TRUE(GlobalPtr.getFieldDesc() == GlobalPtr.getDeclDesc());
+  ASSERT_TRUE(GlobalPtr.getOffset() == 0);
+  ASSERT_FALSE(GlobalPtr.inArray());
+  ASSERT_FALSE(GlobalPtr.isArrayElement());
+  ASSERT_FALSE(GlobalPtr.

[PATCH] D153689: [clang][Interp] Handle CXXConstructExprs

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder abandoned this revision.
tbaeder added a comment.

Superseeded by https://reviews.llvm.org/D156027.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153689

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


[PATCH] D155858: Add a concept AST node.

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(There are still outstanding comments e.g. in ASTImport)

I think it would be useful to add to the patch description:

- the current deficiencies of ConceptReference that make it not a well-behaved 
AST node now
- which of these are addressed in this patch (RecursiveASTVisitor, use in all 
relevant places, avoiding multiple inheritance)
- which of these will be addressed in future patches (DynTypedNode, maybe 
text-dumper?)




Comment at: clang/include/clang/AST/ASTConcept.h:112
 
 /// \brief Common data class for constructs that reference concepts with
 /// template arguments.

Doc comment is out of date. Suggestion:

```
/// A reference to a concept and its template args, as it appears in the code.
///
/// Examples:
///   template  requires is_even int half = X/2;
/// ~~ (in ConceptSpecializationExpr)
///
///   std::input_iterator auto I = Container.begin();
///   ~~~ (in AutoTypeLoc)
///
///   template  T> void dump();
/// ~~~ (in TemplateTypeParmDecl)
```



Comment at: clang/include/clang/AST/ASTConcept.h:140
 public:
   ConceptReference(NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl,

this constructor should now be private, like other AST nodes



Comment at: clang/include/clang/AST/ASTConcept.h:148
 
   ConceptReference()
   : FoundDecl(nullptr), NamedConcept(nullptr), ArgsAsWritten(nullptr) {}

following the pattern for other AST nodes, this constructor should be private 
or gone. If deserialization needs to create an empty ConceptReference, provide 
a CreateEmpty() factory



Comment at: clang/include/clang/AST/ASTConcept.h:193
 
-class TypeConstraint : public ConceptReference {
+class TypeConstraint {
   /// \brief The immediately-declared constraint expression introduced by this

We're not really changing this class, but I think it could use a doc comment as 
its relationship to ConceptReference, TemplateTypeParmType, and AutoTypeLoc 
wasn't all that clear. Suggestion:

```
/// Models the abbreviated syntax to constrain a template type parameter:
///   template  T> void print(T object);
/// ~~
/// Semantically, this adds an "immediately-declared constraint" with extra arg:
///requires convertible_to
///
/// In the C++ grammar, a type-constraint is also used for auto types:
///convertible_to auto X = ...;
/// We do *not* model these as TypeConstraints, but AutoType(Loc) directly.
```



Comment at: clang/include/clang/AST/ExprConcepts.h:90
+  // NOTE(massberg): For the first minimal prototype we keep the
+  // following functions to prevent. Later these functions should
+  // be accessed getConceptReference().

incomplete comment: "to prevent" what?

Also FWIW I don't think *all* uses should be migrated, e.g. `getNamedConcept()` 
is fundamental enough to be exposed here even if it's implemented via 
ConceptReference.



Comment at: clang/include/clang/AST/ExprConcepts.h:140-143
   SourceLocation getBeginLoc() const LLVM_READONLY {
-if (auto QualifierLoc = getNestedNameSpecifierLoc())
+if (auto QualifierLoc = CR->getNestedNameSpecifierLoc())
   return QualifierLoc.getBeginLoc();
+return CR->getConceptNameInfo().getBeginLoc();

cor3ntin wrote:
> Should there be a getLocation() method on `ConceptReference` ? It seems 
> useful. maybe even a `getSourceRange()` method too
agree, though we actually shouldn't call ConceptReference::getLocation() method 
here because primary location != start location.

I think
 - ConceptReference::getLocation() should return getConceptNameLoc() (just an 
alias)
 - ConceptSpecializationExpr::getExprLoc() should return 
ConceptReference::getLocation()
 - ConceptReference::getBeginLoc() should contain this logic, 
ConceptSpecializationExpr::getBeginLoc() should return it
 - ditto end loc
 - ConceptReference::getSourceRange() is a useful helper
 - ConceptSpecializationExpr already has getSourceRange() inherited from Stmt



Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:2517
+const ConceptReference *CR) {
+  TRY_TO(VisitConceptReference(CR));
+  TRY_TO(TraverseNestedNameSpecifierLoc(CR->getNestedNameSpecifierLoc()));

I think this should be guarded by `if 
(!getDerived().shouldTraversePostOrder())`, and then the opposite at the end



Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:318
+  /// \returns false if the visitation was terminated early, true otherwise.
+  bool TraverseConceptLoc(const ConceptLoc *CL);
+

massberg wrote:
> This is basically the old `TraverseConceptReferenceHelper` function. Is it by 
> purpose that this isn't const 

[PATCH] D157385: [clang][CFG] Cleanup functions

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157385

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


[PATCH] D157383: [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder accepted this revision.
tbaeder added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/AST/Interp/Interp.h:530-535
   if (S.checkingForUndefinedBehavior()) {
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();

hazohelet wrote:
> tbaeder wrote:
> > hazohelet wrote:
> > > I'm not sure whether this branch takes effect.
> > > I could not find codes that takes this block, so I haven't added tests 
> > > for this.
> > > 
> > > FWIW, the old interpreter does not have the corresponding 
> > > `warn_integer_constant_overflow` generated against overflowing increments.
> > Is is not this: https://godbolt.org/z/eqn4Gs13q?
> That note is emitted from `S.CCEDiag` at L539.
> This warning looks like it is intended to be emitted when the function is not 
> constexpr, but it does not appear.
From reading the code, it makes sense to me do emit this diagnostic here, but I 
can't get it to trigger either because the increment operator is always 
evaluated standalone and not as part of a function.

For this patch, let's ignore that. The changes here are fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157383

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


[PATCH] D158071: [clang] Remove rdar links; NFC

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: JDevlieghere, zaks.anna, rjmccall, ahatanak.
Herald added subscribers: steakhal, jdoerfert, martong, pengfei, arphaman.
Herald added a reviewer: NoQ.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a subscriber: wangpc.
Herald added a project: clang.

We have a new policy in place making links to private resources something we 
try to avoid in source and test files. Normally, we'd organically switch to the 
new policy rather than make a sweeping change across a project. However, Clang 
is in a somewhat special circumstance currently: recently, I've had several new 
contributors run into rdar links around test code which their patch was 
changing the behavior of. This turns out to be a surprisingly bad experience, 
especially for newer folks, for a handful of reasons: not understanding what 
the link is and feeling intimidated by it, wondering whether their changes are 
actually breaking something important to a downstream in some way, having to 
hunt down strangers not involved with the patch to impose on them for help, 
accidental pressure from asking for potentially private IP to be made public, 
etc. Because folks run into these links entirely by chance (through fixing bugs 
or working on new features), there's not really a set of problematic links to 
focus on -- all of the links have basically the same potential for causing 
these problems. As a result, this is an omnibus patch to remove all such links.

This was not a mechanical change; it was done by manually searching for `rdar`, 
`radar`, `radr`, and other variants to find all the various problematic links. 
From there, I tried to retain or reword the surrounding comments so that we 
would lose as little context as possible. However, because most links were just 
a plain link with no supporting context, the majority of the changes are simple 
removals.

I'm putting this up as a patch for review and adding reviewers from Apple in 
case someone wants to go through the removed links to see if there are 
situations where adding more supporting comments would be warranted. For 
example, there were a few links removed from source code instead of test files; 
perhaps augmenting those comments would be of benefit? However, I do not expect 
every one of these links to be replaced with comments as part of this review. 
(If someone has different expectations, let's work together on a practical way 
to proceed.)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158071

Files:
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp
  clang/test/ARCMT/GC-check-warn-nsalloc.m
  clang/test/ARCMT/GC-no-finalize-removal.m
  clang/test/ARCMT/GC-no-finalize-removal.m.result
  clang/test/ARCMT/GC.m
  clang/test/ARCMT/GC.m.result
  clang/test/ARCMT/check-with-pch.m
  clang/test/ARCMT/checking.m
  clang/test/ARCMT/no-canceling-bridge-to-bridge-cast.m
  clang/test/ARCMT/nonobjc-to-objc-cast-2.m
  clang/test/ARCMT/objcmt-arc-cf-annotations.m
  clang/test/ARCMT/objcmt-arc-cf-annotations.m.result
  clang/test/ARCMT/objcmt-atomic-property.m
  clang/test/ARCMT/objcmt-atomic-property.m.result
  clang/test/ARCMT/objcmt-boxing.m
  clang/test/ARCMT/objcmt-boxing.m.result
  clang/test/ARCMT/objcmt-migrate-all.m
  clang/test/ARCMT/objcmt-migrate-all.m.result
  clang/test/ARCMT/objcmt-ns-macros.m
  clang/test/ARCMT/objcmt-ns-macros.m.result
  clang/test/ARCMT/objcmt-ns-nonatomic-iosonly.m
  clang/test/ARCMT/objcmt-ns-nonatomic-iosonly.m.result
  clang/test/ARCMT/objcmt-ns-returns-inner-pointer.m
  clang/test/ARCMT/objcmt-ns-returns-inner-pointer.m.result
  clang/test/ARCMT/objcmt-property-availability.m
  clang/test/ARCMT/objcmt-property-availability.m.result
  clang/test/ARCMT/objcmt-property-dot-syntax.m
  clang/test/ARCMT/objcmt-property-dot-syntax.m.result
  clang/test/ARCMT/objcmt-property.m
  clang/test/ARCMT/objcmt-property.m.result
  clang/test/ARCMT/objcmt-protocol-conformance.m
  clang/test/ARCMT/objcmt-protocol-conformance.m.result
  clang/test/ARCMT/objcmt-undefined-ns-macros.m
  clang/test/ARCMT/objcmt-undefined-ns-macros.m.result
  clang/test/Analysis/DeallocMissingRelease.m
  clang/test/Analysis/DeallocUseAfterFreeErrors.m
  clang/test/Analysis/Inputs/expected-plists/edges-new.mm.plist
  clang/test/Analysis/Inputs/expected-plists/inline-plist.c.plist
  clang/test/Analysis/Inputs/expected-plists/malloc-plist.c.plist
  clang/test/Analysis/Inputs/expected-plists/plist-output.m.plist
  clang/test/Analysis/Inputs/expected-plists/retain-release.m.objc.plist
  clang/test/Analysis/Inputs/expected-plists/retain-release.m.objcpp.plist
  clang/test/Analysis/NSString.m
  clang/test/Analysis/OSAtomic_mac.cpp
  clang/test/Analysis/PR46264.cpp
  clang/test/Analysis/UserNullabilityAnnotations.m
  clang/test/Analysis/array-struct-region.c
  clan

[PATCH] D157933: [OpenMP 5.1] Parsing and Sema support for `scope` construct

2023-08-16 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Could you also add the nesting tests for outer scope directive? Currently it 
tests only for inner


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

https://reviews.llvm.org/D157933

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-16 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy updated this revision to Diff 550703.
donat.nagy added a comment.

Updated the release notes. This could be the final version of this commit if 
you agree that it's good enough.


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

https://reviews.llvm.org/D156312

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/bitwise-ops-nocrash.c
  clang/test/Analysis/bitwise-ops.c
  clang/test/Analysis/bitwise-shift-common.c
  clang/test/Analysis/bitwise-shift-pedantic.c
  clang/test/Analysis/bitwise-shift-sanity-checks.c
  clang/test/Analysis/bitwise-shift-state-update.c
  clang/test/Analysis/casts.c
  clang/test/Analysis/diagnostics/track_subexpressions.cpp
  clang/test/Analysis/left-shift-cxx2a.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/symbol-simplification-nonloc-loc.cpp

Index: clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
===
--- clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
+++ clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
@@ -14,7 +14,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -29,7 +29,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -43,8 +43,6 @@
   nonloc_OP_loc(p, BINOP(-)); // no-crash
 
   // Bitwise operators:
-  // expected-warning@+2 {{The result of the left shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
-  // expected-warning@+2 {{The result of the right shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
   nonloc_OP_loc(p, BINOP(<<)); // no-crash
   nonloc_OP_loc(p, BINOP(>>)); // no-crash
   nonloc_OP_loc(p, BINOP(&));
Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -24,6 +24,7 @@
 // CHECK-NEXT: apiModeling.TrustReturnsNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
+// CHECK-NEXT: core.BitwiseShift
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonnilStringConstants
Index: clang/test/Analysis/left-shift-cxx2a.cpp
===
--- clang/test/Analysis/left-shift-cxx2a.cpp
+++ clang/test/Analysis/left-shift-cxx2a.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
 
 int testNegativeShift(int a) {
   if (a == -5) {
Index: clang/test/Analysis/diagnostics/track_subexpressions.cpp
===
--- clang/test/Analysis/diagnostics/track_subexpressions.cpp
+++ clang/test/Analysis/diagnostics/track_subexpressions.cpp
@@ -12,10 +12,10 @@
 
 void shift_by_undefined_value() {
   uint8_t shift_amount = get_uint8_max(); // expected-note{{'shift_amount' initialized to 255}}
-// expected-note@-1{{Calling 'get_uint8_max'}}
-// expected-note@-2{{Returning from 'get_uint8_max'}}
-  (void)(TCP_MAXWIN << shift_amount); // expected-warning{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
-  // expected-note@-1{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
+  // expected-note@-1{{Calling 'get_uint8_max'}}
+  // expected-note@-2{{Returning from 'get_uint8_max'}}
+  (void)(TCP_MAXWIN << shift_amount); // expected-warning{{Left shift by '255' overflows the capacity of

[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-16 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy marked 2 inline comments as done.
donat.nagy added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:81
+
+Ensure the shift operands are in proper range before shifting.
+

donat.nagy wrote:
> steakhal wrote:
> > We should exactly elaborate on what "proper" means here.
> What would you suggest? I could try to write a slightly longer suggestion, 
> but I don't want to repeat the same conditions that I listed above the code 
> example.
(I'm marking this request as "Done" because I couldn't find a better wording. 
Feel free to reopen the discussion if you wish.)


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

https://reviews.llvm.org/D156312

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


[PATCH] D158071: [clang] Remove rdar links; NFC

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Having worked with phabricator for a long time, this is the first time I've 
seen it "pull a github" where it just doesn't want to show you the content of 
anything in the review. Ugh, sorry for that! You can click on Changeset List 
above to see the list of changed files, and you can click on individual files 
to see changes and leave comments, which is pretty awful because of the amount 
of clicking involved but does work. I could split it up by top-level directory, 
but then we'd have approx 30 reviews to cover which feels like more effort than 
an NFC change to comments is worth. I'd recommend we try to advance with this 
review as best we can (I'm assuming there's only some subset of files people 
are interested in trying to retain comments for, so thinking that clicking 
around won't be too awful), but if others have a suggestion on a better way 
that isn't overly onerous, I'm happy to consider it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158071

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-16 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy updated this revision to Diff 550706.
donat.nagy added a comment.

A few minutes ago I accidentally re-uploaded the previous version of the patch; 
now I'm fixing this by uploading the actually updated variant.


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

https://reviews.llvm.org/D156312

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/bitwise-ops-nocrash.c
  clang/test/Analysis/bitwise-ops.c
  clang/test/Analysis/bitwise-shift-common.c
  clang/test/Analysis/bitwise-shift-pedantic.c
  clang/test/Analysis/bitwise-shift-sanity-checks.c
  clang/test/Analysis/bitwise-shift-state-update.c
  clang/test/Analysis/casts.c
  clang/test/Analysis/diagnostics/track_subexpressions.cpp
  clang/test/Analysis/left-shift-cxx2a.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/symbol-simplification-nonloc-loc.cpp

Index: clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
===
--- clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
+++ clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
@@ -14,7 +14,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -29,7 +29,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -43,8 +43,6 @@
   nonloc_OP_loc(p, BINOP(-)); // no-crash
 
   // Bitwise operators:
-  // expected-warning@+2 {{The result of the left shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
-  // expected-warning@+2 {{The result of the right shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
   nonloc_OP_loc(p, BINOP(<<)); // no-crash
   nonloc_OP_loc(p, BINOP(>>)); // no-crash
   nonloc_OP_loc(p, BINOP(&));
Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -24,6 +24,7 @@
 // CHECK-NEXT: apiModeling.TrustReturnsNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
+// CHECK-NEXT: core.BitwiseShift
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonnilStringConstants
Index: clang/test/Analysis/left-shift-cxx2a.cpp
===
--- clang/test/Analysis/left-shift-cxx2a.cpp
+++ clang/test/Analysis/left-shift-cxx2a.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
 
 int testNegativeShift(int a) {
   if (a == -5) {
Index: clang/test/Analysis/diagnostics/track_subexpressions.cpp
===
--- clang/test/Analysis/diagnostics/track_subexpressions.cpp
+++ clang/test/Analysis/diagnostics/track_subexpressions.cpp
@@ -12,10 +12,10 @@
 
 void shift_by_undefined_value() {
   uint8_t shift_amount = get_uint8_max(); // expected-note{{'shift_amount' initialized to 255}}
-// expected-note@-1{{Calling 'get_uint8_max'}}
-// expected-note@-2{{Returning from 'get_uint8_max'}}
-  (void)(TCP_MAXWIN << shift_amount); // expected-warning{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
-  // expected-note@-1{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
+  // expected-note@-1{{Calling 'get_uint8_max'}}
+  // expected-note@-2{{Returning from 'get_uint8_max'}}
+  (void)(TCP_MAXWIN << shift_amount); // 

[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-08-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/AST/Interp/Context.h:88
+  /// Returns the program. This is only needed for unittests.
+  Program &getProgram() const { return *P.get(); }
+

This should return a const ref



Comment at: clang/lib/AST/Interp/Pointer.h:221
 }
+
 assert(Offset != Base && "not an array element");

WS only change



Comment at: clang/lib/AST/Interp/Pointer.h:342
+
+// narrow()ed element in a composite array.
+if (Base > 0 && Base == Offset)

Can you be a bit more verbose here? I can't figure out what is happening from 
the comment!


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

https://reviews.llvm.org/D158069

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


[PATCH] D155610: [Clang][Sema] Fix display of characters on static assertion failure

2023-08-16 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 550707.
hazohelet marked 3 inline comments as done.
hazohelet added a comment.

Address comments from Hubert

- Bring back type prefix
- NFC stylistic changes


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

https://reviews.llvm.org/D155610

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/Lexer/cxx1z-trigraphs.cpp
  clang/test/SemaCXX/static-assert-cxx26.cpp
  clang/test/SemaCXX/static-assert.cpp

Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -268,7 +268,31 @@
 return 'c';
   }
   static_assert(getChar() == 'a', ""); // expected-error {{failed}} \
-   // expected-note {{evaluates to ''c' == 'a''}}
+   // expected-note {{evaluates to ''c' (0x63, 99) == 'a' (0x61, 97)'}}
+  static_assert((char)9 == '\x61', ""); // expected-error {{failed}} \
+// expected-note {{evaluates to ''\t' (0x09, 9) == 'a' (0x61, 97)'}}
+  static_assert((char)10 == '\0', ""); // expected-error {{failed}} \
+   // expected-note {{n' (0x0A, 10) == '' (0x00, 0)'}}
+  // The note above is intended to match "evaluates to '\n' (0x0A, 10) == '' (0x00, 0)'", but if we write it as it is,
+  // the "\n" cannot be consumed by the diagnostic consumer.
+  static_assert((signed char)10 == (char)-123, ""); // expected-error {{failed}} \
+// expected-note {{evaluates to '10 == '<85>' (0x85, -123)'}}
+  static_assert((char)-4 == (unsigned char)-8, ""); // expected-error {{failed}} \
+// expected-note {{evaluates to ''' (0xFC, -4) == 248'}}
+  static_assert((char)-128 == (char)-123, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to ''<80>' (0x80, -128) == '<85>' (0x85, -123)'}}
+  static_assert('\xA0' == (char)'\x20', ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to ''' (0xA0, -96) == ' ' (0x20, 32)'}}
+  static_assert((char16_t)L'ゆ' == L"C̵̭̯̠̎͌ͅť̺"[1], ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'u'ゆ' (0x3086, 12422) == L'̵' (0x335, 821)'}}
+  static_assert(L"\/"[1] == u'\xFFFD', ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'L'/' (0xFF0F, 65295) == u'�' (0xFFFD, 65533)'}}
+  static_assert(L"⚾"[0] == U'🌍', ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'L'⚾' (0x26BE, 9918) == U'🌍' (0x1F30D, 127757)'}}
+  static_assert(U"\a"[0] == (wchar_t)9, ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'U'\a' (0x07, 7) == L'\t' (0x09, 9)'}}
+  static_assert(L"§"[0] == U'Ö', ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 'L'§' (0xA7, 167) == U'Ö' (0xD6, 214)'}}
 
   /// Bools are printed as bools.
   constexpr bool invert(bool b) {
Index: clang/test/SemaCXX/static-assert-cxx26.cpp
===
--- clang/test/SemaCXX/static-assert-cxx26.cpp
+++ clang/test/SemaCXX/static-assert-cxx26.cpp
@@ -298,3 +298,12 @@
 Bad b; // expected-note {{in instantiation}}
 
 }
+
+namespace EscapeInDiagnostic {
+static_assert('\u{9}' == (char)1, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to ''\t' (0x09, 9) == '' (0x01, 1)'}}
+static_assert((char8_t)-128 == (char8_t)-123, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to 'u8'<80>' (0x80, 128) == u8'<85>' (0x85, 133)'}}
+static_assert((char16_t)0xFEFF == (char16_t)0xDB93, ""); // expected-error {{failed}} \
+ // expected-note {{evaluates to 'u'' (0xFEFF, 65279) == u'\xDB93' (0xDB93, 56211)'}}
+}
Index: clang/test/Lexer/cxx1z-trigraphs.cpp
===
--- clang/test/Lexer/cxx1z-trigraphs.cpp
+++ clang/test/Lexer/cxx1z-trigraphs.cpp
@@ -21,7 +21,7 @@
 
 #if !ENABLED_TRIGRAPHS
 // expected-error@11 {{}} expected-warning@11 {{trigraph ignored}}
-// expected-error@13 {{failed}} expected-warning@13 {{trigraph ignored}} expected-note@13 {{evaluates to ''?' == '#''}}
+// expected-error@13 {{failed}} expected-warning@13 {{trigraph ignored}} expected-note@13 {{evaluates to ''?' (0x3F, 63) == '#' (0x23, 35)'}}
 // expected-error@16 {{}}
 // expected-error@20 {{}}
 #else

[PATCH] D155713: [clang] Fix interaction between dllimport and exclude_from_explicit_instantiation

2023-08-16 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Apologies for the delay, I'm still catching up with my post-vacation backlog.

(For my notes, this came up in https://reviews.llvm.org/D153709)

I think the root of this bug is how class-level dll attributes get propagated 
to class members. Here is an example:

  template 
  struct __declspec(dllimport) S {
void __attribute__((exclude_from_explicit_instantiation)) f() {}
  };
  
  extern template struct S;

The problem is that when `S` is explicitly instantiated, the dllimport 
attribute gets propagated to all its members, assuming all members are also 
being instantiated -- which may not be true now that 
`exclude_from_explicit_instantiation` exists.

I think the right location for the fix is where that inheritance happens:

  diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
  index a7ab0948d01b..12cb2542641a 100644
  --- a/clang/lib/Sema/SemaDeclCXX.cpp
  +++ b/clang/lib/Sema/SemaDeclCXX.cpp
  @@ -6592,6 +6592,13 @@ void Sema::checkClassLevelDLLAttribute(CXXRecordDecl 
*Class) {
   if (!VD && !MD)
 continue;
   
  +if ((TSK == TSK_ExplicitInstantiationDeclaration ||
  + TSK == TSK_ExplicitInstantiationDefinition) &&
  +Member->hasAttr()) {
  +  // Skip members excluded from instantiation.
  +  continue;
  +}
  +
   if (MD) {
 // Don't process deleted methods.
 if (MD->isDeleted())

That's also the approach suggested in 
https://bugs.llvm.org/show_bug.cgi?id=41018#c0 (and it also handles the 
dllexport case.)

That doesn't handle the second of your test cases though, where dllimport is 
put on the member directly:

  template 
  struct  S {
void __attribute__((exclude_from_explicit_instantiation)) 
__declspec(dllimport) f() {}
  };
  
  extern template struct S;
  
  void use(S &s) {
s.f();
  }

Now, `S::f` *is* technically being excluded from explicit instantiation as 
the attribute says, but when it gets implicitly instantiated it will be 
dllimport, because it was declared that way.

It's not clear to me how we'd want to handle that. I don't think it comes up in 
libc++, and I can't think of any code that would want to do that either, really.

https://bugs.llvm.org/show_bug.cgi?id=41018#c0 suggest emitting an error about 
incompatible attributes in that case. I suppose it could also be a warning, or 
we could do nothing for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155713

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


[PATCH] D158061: [clang] Construct ExprRequirement with SubstitutionDiagnostic on SubstFailure

2023-08-16 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 550713.
zyounan added a comment.

Adapt to D157554 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158061

Files:
  clang/include/clang/AST/ExprConcepts.h
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
  clang/test/SemaCXX/concept-fatal-error.cpp

Index: clang/test/SemaCXX/concept-fatal-error.cpp
===
--- clang/test/SemaCXX/concept-fatal-error.cpp
+++ clang/test/SemaCXX/concept-fatal-error.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -ferror-limit 1 -verify %s
 
 template 
 concept f = requires { 42; };
@@ -6,5 +6,5 @@
   // The missing semicolon will trigger an error and -ferror-limit=1 will make it fatal
   // We test that we do not crash in such cases (#55401)
   int i = requires { { i } f } // expected-error {{expected ';' at end of declaration list}}
-   // expected-error@* {{too many errros emitted}}
+   // expected-error@* {{too many errors emitted}}
 };
Index: clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+
+template  class normal_iterator {};
+
+template  struct is_convertible {};
+
+template 
+inline constexpr bool is_convertible_v = is_convertible::value; // #1
+
+// expected-error@#1 {{no member named 'value' in 'is_convertible'}}
+
+template 
+concept convertible_to = is_convertible_v; // expected-note 0+{{}}
+template 
+  requires requires(IteratorL lhs, IteratorR rhs) { // expected-note 0+{{}}
+{ lhs == rhs } -> convertible_to; // #2
+  }
+constexpr bool compare(normal_iterator lhs, normal_iterator rhs) {
+  return false;
+}
+
+// We don't know exactly the substituted type for `lhs == rhs`, thus a placeholder 'expr-type' is emitted.
+// expected-note@#2 {{'convertible_to'}}
+
+// Consume remaining notes/errors.
+// expected-note@* 0+{{}}
+// expected-error@* 0+{{}}
+class Object;
+
+void function() {
+  normal_iterator begin, end;
+  compare(begin, end);
+}
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2271,9 +2271,9 @@
   getPackIndex(Pack), Arg, TL.getNameLoc());
 }
 
-template
 static concepts::Requirement::SubstitutionDiagnostic *
-createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
+createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
+concepts::EntityPrinter Printer) {
   SmallString<128> Message;
   SourceLocation ErrorLoc;
   if (Info.hasSFINAEDiagnostic()) {
@@ -2297,6 +2297,19 @@
   StringRef(MessageBuf, Message.size())};
 }
 
+concepts::Requirement::SubstitutionDiagnostic *
+concepts::createSubstDiagAt(Sema &S, SourceLocation Location,
+EntityPrinter Printer) {
+  SmallString<128> Entity;
+  llvm::raw_svector_ostream OS(Entity);
+  Printer(OS);
+  char *EntityBuf = new (S.Context) char[Entity.size()];
+  llvm::copy(Entity, EntityBuf);
+  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
+  /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
+  /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
+}
+
 ExprResult TemplateInstantiator::TransformRequiresTypeParams(
 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
 RequiresExprBodyDecl *Body, ArrayRef Params,
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
@@ -9074,16 +9075,23 @@
 MLTAL.addOuterRetainedLevels(TPL->getDepth());
 const TypeConstraint *TC = Param->getTypeConstraint();
 assert(TC && "Type Constraint cannot be null here");
-ExprResult Constraint =
-SubstExpr(TC->getImmediatelyDeclaredConstraint(), MLTAL);
+auto *IDC = TC->getImmediatelyDeclaredConstraint();
+assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
+ExprResult Constraint = SubstExpr(IDC, MLTAL);
 if (Constraint.isInvalid()) {
   Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
-} else {
-  SubstitutedConstraintExpr =
-

[PATCH] D156605: [clangd][CodeComplete] Improve FunctionCanBeCall

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks, this does look better.

I agree with Nathan's comments and will leave final stamp to him.




Comment at: clang-tools-extra/clangd/CodeCompletionStrings.cpp:144
+
+  // This variable would be discarded directly at the end of this function. We
+  // store part of the chunks of snippets here if DropFunctionArguments is

I find this comment very unclear, I think because it starts with implementation 
details and works its way up to general principles.

I think `Buffer that snippet chunks are written to once we've decided to 
discard the snippet due to DropFunctionArguments` or so would be enough.

However I'd rather drop this variable entirely if possible, the data flow is 
confusing. See below.



Comment at: clang-tools-extra/clangd/CodeCompletionStrings.cpp:148
+  // Signature for the function would be preserved.
+  // It is preferable if we don't produce the arguments at the clang site. But
+  // that would also lose the signatures, which could sometimes help users to

For the reason you give here, it's actually *not* preferable. So I'd suggest 
leaving out this comment.



Comment at: clang-tools-extra/clangd/CodeCompletionStrings.cpp:258
 case CodeCompletionString::CK_RightParen:
+  if (DropFunctionArguments &&
+  ResultKind == CodeCompletionResult::RK_Declaration)

nridge wrote:
> It looks like we are assuming two things:
> 
>  1. Any LeftParen in an RK_Declaration starts a function argument list
>  2. Everything that comes after the function argument list can be discarded
> 
> I think these assumptions are fine to make, but let's be explicit about them 
> in a comment
Agree, but also I think the code could reflect this more directly:
 - this should trigger only for CK_LeftParen, not CK_RightParen

Rather than redirecting output to a different string by reassigning the param, 
I think it would be a bit more direct to have

```
optional TruncateSnippetAt;
...
case CK_LeftBracket:
  if (DropFunctionArguments && ... && !TruncateSnippetAt)
TruncateSnippetAt = Snippet->size();
...
if (TruncateSnippetAt)
  Snippet->resize(*TruncateSnippetAt);
}
```

(though still not totally clear)



Comment at: clang-tools-extra/clangd/CodeCompletionStrings.h:45
 ///
+/// \p DropFunctionArguments indicates that the function call arguments should
+/// be omitted from the \p Snippet. If enabled, the \p Snippet will only 
contain

Prefer positive sense for bool params (`IncludeFunctionArguments`) to avoid 
double-negative confusion



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:1387
 
-  // When completing a non-static member function (and not via
-  // dot/arrow member access) and we're not inside that class' scope,
-  // it can't be a call.
+  // Decide whether or not a non-static member function can be a call.
   if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) 
{

This is confusing: the `CCC_Symbol` test is part of the specific heuristics 
being used (it's the "not via dot/arrow member access" part, right?) but you've 
moved the comment explaining what it does.

Also this function is just getting too long, and we're inlining more 
complicated control flow here.
Can we extract a function?

```
const auto *Method = ...;
if (Method & !Method->isStatic()) {
  R.FunctionCanBeCall = canMethodBeCalled(...);
}
```



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:1417
+
+  // If the member access "." or "->" is followed by a qualified Id and the
+  // object type is derived from or the same as that of the Id, then

This description is hard for me to follow, and it's hard to tell if this is 
independent of the previous check, or an exception to it.

An example would be clearer. (I think instead rather than in addition):
`Exception: foo->FooBase::bar() *is* a call`.





Comment at: clang/lib/Sema/SemaCodeComplete.cpp:1420
+  // the candidate functions should be perceived as calls.
+  if (const CXXRecordDecl *MaybeDerived = nullptr;
+  !BaseType.isNull() &&

`if (const CXXRecordDecl *BaseDecl = BaseType ? BaseType-> getAsCXXRecordDecl() 
: nullptr)`?
avoiding the reassignment inside a boolean expression


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156605

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


[PATCH] D158061: [clang] Construct ExprRequirement with SubstitutionDiagnostic on SubstFailure

2023-08-16 Thread Younan Zhang via Phabricator via cfe-commits
zyounan added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:9079
+auto *IDC = TC->getImmediatelyDeclaredConstraint();
+assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
+ExprResult Constraint = SubstExpr(IDC, MLTAL);

I'm adding another assertion here following up on D157554: If IDC is nullptr 
somehow, we will fall into the cast statement in the else block and crash 
anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158061

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 550719.
victorkingi marked 9 inline comments as done.
victorkingi added a comment.

code refactoring


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,52 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+
+! Check "unknown remark option" warning
+! RUN: %flang %s -O1 -R 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-WARN
+
+! Check "unknown remark option" warning with suggestion
+! RUN: %flang %s -O1 -Rpas 2>&1 | FileCheck %s --check-prefix=CHECK-WARN-SUGGEST
+
+! Check -Rno-pass, -Rno-pass-analysis, -Rno-pass-missed nothing emitted
+! RUN: %flang %s -O1 -Rno-pass 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-missed 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-analysis 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+! CHECK: optimization-remark.f90:48:5: remark: Loop deleted because it is invariant [-Rpass=loop-delete]
+! CHECK-REMARKS-MISSED: optimization-remark.f90:43:5: remark: loop not vectorized [-Rpass-missed=loop-vectorize]
+! CHECK-REMARKS-ANALYSIS: optimization-remark.f90:43:5: remark: loop not vectorized: instruction cannot be vectorized [-Rpass-analysis=loop-vectorize]
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+! CHECK-REMARKS-WARN: warning: unknown remark option '-R' [-Wunknown-warning-option]
+! CHECK-WARN-SUGGEST: warning: unknown remark option '-Rpas'; did you mean '-Rpass'? [-Wunknown-warning-option]
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -22,6 +22,7 @@
 #include "mlir/IR/AsmState.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Pass/PassManager.h"
+#include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Driver/Options.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
@@ -100,6 +101,54 @@
   llvm_unreachable("Invalid program action!");
 }
 
+// Emit a warning and typo hint for unknown warning opts
+static void emitUnknownDiagWarning(clang::DiagnosticsEngine &diags,
+   clang::diag::Flavor flavor,
+   llvm::StringRef prefix,
+   llvm::StringRef opt) {
+  llvm::StringRef suggestion =
+  clang::DiagnosticIDs::getNearestOption(flavor, opt);
+  diags.Report(clang::diag::warn_unknown_diag_option)
+  << (flavor == clang::diag::Flavor::WarningOrError ? 0 : 1)
+  << (prefix.str() += std::string(opt)) << !suggestion.empty()
+  << (prefix.str() += std::string(suggestion));
+}
+
+// Remarks are ignored by default in Diagnostic.td, hence, we have to
+// enable them here before execution. Clang follows same idea using
+// ProcessWarningOptions in Warnings.cpp
+// This function is also responsible for emitting early warnings for
+// invalid -R options.
+static void
+updateDiagEngineForOptRemarks(clang::DiagnosticsEngine &diagsEng,
+  const clang::DiagnosticOptions &opts) {
+  llvm::SmallVector diags;
+  const llvm::IntrusiveRefCntPtr diagIDs =
+  diagsEng.getDiagnosticIDs();
+
+  for (unsigned i = 0; i < opts.Remarks.size(); i++) {
+llvm::StringRef remarkOpt = opts.Remarks[i];
+const auto flavor = 

[PATCH] D156441: [clangd]Fix addUsing tweak doesn't traverse same-level anon namespaces

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This would be a great fix to have! However I don't think the specific changes 
to the RecursiveASTVisitor are correct.

I can see a couple of approaches:

1. prevent the RecursiveASTVisitor from traversing into uninteresting contexts, 
and drop the Encloses check in VisitUsingDecl
2. explicitly gather the list of interesting contexts

option 1 is most similar to this patch, I believe TraverseNamespaceDecl needs 
to call base::TraverseNamespaceDecl only if the NS either encloses the 
selection DC or is anonymous.

option 2 would mean walking up the declcontext chain and grabbing each entry 
and also getAnonymousNamespace() from TranslationUnitDecl and NamespaceDecl, 
and changing our Encloses() tests to check membership in that set.




Comment at: clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp:97
 
+  bool TraverseNamespaceDecl(NamespaceDecl *D) {
+for (auto *Decl : D->decls()) {

This doesn't look like it can be right:
 - there's no distinction on whether the namespace is anonymous or not
 - you're calling VisitUsingDecl, but also Base::TraverseNamespaceDecl which 
will visit the contained using decls again

this also suggests we need more testcases here: some negative ones verifying 
that we don't look at UsingDecls that are inside named namespaces.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156441

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


[clang] 871ee94 - [clang][ExprConst] Use call source range for 'in call to' diags

2023-08-16 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-08-16T15:22:29+02:00
New Revision: 871ee94141123f40cf0310ca89123c6c416c3d84

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

LOG: [clang][ExprConst] Use call source range for 'in call to' diags

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Frame.h
clang/lib/AST/Interp/InterpFrame.cpp
clang/lib/AST/Interp/InterpFrame.h
clang/lib/AST/Interp/State.cpp
clang/test/Misc/constexpr-source-ranges.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index ee2f3b7be1dabd..e3569be5549cfe 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -551,8 +551,8 @@ namespace {
 /// Temporaries - Temporary lvalues materialized within this stack frame.
 MapTy Temporaries;
 
-/// CallLoc - The location of the call expression for this call.
-SourceLocation CallLoc;
+/// CallRange - The source range of the call expression for this call.
+SourceRange CallRange;
 
 /// Index - The call index of this call.
 unsigned Index;
@@ -586,7 +586,7 @@ namespace {
 llvm::DenseMap LambdaCaptureFields;
 FieldDecl *LambdaThisCaptureField = nullptr;
 
-CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
+CallStackFrame(EvalInfo &Info, SourceRange CallRange,
const FunctionDecl *Callee, const LValue *This,
const Expr *CallExpr, CallRef Arguments);
 ~CallStackFrame();
@@ -630,7 +630,7 @@ namespace {
 void describe(llvm::raw_ostream &OS) const override;
 
 Frame *getCaller() const override { return Caller; }
-SourceLocation getCallLocation() const override { return CallLoc; }
+SourceRange getCallRange() const override { return CallRange; }
 const FunctionDecl *getCallee() const override { return Callee; }
 
 bool isStdFunction() const {
@@ -1468,11 +1468,11 @@ void 
SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
   setInvalid();
 }
 
-CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
+CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
const FunctionDecl *Callee, const LValue *This,
const Expr *CallExpr, CallRef Call)
 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
-  CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc),
+  CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
   Index(Info.NextCallIndex++) {
   Info.CurrentCall = this;
   ++Info.CallStackDepth;
@@ -6245,7 +6245,7 @@ static bool HandleFunctionCall(SourceLocation CallLoc,
   if (!Info.CheckCallLimit(CallLoc))
 return false;
 
-  CallStackFrame Frame(Info, CallLoc, Callee, This, E, Call);
+  CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
 
   // For a trivial copy or move assignment, perform an APValue copy. This is
   // essential for unions, where the operations performed by the assignment
@@ -6310,7 +6310,7 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
   Info,
   ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
   RD->getNumBases());
-  CallStackFrame Frame(Info, CallLoc, Definition, &This, E, Call);
+  CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
 
   // FIXME: Creating an APValue just to hold a nonexistent return value is
   // wasteful.
@@ -6518,7 +6518,7 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
  CallScope.destroy();
 }
 
-static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
+static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
   const LValue &This, APValue &Value,
   QualType T) {
   // Objects can only be destroyed while they're within their lifetimes.
@@ -6528,21 +6528,22 @@ static bool HandleDestructionImpl(EvalInfo &Info, 
SourceLocation CallLoc,
   if (Value.isAbsent() && !T->isNullPtrType()) {
 APValue Printable;
 This.moveInto(Printable);
-Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
-  << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
+Info.FFDiag(CallRange.getBegin(),
+diag::note_constexpr_destroy_out_of_lifetime)
+<< Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
 return false;
   }
 
   // Invent an expression for location purposes.
   // FIXME: We shouldn't need to do this.
-  OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
+  OpaqueValueExpr LocE(CallRange.getBegin(), 

[PATCH] D156604: [clang][ExprConst] Use call source range for 'in call to' diags

2023-08-16 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG871ee9414112: [clang][ExprConst] Use call source range for 
'in call to' diags (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D156604?vs=548520&id=550724#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156604

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/Frame.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/lib/AST/Interp/InterpFrame.h
  clang/lib/AST/Interp/State.cpp
  clang/test/Misc/constexpr-source-ranges.cpp

Index: clang/test/Misc/constexpr-source-ranges.cpp
===
--- clang/test/Misc/constexpr-source-ranges.cpp
+++ clang/test/Misc/constexpr-source-ranges.cpp
@@ -25,3 +25,12 @@
 /// evaluating the static_assert above.
 // CHECK: constexpr-source-ranges.cpp:23:15:{23:15-23:31}
 // CHECK: constexpr-source-ranges.cpp:21:12:{21:14-21:20}
+
+constexpr int div(bool a, bool b) {
+  return 1 / (int)b;
+}
+constexpr int ints(int a, int b, int c, int d) {
+  return 1;
+}
+static_assert(ints(1, div(true, false), 2, div(false, true)) == 1, "");
+// CHECK: constexpr-source-ranges.cpp:35:23:{35:23-35:39}
Index: clang/lib/AST/Interp/State.cpp
===
--- clang/lib/AST/Interp/State.cpp
+++ clang/lib/AST/Interp/State.cpp
@@ -129,13 +129,13 @@
   const Frame *Top = getCurrentFrame();
   const Frame *Bottom = getBottomFrame();
   for (const Frame *F = Top; F != Bottom; F = F->getCaller(), ++CallIdx) {
-SourceLocation CallLocation = F->getCallLocation();
+SourceRange CallRange = F->getCallRange();
 
 // Skip this call?
 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
   if (CallIdx == SkipStart) {
 // Note that we're skipping calls.
-addDiag(CallLocation, diag::note_constexpr_calls_suppressed)
+addDiag(CallRange.getBegin(), diag::note_constexpr_calls_suppressed)
 << unsigned(ActiveCalls - Limit);
   }
   continue;
@@ -146,7 +146,8 @@
 if (const auto *CD =
 dyn_cast_if_present(F->getCallee());
 CD && CD->isInheritingConstructor()) {
-  addDiag(CallLocation, diag::note_constexpr_inherited_ctor_call_here)
+  addDiag(CallRange.getBegin(),
+  diag::note_constexpr_inherited_ctor_call_here)
   << CD->getParent();
   continue;
 }
@@ -154,6 +155,7 @@
 SmallString<128> Buffer;
 llvm::raw_svector_ostream Out(Buffer);
 F->describe(Out);
-addDiag(CallLocation, diag::note_constexpr_call_here) << Out.str();
+addDiag(CallRange.getBegin(), diag::note_constexpr_call_here)
+<< Out.str() << CallRange;
   }
 }
Index: clang/lib/AST/Interp/InterpFrame.h
===
--- clang/lib/AST/Interp/InterpFrame.h
+++ clang/lib/AST/Interp/InterpFrame.h
@@ -56,7 +56,7 @@
   Frame *getCaller() const override;
 
   /// Returns the location of the call to the frame.
-  SourceLocation getCallLocation() const override;
+  SourceRange getCallRange() const override;
 
   /// Returns the caller.
   const FunctionDecl *getCallee() const override;
Index: clang/lib/AST/Interp/InterpFrame.cpp
===
--- clang/lib/AST/Interp/InterpFrame.cpp
+++ clang/lib/AST/Interp/InterpFrame.cpp
@@ -176,10 +176,10 @@
   return S.getSplitFrame();
 }
 
-SourceLocation InterpFrame::getCallLocation() const {
+SourceRange InterpFrame::getCallRange() const {
   if (!Caller->Func)
-return S.getLocation(nullptr, {});
-  return S.getLocation(Caller->Func, RetPC - sizeof(uintptr_t));
+return S.getRange(nullptr, {});
+  return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
 }
 
 const FunctionDecl *InterpFrame::getCallee() const {
Index: clang/lib/AST/Interp/Frame.h
===
--- clang/lib/AST/Interp/Frame.h
+++ clang/lib/AST/Interp/Frame.h
@@ -33,7 +33,7 @@
   virtual Frame *getCaller() const = 0;
 
   /// Returns the location of the call site.
-  virtual SourceLocation getCallLocation() const = 0;
+  virtual SourceRange getCallRange() const = 0;
 
   /// Returns the called function's declaration.
   virtual const FunctionDecl *getCallee() const = 0;
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -551,8 +551,8 @@
 /// Temporaries - Temporary lvalues materialized within this stack frame.
 MapTy Temporaries;
 
-/// CallLoc - The location of the call expression for this call.
-SourceLocation CallLoc;
+/// CallRange - The source range of the call expression for this call.
+SourceRange CallRange;
 
 /// Index - The call index of this call.
 unsigned Index;

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 550725.
victorkingi added a comment.

code refactoring


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,52 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+
+! Check "unknown remark option" warning
+! RUN: %flang %s -O1 -R 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-WARN
+
+! Check "unknown remark option" warning with suggestion
+! RUN: %flang %s -O1 -Rpas 2>&1 | FileCheck %s --check-prefix=CHECK-WARN-SUGGEST
+
+! Check -Rno-pass, -Rno-pass-analysis, -Rno-pass-missed nothing emitted
+! RUN: %flang %s -O1 -Rno-pass 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-missed 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-analysis 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+! CHECK: optimization-remark.f90:48:5: remark: Loop deleted because it is invariant [-Rpass=loop-delete]
+! CHECK-REMARKS-MISSED: optimization-remark.f90:43:5: remark: loop not vectorized [-Rpass-missed=loop-vectorize]
+! CHECK-REMARKS-ANALYSIS: optimization-remark.f90:43:5: remark: loop not vectorized: instruction cannot be vectorized [-Rpass-analysis=loop-vectorize]
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+! CHECK-REMARKS-WARN: warning: unknown remark option '-R' [-Wunknown-warning-option]
+! CHECK-WARN-SUGGEST: warning: unknown remark option '-Rpas'; did you mean '-Rpass'? [-Wunknown-warning-option]
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -22,6 +22,7 @@
 #include "mlir/IR/AsmState.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Pass/PassManager.h"
+#include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Driver/Options.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
@@ -100,6 +101,54 @@
   llvm_unreachable("Invalid program action!");
 }
 
+// Emit a warning and typo hint for unknown warning opts
+static void emitUnknownDiagWarning(clang::DiagnosticsEngine &diags,
+   clang::diag::Flavor flavor,
+   llvm::StringRef prefix,
+   llvm::StringRef opt) {
+  llvm::StringRef suggestion =
+  clang::DiagnosticIDs::getNearestOption(flavor, opt);
+  diags.Report(clang::diag::warn_unknown_diag_option)
+  << (flavor == clang::diag::Flavor::WarningOrError ? 0 : 1)
+  << (prefix.str() += std::string(opt)) << !suggestion.empty()
+  << (prefix.str() += std::string(suggestion));
+}
+
+// Remarks are ignored by default in Diagnostic.td, hence, we have to
+// enable them here before execution. Clang follows same idea using
+// ProcessWarningOptions in Warnings.cpp
+// This function is also responsible for emitting early warnings for
+// invalid -R options.
+static void
+updateDiagEngineForOptRemarks(clang::DiagnosticsEngine &diagsEng,
+  const clang::DiagnosticOptions &opts) {
+  llvm::SmallVector diags;
+  const llvm::IntrusiveRefCntPtr diagIDs =
+  diagsEng.getDiagnosticIDs();
+
+  for (unsigned i = 0; i < opts.Remarks.size(); i++) {
+llvm::StringRef remarkOpt = opts.Remarks[i];
+const auto flavor = clang::diag::Flavor::Remark;
+
+// Check t

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi added inline comments.



Comment at: flang/include/flang/Frontend/CodeGenOptions.h:76-81
+RK_Missing,// Remark argument not present on the command line.
+RK_Enabled,// Remark enabled via '-Rgroup'.
+RK_EnabledEverything,  // Remark enabled via '-Reverything'.
+RK_Disabled,   // Remark disabled via '-Rno-group'.
+RK_DisabledEverything, // Remark disabled via '-Rno-everything'.
+RK_WithPattern,// Remark pattern specified via '-Rgroup=regexp'.

awarzynski wrote:
> I only see `RK_Enabled` and `RK_Disabled` being used, though I don't see 
> `-Rgroup` nor `-Rno-group` being tested 🤔 .
`-Rgroup` represents `-Rpass`, `-Rpass-missed` and `-Rpass-analysis`. Same 
applies to the `no` variation



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:227
 
+  // Specifies, using a regex, which successful optimization passes done,
+  // to include in the final optimization record file generated. If not 
provided

tschuett wrote:
> awarzynski wrote:
> > Do you know whether that only includes middle-end, or also back-end passes?
> I use -Rpass-missed='gisel*'  for GlobalIsel aka backend. I am interested in 
> doing that exercise with Flang.
Includes both middle and backend



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:240
+  // OptimizationRemark, OptimizationRemarkMissed and 
OptimizationRemarkAnalysis
+  // contain regex values which are used in optimizationRemarkHandler in
+  // FrontendActions.cpp to determine which remarks generated should be 
outputed

awarzynski wrote:
> `optimizationRemarkHandler` is a member method of `DiagnosticHandler`, that 
> you specialise in FrontendActions.cpp, right?
No, it's just a member method of BackendRemarkConsumer



Comment at: flang/lib/Frontend/TextDiagnosticPrinter.cpp:23
 #include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/ADT/SmallString.h"

awarzynski wrote:
> Is this needed?
No it's not, I've removed it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D157994: [OpenMP] Migrate dispatch related utility functions from Clang codegen to OMPIRBuilder

2023-08-16 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis updated this revision to Diff 550729.
TIFitis added a comment.

Updated test with correct function attributes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157994

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/test/OpenMP/ordered_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4337,6 +4337,66 @@
   return Builder.saveIP();
 }
 
+FunctionCallee
+OpenMPIRBuilder::createForStaticInitFunction(unsigned IVSize, bool IVSigned,
+ bool IsGPUDistribute) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name;
+  if (IsGPUDistribute)
+Name = IVSize == 32
+   ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
+   : omp::OMPRTL___kmpc_distribute_static_init_4u)
+   : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
+   : omp::OMPRTL___kmpc_distribute_static_init_8u);
+  else
+Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
+: omp::OMPRTL___kmpc_for_static_init_4u)
+: (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
+: omp::OMPRTL___kmpc_for_static_init_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchInitFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
+ : omp::OMPRTL___kmpc_dispatch_init_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
+ : omp::OMPRTL___kmpc_dispatch_init_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchNextFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
+ : omp::OMPRTL___kmpc_dispatch_next_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
+ : omp::OMPRTL___kmpc_dispatch_next_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchFiniFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
+ : omp::OMPRTL___kmpc_dispatch_fini_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
+ : omp::OMPRTL___kmpc_dispatch_fini_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
 // Copy input from pointer or i64 to the expected argument type.
 static Value *copyInput(IRBuilderBase &Builder, unsigned AddrSpace,
 Value *Input, Argument &Arg) {
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -2146,6 +2146,24 @@
  GenMapInfoCallbackTy GenMapInfoCB,
  TargetBodyGenCallbackTy BodyGenCB);
 
+  /// Returns __kmpc_for_static_init_* runtime function for the specified
+  /// size \a IVSize and sign \a IVSigned. Will create a distribute call
+  /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
+  FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned,
+ bool IsGPUDistribute);
+
+  /// Returns __kmpc_dispatch_init_* runtime function for the specified
+  /// size \a IVSize and sign \a IVSigned.
+  FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned);
+
+  /// Returns __kmpc_dispatch_next_* runtime function for the specified
+  //

[PATCH] D158056: [clang] Implement constexpr operator[] for vectors

2023-08-16 Thread Joey Rabil via Phabricator via cfe-commits
DaPorkchop_ updated this revision to Diff 550731.
DaPorkchop_ added a comment.

Fixed test code for `CodeGenCXX/temporaries.cpp`

Creating and extracting a reference to a temporary
vector's element is now able to be evaluated at compile
time, which made this test case fail (since it was looking
for code which no longer needs to be generated).


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

https://reviews.llvm.org/D158056

Files:
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/State.h
  clang/test/CodeGenCXX/temporaries.cpp
  clang/test/SemaCXX/constexpr-vectors.cpp

Index: clang/test/SemaCXX/constexpr-vectors.cpp
===
--- clang/test/SemaCXX/constexpr-vectors.cpp
+++ clang/test/SemaCXX/constexpr-vectors.cpp
@@ -1,10 +1,4 @@
-// RUN: %clang_cc1 -std=c++14 -Wno-unused-value %s -disable-llvm-passes -triple x86_64-linux-gnu -emit-llvm -o - | FileCheck %s
-
-// FIXME: Unfortunately there is no good way to validate that our values are
-// correct since Vector types don't have operator [] implemented for constexpr.
-// Instead, we need to use filecheck to ensure the emitted IR is correct. Once
-// someone implements array subscript operator for these types as constexpr,
-// this test should modified to jsut use static asserts.
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-linux-gnu -Wno-unused-value %s
 
 using FourCharsVecSize __attribute__((vector_size(4))) = char;
 using FourIntsVecSize __attribute__((vector_size(16))) = int;
@@ -50,6 +44,12 @@
 a != b;   \
 a &&b;\
 a || b;   \
+a += a[1];\
+a[1] += 1;\
+a[1] = 1; \
+a[1] = b[1];  \
+a[1]++;   \
+++a[1];   \
 auto c = (a, b);  \
 return c; \
   }
@@ -92,6 +92,15 @@
 MathShiftOpsInts(FourIntsExtVec);
 MathShiftOpsInts(FourLongLongsExtVec);
 
+template
+constexpr bool VectorsEqual(T a, U b) {
+  for (unsigned I = 0; I < 4; ++I) {
+if (a[I] != b[I])
+  return false;
+  }
+  return true;
+}
+
 template 
 constexpr auto CmpMul(T t, U u) {
   t *= u;
@@ -150,564 +159,711 @@
   return t;
 }
 
+template 
+constexpr auto UpdateElementsInPlace(T t, U u) {
+  t[0] += u[0];
+  t[1]++;
+  t[2] = 1;
+  return t;
+}
+
 // Only int vs float makes a difference here, so we only need to test 1 of each.
 // Test Char to make sure the mixed-nature of shifts around char is evident.
 void CharUsage() {
   constexpr auto a = FourCharsVecSize{6, 3, 2, 1} +
  FourCharsVecSize{12, 15, 5, 7};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(a, FourCharsVecSize{18, 18, 7, 8}), "");
+
   constexpr auto b = FourCharsVecSize{19, 15, 13, 12} -
  FourCharsVecSize{13, 14, 5, 3};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(b, FourCharsVecSize{6, 1, 8, 9}), "");
+
   constexpr auto c = FourCharsVecSize{8, 4, 2, 1} *
  FourCharsVecSize{3, 4, 5, 6};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(c, FourCharsVecSize{24, 16, 10, 6}), "");
+
   constexpr auto d = FourCharsVecSize{12, 12, 10, 10} /
  FourCharsVecSize{6, 4, 5, 2};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(d, FourCharsVecSize{2, 3, 2, 5}), "");
+
   constexpr auto e = FourCharsVecSize{12, 12, 10, 10} %
  FourCharsVecSize{6, 4, 4, 3};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(e, FourCharsVecSize{0, 0, 2, 1}), "");
 
   constexpr auto f = FourCharsVecSize{6, 3, 2, 1} + 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(f, FourCharsVecSize{9, 6, 5, 4}), "");
+
   constexpr auto g = FourCharsVecSize{19, 15, 12, 10} - 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(g, FourCharsVecSize{16, 12, 9, 7}), "");
+
   constexpr auto h = FourCharsVecSize{8, 4, 2, 1} * 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(h, FourCharsVecSize{24, 12, 6, 3}), "");
+
   constexpr auto j = FourCharsVecSize{12, 15, 18, 21} / 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(j, FourCharsVecSize{4, 5, 6, 7}), "");
+
   constexpr auto k = FourCharsVecSize{12, 17, 19, 22} % 3;
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(k, FourCharsVecSize{0, 2, 1, 1}), "");
 
   constexpr auto l = 3 + FourCharsVecSize{6, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  static_assert(VectorsEqual(l, FourCharsVecSize{9, 6, 5, 4}), "");
+
   constexpr auto m = 20 - FourCharsVecSize{19, 15, 12, 10};
-  // CHECK: store <4 x i8> 
+  static_assert(V

[PATCH] D147905: [clangd] Avoid passing -xobjective-c++-header to the system include extractor

2023-08-16 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.

Agree this is a mess: the reason we think objective-c++-header is safe is that 
we have built-in support, but in the presence of query-driver that's not enough.

In terms of testing this: I think ~nobody really cares about objc + gcc these 
days, the thing we'd expect to break by downgrading objective-c++-header to 
c++-header is querying the clang driver on a mac.
I checked that, and at least on my machine it makes no difference.

So while this is ugly and layering-violationy, it's also short and simple, and 
solves a practical problem that we've created ourselves.

(Also discussed with @kadircet offline - you're good to land this)




Comment at: clang-tools-extra/clangd/SystemIncludeExtractor.cpp:339
+// command if it contains `-xobjective-c++-header` and objective-c++ 
support
+// is not installed.
+if (Lang == "objective-c++-header") {

Maybe add comment:
```
// In practice, we don't see different include paths for the two on clang+mac,
// which is the most common objective-c compiler.
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147905

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


[PATCH] D154853: [clangd][c++20]Consider the constraint of a constrained auto in FindTarget.

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall requested changes to this revision.
sammccall added a comment.
This revision now requires changes to proceed.

(This will look different/better after D155858 
, taking it off my radar until then)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154853

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


[PATCH] D157989: [NFC] Initialize pointer field

2023-08-16 Thread Soumi Manna via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbd1ddc5850b1: [NFC][OpenMP] Initialize pointer field 
(authored by Manna).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157989

Files:
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp


Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -931,7 +931,7 @@
   (void)OutlinedFnID;
 
   // Return value of the runtime offloading call.
-  Value *Return;
+  Value *Return = nullptr;
 
   // Arguments for the target kernel.
   SmallVector ArgsVector;


Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -931,7 +931,7 @@
   (void)OutlinedFnID;
 
   // Return value of the runtime offloading call.
-  Value *Return;
+  Value *Return = nullptr;
 
   // Arguments for the target kernel.
   SmallVector ArgsVector;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread Thorsten via Phabricator via cfe-commits
tschuett added inline comments.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:227
 
+  // Specifies, using a regex, which successful optimization passes done,
+  // to include in the final optimization record file generated. If not 
provided

victorkingi wrote:
> tschuett wrote:
> > awarzynski wrote:
> > > Do you know whether that only includes middle-end, or also back-end 
> > > passes?
> > I use -Rpass-missed='gisel*'  for GlobalIsel aka backend. I am interested 
> > in doing that exercise with Flang.
> Includes both middle and backend
No. There are no middle-end passes that match that pattern.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D141177: [Clang] Don't tell people to place _Alignas on a struct in diagnostics

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

@theo-lw -- are you planning to continue working on this review? (It's okay if 
you're not, I'm more wondering if I should remove you as the assignee on 
https://github.com/llvm/llvm-project/issues/58637)


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

https://reviews.llvm.org/D141177

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


[clang-tools-extra] a94c44c - [clang-tidy] Added a new option to lambda-function-name to ignore warnings in macro expansion

2023-08-16 Thread Piotr Zegar via cfe-commits

Author: Felix
Date: 2023-08-16T15:02:56Z
New Revision: a94c44cc0a5601e977b5cc1d2cfdee1488be62e9

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

LOG: [clang-tidy] Added a new option to lambda-function-name to ignore warnings 
in macro expansion

Improved check lambda-function-name with option IgnoreMacros to ignore warnings 
in macro expansion.
Relates to #62857 (https://github.com/llvm/llvm-project/issues/62857)

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst
clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
index 2f155820a83e52..a01b7f5a4ee6e6 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
@@ -19,6 +19,8 @@ namespace clang::tidy::bugprone {
 
 namespace {
 
+static constexpr bool DefaultIgnoreMacros = false;
+
 // Keep track of macro expansions that contain both __FILE__ and __LINE__. If
 // such a macro also uses __func__ or __FUNCTION__, we don't want to issue a
 // warning because __FILE__ and __LINE__ may be useful even if __func__ or
@@ -56,6 +58,16 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks {
 
 } // namespace
 
+LambdaFunctionNameCheck::LambdaFunctionNameCheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IgnoreMacros(
+  Options.getLocalOrGlobal("IgnoreMacros", DefaultIgnoreMacros)) {}
+
+void LambdaFunctionNameCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IgnoreMacros", IgnoreMacros);
+}
+
 void LambdaFunctionNameCheck::registerMatchers(MatchFinder *Finder) {
   // Match on PredefinedExprs inside a lambda.
   Finder->addMatcher(predefinedExpr(hasAncestor(lambdaExpr())).bind("E"),
@@ -76,6 +88,9 @@ void LambdaFunctionNameCheck::check(const 
MatchFinder::MatchResult &Result) {
 return;
   }
   if (E->getLocation().isMacroID()) {
+if (IgnoreMacros)
+  return;
+
 auto ER =
 Result.SourceManager->getImmediateExpansionRange(E->getLocation());
 if (SuppressMacroExpansions.find(ER.getAsRange()) !=
@@ -84,6 +99,7 @@ void LambdaFunctionNameCheck::check(const 
MatchFinder::MatchResult &Result) {
   return;
 }
   }
+
   diag(E->getLocation(),
"inside a lambda, '%0' expands to the name of the function call "
"operator; consider capturing the name of the enclosing function "

diff  --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
index 03f1c4544aee1f..dab64f74aa6ca0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
@@ -31,8 +31,9 @@ class LambdaFunctionNameCheck : public ClangTidyCheck {
   };
   using SourceRangeSet = std::set;
 
-  LambdaFunctionNameCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  LambdaFunctionNameCheck(StringRef Name, ClangTidyContext *Context);
+
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
@@ -40,6 +41,7 @@ class LambdaFunctionNameCheck : public ClangTidyCheck {
 
 private:
   SourceRangeSet SuppressMacroExpansions;
+  bool IgnoreMacros;
 };
 
 } // namespace clang::tidy::bugprone

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index dffc838053f08d..a80473f09464fe 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -173,6 +173,10 @@ Changes in existing checks
   `, so that it does not warn
   on macros starting with underscore and lowercase letter.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by adding option
+  `IgnoreMacros` to ignore warnings in macros.
+
 - Improved :doc:`cppcoreguidelines-avoid-non-const-global-variables
   ` check
   to ignore ``static`` variables declared within the scope of

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst 

[PATCH] D157829: [clang-tidy] Added a new option to lambda-function-name to ignore warnings in macro expansion

2023-08-16 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa94c44cc0a56: [clang-tidy] Added a new option to 
lambda-function-name to ignore warnings in… (authored by felix642, committed by 
PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157829

Files:
  clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/lambda-function-name.cpp
@@ -1,4 +1,6 @@
-// RUN: %check_clang_tidy %s bugprone-lambda-function-name %t
+// RUN: %check_clang_tidy -check-suffixes=,NO-CONFIG %s bugprone-lambda-function-name %t
+// RUN: %check_clang_tidy %s bugprone-lambda-function-name %t -- -config="{CheckOptions: [{key: bugprone-lambda-function-name.IgnoreMacros, value: true}]}" --
+
 
 void Foo(const char* a, const char* b, int c) {}
 
@@ -12,11 +14,11 @@
   [] { __FUNCTION__; }();
   // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: inside a lambda, '__FUNCTION__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
   [] { FUNC_MACRO; }();
-  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
+  // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
   [] { FUNCTION_MACRO; }();
-  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: inside a lambda, '__FUNCTION__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
+  // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, '__FUNCTION__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
   [] { EMBED_IN_ANOTHER_MACRO1; }();
-  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
+  // CHECK-MESSAGES-NO-CONFIG: :[[@LINE-1]]:8: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
 }
 
 #define FUNC_MACRO_WITH_FILE_AND_LINE Foo(__func__, __FILE__, __LINE__)
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/lambda-function-name.rst
@@ -25,3 +25,11 @@
 
   Called from FancyFunction
   Now called from FancyFunction
+
+Options
+---
+
+.. option::  IgnoreMacros
+
+  The value `true` specifies that attempting to get the name of a function from
+  within a macro should not be diagnosed. The default value is `false`.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -173,6 +173,10 @@
   `, so that it does not warn
   on macros starting with underscore and lowercase letter.
 
+- Improved :doc:`bugprone-lambda-function-name
+  ` check by adding option
+  `IgnoreMacros` to ignore warnings in macros.
+
 - Improved :doc:`cppcoreguidelines-avoid-non-const-global-variables
   ` check
   to ignore ``static`` variables declared within the scope of
Index: clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.h
@@ -31,8 +31,9 @@
   };
   using SourceRangeSet = std::set;
 
-  LambdaFunctionNameCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  LambdaFunctionNameCheck(StringRef Name, ClangTidyContext *Context);
+
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) over

[PATCH] D155833: [Clang][Sema][RFC] Add Sema support for C++ Parallel Algorithm Offload

2023-08-16 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


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

https://reviews.llvm.org/D155833

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


[PATCH] D158093: [Sema] Clean up ActionResult type a little. NFCI

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: kadircet, aaron.ballman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Document the valid states: invalid/unset/pointer (Currently both 
documentation and implementation strongly suggest that pointer+invalid is 
poissible, when it's not)
- Remove unused set() functions, which had different semantics between the 
compressed/uncompressed specialization! (The former allowing escaping the 
tristate into pointer+invalid)
- Make the compressed specialization's internals directly model the tristate, 
rather than pretending pointer + invalid were independent.
- Make members of each version identical where possible, remove repetition
- fix operator= accidentally returning a const reference
- Fix indentation :-)

This was motivated by D157868 , in which an 
experienced clang dev was
confused about the possible states for ExprResult - and I vividly
remember getting very confused about this myself.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158093

Files:
  clang/include/clang/Sema/Ownership.h

Index: clang/include/clang/Sema/Ownership.h
===
--- clang/include/clang/Sema/Ownership.h
+++ clang/include/clang/Sema/Ownership.h
@@ -132,7 +132,6 @@
 
 namespace clang {
 
-  // Basic
 class StreamingDiagnostic;
 
 // Determines whether the low bit of the result pointer for the
@@ -140,164 +139,147 @@
 // for it's "invalid" flag.
 template  struct IsResultPtrLowBitFree {
   static const bool value = false;
-  };
-
-  /// ActionResult - This structure is used while parsing/acting on
-  /// expressions, stmts, etc.  It encapsulates both the object returned by
-  /// the action, plus a sense of whether or not it is valid.
-  /// When CompressInvalid is true, the "invalid" flag will be
-  /// stored in the low bit of the Val pointer.
-  template::value>
-  class ActionResult {
-PtrTy Val;
-bool Invalid;
-
-  public:
-ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {}
-ActionResult(PtrTy val) : Val(val), Invalid(false) {}
-ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
-
-// These two overloads prevent void* -> bool conversions.
-ActionResult(const void *) = delete;
-ActionResult(volatile void *) = delete;
-
-bool isInvalid() const { return Invalid; }
-bool isUsable() const { return !Invalid && Val; }
-bool isUnset() const { return !Invalid && !Val; }
-
-PtrTy get() const { return Val; }
-template  T *getAs() { return static_cast(get()); }
-
-void set(PtrTy V) { Val = V; }
-
-const ActionResult &operator=(PtrTy RHS) {
-  Val = RHS;
-  Invalid = false;
-  return *this;
-}
-  };
-
-  // This ActionResult partial specialization places the "invalid"
-  // flag into the low bit of the pointer.
-  template
-  class ActionResult {
-// A pointer whose low bit is 1 if this result is invalid, 0
-// otherwise.
-uintptr_t PtrWithInvalid;
-
-using PtrTraits = llvm::PointerLikeTypeTraits;
-
-  public:
-ActionResult(bool Invalid = false)
-: PtrWithInvalid(static_cast(Invalid)) {}
-
-ActionResult(PtrTy V) {
-  void *VP = PtrTraits::getAsVoidPointer(V);
-  PtrWithInvalid = reinterpret_cast(VP);
-  assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
-}
-
-ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) {}
-
-// These two overloads prevent void* -> bool conversions.
-ActionResult(const void *) = delete;
-ActionResult(volatile void *) = delete;
-
-bool isInvalid() const { return PtrWithInvalid & 0x01; }
-bool isUsable() const { return PtrWithInvalid > 0x01; }
-bool isUnset() const { return PtrWithInvalid == 0; }
-
-PtrTy get() const {
-  void *VP = reinterpret_cast(PtrWithInvalid & ~0x01);
-  return PtrTraits::getFromVoidPointer(VP);
-}
-
-template  T *getAs() { return static_cast(get()); }
-
-void set(PtrTy V) {
-  void *VP = PtrTraits::getAsVoidPointer(V);
-  PtrWithInvalid = reinterpret_cast(VP);
-  assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
-}
-
-const ActionResult &operator=(PtrTy RHS) {
-  void *VP = PtrTraits::getAsVoidPointer(RHS);
-  PtrWithInvalid = reinterpret_cast(VP);
-  assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
-  return *this;
-}
-
-// For types where we can fit a flag in with the pointer, provide
-// conversions to/from pointer type.
-static ActionResult getFromOpaquePointer(void *P) {
-  ActionResult Result;
-  Result.PtrWithInvalid = (uintptr_t)P;
-  return Result;
-}
-void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
-  };
+};
+
+/// The result of parsing/analyzing an expressio

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi added inline comments.



Comment at: flang/test/Driver/optimization-remark.f90:7
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-NO-REMARKS
+

awarzynski wrote:
> How about something like this:
> ```
> ! RUN: %flang_fc1 %s -O1 -Runsupported_remark_opt -Rpass -emit-llvm -o - 2>&1 
> | FileCheck %s
> ```
We are testing here if `-Rno-pass`  is provided after `-Rpass`, nothing should 
be printed.

Unsupported value is tested at 

> ! Check "unknown remark option" warning with suggestion
> ! RUN: %flang %s -O1 -Rpas 2>&1 | FileCheck %s 
> --check-prefix=CHECK-WARN-SUGGEST



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[clang] 5d9ccd7 - [OpenMP] Migrate dispatch related utility functions from Clang codegen to OMPIRBuilder

2023-08-16 Thread Akash Banerjee via cfe-commits

Author: Akash Banerjee
Date: 2023-08-16T16:35:28+01:00
New Revision: 5d9ccd7a96930351519ccbe5f85b127faa0dda9a

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

LOG: [OpenMP] Migrate dispatch related utility functions from Clang codegen to 
OMPIRBuilder

Migrate createForStaticInitFunction, createDispatchInitFunction, 
createDispatchNextFunction and createDispatchFiniFunction from Clang CodeGen to 
OMPIRBuilder.

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/test/OpenMP/ordered_codegen.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index fad8faad68c479..d35788ec38c2c7 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1502,103 +1502,6 @@ llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
   return llvm::PointerType::getUnqual(Kmpc_MicroTy);
 }
 
-llvm::FunctionCallee
-CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned,
- bool IsGPUDistribute) {
-  assert((IVSize == 32 || IVSize == 64) &&
- "IV size is not compatible with the omp runtime");
-  StringRef Name;
-  if (IsGPUDistribute)
-Name = IVSize == 32 ? (IVSigned ? "__kmpc_distribute_static_init_4"
-: "__kmpc_distribute_static_init_4u")
-: (IVSigned ? "__kmpc_distribute_static_init_8"
-: "__kmpc_distribute_static_init_8u");
-  else
-Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
-: "__kmpc_for_static_init_4u")
-: (IVSigned ? "__kmpc_for_static_init_8"
-: "__kmpc_for_static_init_8u");
-
-  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
-  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
-  llvm::Type *TypeParams[] = {
-getIdentTyPointerTy(), // loc
-CGM.Int32Ty,   // tid
-CGM.Int32Ty,   // schedtype
-llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
-PtrTy, // p_lower
-PtrTy, // p_upper
-PtrTy, // p_stride
-ITy,   // incr
-ITy// chunk
-  };
-  auto *FnTy =
-  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
-  return CGM.CreateRuntimeFunction(FnTy, Name);
-}
-
-llvm::FunctionCallee
-CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
-  assert((IVSize == 32 || IVSize == 64) &&
- "IV size is not compatible with the omp runtime");
-  StringRef Name =
-  IVSize == 32
-  ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
-  : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
-  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
-  llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
-   CGM.Int32Ty,   // tid
-   CGM.Int32Ty,   // schedtype
-   ITy,   // lower
-   ITy,   // upper
-   ITy,   // stride
-   ITy// chunk
-  };
-  auto *FnTy =
-  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
-  return CGM.CreateRuntimeFunction(FnTy, Name);
-}
-
-llvm::FunctionCallee
-CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
-  assert((IVSize == 32 || IVSize == 64) &&
- "IV size is not compatible with the omp runtime");
-  StringRef Name =
-  IVSize == 32
-  ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
-  : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
-  llvm::Type *TypeParams[] = {
-  getIdentTyPointerTy(), // loc
-  CGM.Int32Ty,   // tid
-  };
-  auto *FnTy =
-  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
-  return CGM.CreateRuntimeFunction(FnTy, Name);
-}
-
-llvm::FunctionCallee
-CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
-  assert((IVSize == 32 || IVSize == 64) &&
- "IV size is not compatible with the omp runtime");
-  StringRef Name =

[PATCH] D157994: [OpenMP] Migrate dispatch related utility functions from Clang codegen to OMPIRBuilder

2023-08-16 Thread Akash Banerjee via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5d9ccd7a9693: [OpenMP] Migrate dispatch related utility 
functions from Clang codegen to… (authored by TIFitis).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157994

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/test/OpenMP/ordered_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4337,6 +4337,66 @@
   return Builder.saveIP();
 }
 
+FunctionCallee
+OpenMPIRBuilder::createForStaticInitFunction(unsigned IVSize, bool IVSigned,
+ bool IsGPUDistribute) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name;
+  if (IsGPUDistribute)
+Name = IVSize == 32
+   ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
+   : omp::OMPRTL___kmpc_distribute_static_init_4u)
+   : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
+   : omp::OMPRTL___kmpc_distribute_static_init_8u);
+  else
+Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
+: omp::OMPRTL___kmpc_for_static_init_4u)
+: (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
+: omp::OMPRTL___kmpc_for_static_init_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchInitFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
+ : omp::OMPRTL___kmpc_dispatch_init_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
+ : omp::OMPRTL___kmpc_dispatch_init_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchNextFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
+ : omp::OMPRTL___kmpc_dispatch_next_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
+ : omp::OMPRTL___kmpc_dispatch_next_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
+FunctionCallee OpenMPIRBuilder::createDispatchFiniFunction(unsigned IVSize,
+   bool IVSigned) {
+  assert((IVSize == 32 || IVSize == 64) &&
+ "IV size is not compatible with the omp runtime");
+  RuntimeFunction Name = IVSize == 32
+ ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
+ : omp::OMPRTL___kmpc_dispatch_fini_4u)
+ : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
+ : omp::OMPRTL___kmpc_dispatch_fini_8u);
+
+  return getOrCreateRuntimeFunction(M, Name);
+}
+
 // Copy input from pointer or i64 to the expected argument type.
 static Value *copyInput(IRBuilderBase &Builder, unsigned AddrSpace,
 Value *Input, Argument &Arg) {
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -2146,6 +2146,24 @@
  GenMapInfoCallbackTy GenMapInfoCB,
  TargetBodyGenCallbackTy BodyGenCB);
 
+  /// Returns __kmpc_for_static_init_* runtime function for the specified
+  /// size \a IVSize and sign \a IVSigned. Will create a distribute call
+  /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
+  FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned,
+ bool IsGPUDistribute);
+
+  /// Returns __kmpc_dispatch_init_* runtime function for the specified
+  /// size \a IVSize and sign \a IVSigned.
+  FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSig

[PATCH] D153152: Adds tweak to add declarations for pure virtuals

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks for working on this!

FWIW I had an old draft of this feature that may have interesting ideas: 
https://reviews.llvm.org/D122827




Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:44
+for (const auto &WhatIsThis :
+ Overrider.second) { // TODO: why is there a second level
+  return !WhatIsThis.Method->isPure();

see the long comment on CXXFinalOverriderMap 
TL;DR: a derived class can inherit multiple times from the same base, each such 
subobject could potentially have a separate override



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:58
+
+  const llvm::ArrayRef Tokens =
+  TokBuf.expandedTokens(MethodDeclRange);

copying the tokens directly seems brittle, for example we shouldn't be emitting 
"virtual" but its's hard to avoid doing so.
(Also, surprising that getEndLoc() doesn't cover the `= 0`!)

D122827 has a reprint() function that seems to work



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:75
+// same as or derived from Start.
+std::string collectPureVirtualFuncOverrideDecls(
+const CXXRecordDecl &Target, const CXXRecordDecl &Start,

this probably needs to be restructured somewhat as need to enumerate these in 
prepare() to be sure there are any, but don't want to pay to produce the strings



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:86
+  CXXFinalOverriderMap FinalOverriderMapOfTarget;
+  // If &Target == &Start then Target doesn't already have any
+  // overrides for functions that are pure in Start. The map remains empty,

FWIW, I'm not actually sure that the case of multiple bases classes each 
providing pure-virtual-methods of which you want to override only one set is 
common enough to be worth this extra complexity.





Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:139
+///   class Base{ virtual void foo() = 0; };
+///   class Derived {};
+///

please use `^^` markers underneath the characters where you expect the tweak to 
trigger



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:143
+///   class Base{ virtual void foo() = 0; };
+///   class Derived { virtual void foo() override; };
+class DeclarePureVirtuals : public Tweak {

no "virtual"



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:149
+  std::string title() const override {
+return "Override pure virtual functions";
+  }

what do you think about listing the functions we'll define?

Especially in the case where there's only one.



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:153
+  llvm::StringLiteral kind() const override {
+return CodeAction::QUICKFIX_KIND;
+  }

I don't think this is a quick-fix, which should address a diagnostic or so.

Really there doesn't seem to be a standard kind that fits here. Maybe we should 
add a new constant "generate"?



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:156
+
+  bool prepare(const Selection &Sel) override {
+const SelectionTree::Node *const CommonAncestor =

it's important that we only offer the code action (i.e. prepare returns true) 
if there are actually methods to override.

This means actually enumerating the functions needs to happen in prepare rather 
than apply. (Which means it needs to be fast...)



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:163
+// maybe selected a class, in which case override functions of all bases
+SelectedDerivedClass = CommonAncestor->ASTNode.get();
+if (SelectedDerivedClass) {

this should only trigger on the class definition, not forward declarations



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:170
+// bases's functions
+const DeclContext &DC = CommonAncestor->getDeclContext();
+SelectedDerivedClass = dyn_cast(&DC);

this seems confusing: if you're going to walk up looking for a 
CXXBaseSpecifier, why not just do that in the first place?



Comment at: clang-tools-extra/clangd/refactor/tweaks/DeclarePureVirtuals.cpp:196
+  if (!Start) {
+return llvm::createStringError(
+llvm::inconvertibleErrorCode(),

this doesn't seem like a condition we should be surfacing to the user.
How do we get here? if it's e.g. because the base is dependent, then we should 
be returning false from prepare() in the appropriate dependent-code cases.



Comment at: clang-tools-extra/clangd/refactor/tweaks/Declar

[PATCH] D157497: feat: Migrate isArch16Bit

2023-08-16 Thread Evgeniy Makarev via Phabricator via cfe-commits
Pivnoy added a comment.

At the moment, the TargetParser architecture is extensible. This complicates 
the addition of new architectures, operating systems, and so on.
In the main discussion, it was proposed to redesign the architecture of this 
module in order to increase the possibility of adding new architectures, etc.
The main idea of   the rework was to separate the Triple entity into a 
data-class, and create a number of interfaces from components that would 
include Triple, through the implementation of which it would be possible to 
represent various data bindings of the components. At the moment, Triple is 
overflowing with various methods that do not fully meet the ideas of OOP.
Since the TargetParser module is quite large and has many dependencies 
throughout the llvm-project, it was first of all supposed to remove these 
methods from Triple, since they would not correspond to OOP ideas.
This would help to gradually rid Triple of unnecessary dependencies, and 
gradually change the architecture inside Triple, without breaking code of 
another LLVM developers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157497

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


[PATCH] D158045: [clang][SVE] Rename isVLSTBuiltinType, NFC

2023-08-16 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm accepted this revision.
paulwalker-arm added a comment.
This revision is now accepted and ready to land.

I'd hope there are common code paths where `isVLSTBuiltinType` would still be 
useful but I guess this step is required to make that happen anyway.

If you permit a minor request can the new name please be `isSveVLSBuiltinType` 
to match the case used by the related `getSveEltType` function and the extra 
`T` in the old name has always bugged me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158045

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


[PATCH] D151315: [clangd] Add a switch to specify a default clangd configuration file

2023-08-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Sorry about the delay, I think this is OK to add.




Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:500
+"User config is from clangd/config.yaml in the following directories 
\n"
+"(unless specified with --default-config):\n"
 "\tWindows: %USERPROFILE%\\AppData\\Local\n"

why this change? user config is still loaded from those directories

Maybe after the user config text, add "Extra config may be specified by 
--extra-config-file"



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:509
+opt DefaultConfig{
+"default-config",
+cat(Misc),

"default" doesn't seem like the right term for this, as it's clearly not the 
default - the user is providing it!

Also, there's also been desire to provide config inline in a flag (as opposed 
to a file) as this is more self-contained. Calling this config when it's 
actually a config filename is a bit confusing.

maybe `--extra-config-file`?



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:512
+desc("Path to a default clangd configuration file. A clangd user and "
+ "project configuration has a higher priority (requires "
+ "--enable-config) "),

I think mentioning --enable-config is more confusing than helpful, since it's 
on by default.



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:959
+  llvm::SmallString<256> DefaultConfigPath;
+  if (auto Error = llvm::sys::fs::real_path(
+  DefaultConfig, DefaultConfigPath, /*expand_tilde=*/true)) {

none of this path checking/resolution should be necessary, the fromYAMLFile 
provider already handles the case where the path does not exist.

We don't expand tildes in paths clangd (or clang, generally) processes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151315

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


[PATCH] D141177: [Clang] Don't tell people to place _Alignas on a struct in diagnostics

2023-08-16 Thread Theodore Luo Wang via Phabricator via cfe-commits
theo-lw added a comment.

In D141177#4592158 , @aaron.ballman 
wrote:

> @theo-lw -- are you planning to continue working on this review? (It's okay 
> if you're not, I'm more wondering if I should remove you as the assignee on 
> https://github.com/llvm/llvm-project/issues/58637)

Hey! Sorry, got busy with school. I can continue working on this.


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

https://reviews.llvm.org/D141177

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


[PATCH] D141177: [Clang] Don't tell people to place _Alignas on a struct in diagnostics

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D141177#4592361 , @theo-lw wrote:

> In D141177#4592158 , @aaron.ballman 
> wrote:
>
>> @theo-lw -- are you planning to continue working on this review? (It's okay 
>> if you're not, I'm more wondering if I should remove you as the assignee on 
>> https://github.com/llvm/llvm-project/issues/58637)
>
> Hey! Sorry, got busy with school. I can continue working on this.

No worries, it happens! Thank you for continuing work on this -- if you find 
you don't have the time, it's not a big deal, just let us know. :-)


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

https://reviews.llvm.org/D141177

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


[PATCH] D158093: [Sema] Clean up ActionResult type a little. NFCI

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

thanks a lot for doing this, i think this makes it a lot more obvious that this 
is a tristate struct rather than invalid just being a bit that can bit set for 
both null and non-null pointers.




Comment at: clang/include/clang/Sema/Ownership.h:155
+  PtrTy Val = {};
+  bool Invalid;
+

nit: also initialize Invalid to false?



Comment at: clang/include/clang/Sema/Ownership.h:204
+  PtrTy get() const {
+void *VP = reinterpret_cast(Value & ~0x01);
+return PtrTraits::getFromVoidPointer(VP);

nit: `Value == InvalidValue ? nullptr : Value` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158093

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


[PATCH] D157076: [clang][ExtractAPI] Add support for C++ class templates and concepts

2023-08-16 Thread Daniel Grumberg via Phabricator via cfe-commits
dang added a comment.

Looks mostly good. Quick Question how do we handle inheritance to a template 
parameter?




Comment at: clang/include/clang/ExtractAPI/API.h:665
+
+struct ClassTemplateSpecRecord : CXXClassRecord {
+  ClassTemplateSpecRecord(StringRef USR, StringRef Name, PresumedLoc Loc,

Minor nit, I would prefer for Specialization to be fully spelled out.



Comment at: clang/include/clang/ExtractAPI/DeclarationFragments.h:191
 
+class Template {
+  struct TemplateParameter {

This is really a model type and should live either in it's own file or in API.h



Comment at: clang/include/clang/ExtractAPI/DeclarationFragments.h:313
+  /// Get template details from a template function, class, or variable
+  static Template getTemplate(const TemplateDecl *Decl) {
+Template Template;

I feel this should be a constructor for Template seeing that this never fails.



Comment at: clang/include/clang/ExtractAPI/ExtractAPIVisitor.h:435
+Decl->getDescribedClassTemplate()));
+// Cast to easily use previous declaration to get bases.
+CXXClassRecord = API.addClassTemplate(

Where is the cast?



Comment at: clang/lib/ExtractAPI/DeclarationFragments.cpp:754
+  Fragments.append(TemplateParam->getTypeConstraint()
+   ->getNamedConcept()
+   ->getName()

is this clang-format formatted?



Comment at: clang/lib/ExtractAPI/DeclarationFragments.cpp:784
+dyn_cast(TemplateParameters[i]);
+if (TypeParameter.compare("type-parameter-" +
+  std::to_string(Parameter->getDepth()) + "-" +

Kinda sad we have to do this. I guess there is no easy way to change the AST to 
support this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157076

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


[PATCH] D158093: [Sema] Clean up ActionResult type a little. NFCI

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

Thank you for this! LGTM aside from a tiny nit.




Comment at: clang/include/clang/Sema/Ownership.h:147
+/// It may be:
+/// - a valid pointer to the result object
+/// - unset (null but valid), for constructs that may legitimately be absent

It might be worth tying this to `usable`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158093

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


[PATCH] D157905: [include-cleaner] Filter references to identity macros

2023-08-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked 2 inline comments as done.
kadircet added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:43
+  // This results in surprising behavior from users point of view (we
+  // generate a usage of stdio.h, in places unrelated to standard library).
+  // FIXME: Also eliminate the false positives by treating declarations

sammccall wrote:
> kadircet wrote:
> > sammccall wrote:
> > > Comment nit: I'm having trouble imagining cases that are 
> > > actually*unrelated* to the stdlib.
> > > 
> > > If `stderr` is an impl-defined macro, then the only way to use the name 
> > > to refer to something else is if it's not defined (inside ifndef stderr, 
> > > or if you can be sure your TU doesn't include stdio first). Seems 
> > > implausible...
> > > 
> > > That said I feel like we've had this conversation before and I've just 
> > > forgotten the details.
> > > If stderr is an impl-defined macro, then the only way to use the name to 
> > > refer to something else is if it's not defined
> > 
> > That's absolutely right. The issue here is macro expansion triggers 
> > independent of the context, e.g.
> > ```
> > #include 
> > namespace ns { void stderr(); }
> > void foo() { ns::stderr(); }
> > ```
> > 
> > here we have a (well two) reference to `stderr` macro from stdandard 
> > library, which is not user's intent, but rather a quirk of the language.
> Sure, but this code is not valid C++ (since `stderr` is not guaranteed to 
> expand to a single identifier). Is this actually a common/motivating case?
> Sure, but this code is not valid C++ (since stderr is not guaranteed to 
> expand to a single identifier).

That's true. Most of the standard library implementations I checked does that, 
but I also don't like that reliance, so making it a little bit more generic 
(which meant some more plumbing, sorry for the big diff :( ), by making sure 
that we apply this to all the macros that expand to themselves.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157905

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


[PATCH] D157905: [include-cleaner] Filter references to identity macros

2023-08-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 550790.
kadircet added a comment.
Herald added subscribers: PiotrZSL, carlosgalvezp, arphaman.
Herald added a reviewer: njames93.

- Apply filtering only to macros that expand to themselves


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157905

Files:
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -66,8 +66,9 @@
   }
 
   std::multimap>
-  offsetToProviders(TestAST &AST, SourceManager &SM,
+  offsetToProviders(TestAST &AST,
 llvm::ArrayRef MacroRefs = {}) {
+const auto &SM = AST.sourceManager();
 llvm::SmallVector TopLevelDecls;
 for (Decl *D : AST.context().getTranslationUnitDecl()->decls()) {
   if (!SM.isWrittenInMainFile(SM.getExpansionLoc(D->getLocation(
@@ -75,7 +76,7 @@
   TopLevelDecls.emplace_back(D);
 }
 std::multimap> OffsetToProviders;
-walkUsed(TopLevelDecls, MacroRefs, &PI, SM,
+walkUsed(TopLevelDecls, MacroRefs, &PI, AST.preprocessor(),
  [&](const SymbolReference &Ref, llvm::ArrayRef Providers) {
auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
if (FID != SM.getMainFileID())
@@ -118,7 +119,7 @@
   auto VectorSTL = Header(*tooling::stdlib::Header::named(""));
   auto UtilitySTL = Header(*tooling::stdlib::Header::named(""));
   EXPECT_THAT(
-  offsetToProviders(AST, SM),
+  offsetToProviders(AST),
   UnorderedElementsAre(
   Pair(Code.point("bar"), UnorderedElementsAre(MainFile)),
   Pair(Code.point("private"),
@@ -155,7 +156,7 @@
   auto HeaderFile2 = Header(AST.fileManager().getFile("header2.h").get());
   auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
   EXPECT_THAT(
-  offsetToProviders(AST, SM),
+  offsetToProviders(AST),
   Contains(Pair(Code.point("foo"),
 UnorderedElementsAre(HeaderFile1, HeaderFile2, MainFile;
 }
@@ -171,19 +172,19 @@
   Inputs.ExtraFiles["hdr.h"] = Hdr.code();
   TestAST AST(Inputs);
   auto &SM = AST.sourceManager();
+  auto &PP = AST.preprocessor();
   const auto *HdrFile = SM.getFileManager().getFile("hdr.h").get();
   auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
 
   auto HdrID = SM.translateFile(HdrFile);
 
-  IdentifierTable Idents;
-  Symbol Answer1 =
-  Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
-  Symbol Answer2 =
-  Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
+  Symbol Answer1 = Macro{PP.getIdentifierInfo("ANSWER"),
+ SM.getComposedLoc(HdrID, Hdr.point())};
+  Symbol Answer2 = Macro{PP.getIdentifierInfo("ANSWER"),
+ SM.getComposedLoc(HdrID, Hdr.point())};
   EXPECT_THAT(
   offsetToProviders(
-  AST, SM,
+  AST,
   {SymbolReference{
Answer1, SM.getComposedLoc(SM.getMainFileID(), Code.point("1")),
RefType::Explicit},
@@ -240,8 +241,7 @@
   auto Decls = AST.context().getTranslationUnitDecl()->decls();
   auto Results =
   analyze(std::vector{Decls.begin(), Decls.end()},
-  PP.MacroReferences, PP.Includes, &PI, AST.sourceManager(),
-  AST.preprocessor().getHeaderSearchInfo());
+  PP.MacroReferences, PP.Includes, &PI, AST.preprocessor());
 
   const Include *B = PP.Includes.atLine(3);
   ASSERT_EQ(B->Spelled, "b.h");
@@ -257,8 +257,7 @@
   Inputs.FileName = "public.h";
   TestAST AST(Inputs);
   EXPECT_FALSE(PP.Includes.all().empty());
-  auto Results = analyze({}, {}, PP.Includes, &PI, AST.sourceManager(),
- AST.preprocessor().getHeaderSearchInfo());
+  auto Results = analyze({}, {}, PP.Includes, &PI, AST.preprocessor());
   EXPECT_THAT(Results.Unused, testing::IsEmpty());
 }
 
@@ -268,8 +267,7 @@
   Inputs.ErrorOK = true;
   TestAST AST(Inputs);
   EXPECT_FALSE(PP.Includes.all().empty());
-  auto Results = analyze({}, {}, PP.Includes, &PI, AST.sourceManager(),
- AST.preprocessor().getHeaderSearchInfo());
+  auto Results = analyze({}, {}, PP.Includes, &PI, AST.preprocessor());
   EXPECT_THAT(Results.Unused, testing::IsEmpty());
 }
 
@@ -409,7 +407,7 @@
 
 SourceLocati

[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-08-16 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

friendly ping~


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

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


[PATCH] D129061: [Lex] Diagnose macro in command lines

2023-08-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

This review went cold for about a year now (sorry for not noticing we hadn't 
answered your question!), so I'm uncertain if @jackhong12 is still interested 
in pursuing this. If not, that's totally fine, just let us know so we can 
remove you as the assignee on the issue 
(https://github.com/llvm/llvm-project/issues/56159).




Comment at: clang/include/clang/Driver/Options.td:664
 HelpText<"Define  to  (or 1 if  omitted)">;
+def DriverDefine : JoinedOrSeparate<["-"], "driver-define">, 
Group,
+Flags<[CC1Option, FlangOption, FC1Option]>, MetaVarName<"=">,

jackhong12 wrote:
> MaskRay wrote:
> > Make this CC1 only  option `NoDriverOption` by moving it somewhere under 
> > `let Flags = [CC1Option, NoDriverOption] in {`
> > 
> > Don't add new `Separate` or `JoinedOrSeparate` options. They are legacy.
> I tried to add `=` behind `driver-define`. But I got the following error 
> messages when I ran `ninja check-all`.
> ```
> [416/433] cd /home/zhenhong/ssd/zhenhong/llvm-project/clang/bindings/python 
> && /usr/bin/cmake -E env 
> CLANG_LIBRARY_PATH=/home/zhenhong/ssd/zhenhong/llvm-project/release/lib 
> /usr/bin/python3.8 -m unittest discover  
> FAILED: tools/clang/bindings/python/tests/CMakeFiles/check-clang-python   
>   
>   
> 
> cd /home/zhenhong/ssd/zhenhong/llvm-project/clang/bindings/python && 
> /usr/bin/cmake -E env 
> CLANG_LIBRARY_PATH=/home/zhenhong/ssd/zhenhong/llvm-project/release/lib 
> /usr/bin/python3.8 -m unittest discover
> E..EE...EE.E....EE
>   
>   
> ==
>   
>   
> 
> ERROR: test_access_specifiers 
> (tests.cindex.test_access_specifiers.TestAccessSpecifiers)
>   
> 
> Ensure that C++ access specifiers are available on cursors
>   
>   
> 
> --
>   
>   
> 
> Traceback (most recent call last):
>   
>   
> 
>   File 
> "/home/zhenhong/ssd/zhenhong/llvm-project/clang/bindings/python/tests/cindex/test_access_specifiers.py",
>  line 20, in test_access_specifiers   
>  
> tu = get_tu("""   
>   
>   
> 
>   File 
> "/home/zhenhong/ssd/zhenhong/llvm-project/clang/bindings/python/tests/cindex/util.py",
>  line 40, in get_tu   
>
> return TranslationUnit.from_source(name, args, unsaved_files=[(name,  
>   
>   
> 
>   File 
> "/home/zhenhong/ssd/zhenhong/llvm-project/clang/bindings/python/clang/cindex.py",
>  line 2837, in from_source
> 
> raise TranslationUnitLoadError("Error parsing translation unit.") 
>   
>   
> 
> clang.cindex.TranslationUnitLoadError: Error parsing translation unit.
> 
> ...
> ```
> 
> I don't know what triggers the crash.
I've never seen output like that before -- were you able to resolve this crash? 
@MaskRay do you have ideas?


CHANGE

[PATCH] D142660: [AIX] supporting -X options for llvm-ranlib in AIX OS

2023-08-16 Thread Digger Lin via Phabricator via cfe-commits
DiggerLin updated this revision to Diff 550776.
DiggerLin marked 3 inline comments as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142660

Files:
  clang/lib/Driver/OffloadBundler.cpp
  clang/test/lit.cfg.py
  clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
  llvm/include/llvm/Object/Archive.h
  llvm/include/llvm/Object/ArchiveWriter.h
  llvm/lib/ObjCopy/Archive.cpp
  llvm/lib/ObjCopy/MachO/MachOObjcopy.cpp
  llvm/lib/Object/Archive.cpp
  llvm/lib/Object/ArchiveWriter.cpp
  llvm/lib/Object/COFFImportFile.cpp
  llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp
  llvm/test/tools/llvm-ranlib/AIX-X-option-non-AIX.test
  llvm/test/tools/llvm-ranlib/aix-X-option.test
  llvm/tools/llvm-ar/llvm-ar.cpp
  llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp

Index: llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp
===
--- llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp
+++ llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp
@@ -594,18 +594,17 @@
 
   if (NewMembers.size() == 1)
 return writeArchive(OutputFile, NewMembers.begin()->second.getMembers(),
-/*WriteSymtab=*/true,
+SymtabWritingMode::NormalSymtab,
 /*Kind=*/object::Archive::K_DARWIN, C.Deterministic,
 /*Thin=*/false);
 
   SmallVector, 2> OutputBinaries;
   for (const std::pair &M : NewMembers) {
 Expected> OutputBufferOrErr =
-writeArchiveToBuffer(M.second.getMembers(),
- /*WriteSymtab=*/true,
- /*Kind=*/object::Archive::K_DARWIN,
- C.Deterministic,
- /*Thin=*/false);
+writeArchiveToBuffer(
+M.second.getMembers(), SymtabWritingMode::NormalSymtab,
+/*Kind=*/object::Archive::K_DARWIN, C.Deterministic,
+/*Thin=*/false);
 if (!OutputBufferOrErr)
   return OutputBufferOrErr.takeError();
 std::unique_ptr &OutputBuffer = OutputBufferOrErr.get();
Index: llvm/tools/llvm-ar/llvm-ar.cpp
===
--- llvm/tools/llvm-ar/llvm-ar.cpp
+++ llvm/tools/llvm-ar/llvm-ar.cpp
@@ -69,7 +69,9 @@
  << "  -v --version  - Display the version of this program\n"
  << "  -D- Use zero for timestamps and uids/gids "
 "(default)\n"
- << "  -U- Use actual timestamps and uids/gids\n";
+ << "  -U- Use actual timestamps and uids/gids\n"
+ << "  -X{32|64|32_64|any}   - Specify which archive symbol tables "
+"should be generated if they do not already exist (AIX OS only)\n";
 }
 
 static void printArHelp(StringRef ToolName) {
@@ -225,7 +227,8 @@
 static bool CompareFullPath = false;  ///< 'P' modifier
 static bool OnlyUpdate = false;   ///< 'u' modifier
 static bool Verbose = false;  ///< 'v' modifier
-static bool Symtab = true;///< 's' modifier
+static SymtabWritingMode Symtab =
+SymtabWritingMode::NormalSymtab;  ///< 's' modifier
 static bool Deterministic = true; ///< 'D' and 'U' modifiers
 static bool Thin = false; ///< 'T' modifier
 static bool AddLibrary = false;   ///< 'L' modifier
@@ -371,11 +374,11 @@
   CompareFullPath = true;
   break;
 case 's':
-  Symtab = true;
+  Symtab = SymtabWritingMode::NormalSymtab;
   MaybeJustCreateSymTab = true;
   break;
 case 'S':
-  Symtab = false;
+  Symtab = SymtabWritingMode::NoSymtab;
   break;
 case 'u':
   OnlyUpdate = true;
@@ -1074,9 +1077,31 @@
   // In summary, we only need to update the symbol table if we have none.
   // This is actually very common because of broken build systems that think
   // they have to run ranlib.
-  if (OldArchive->hasSymbolTable())
-return;
+  if (OldArchive->hasSymbolTable()) {
+if (OldArchive->kind() != object::Archive::K_AIXBIG)
+  return;
 
+// For archives in the Big Archive format, the bit mode option specifies
+// which symbol table to generate. The presence of a symbol table that does
+// not match the specified bit mode does not prevent creation of the symbol
+// table that has been requested.
+if (OldArchive->kind() == object::Archive::K_AIXBIG) {
+  BigArchive *BigArc = dyn_cast(OldArchive);
+  if (BigArc->has32BitGlobalSymtab() &&
+  Symtab == SymtabWritingMode::BigArchive32)
+return;
+
+  if (BigArc->has64BitGlobalSymtab() &&
+  Symtab == SymtabWritingMode::BigArchive64)
+return;
+
+  if (BigArc->has32BitGlobalSymtab() && BigArc->has64BitGlobalSymtab() &&
+  Symtab == SymtabWritingMode::NormalSymtab)
+return;
+
+  Symtab = SymtabWritin

[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-16 Thread Mark de Wever via Phabricator via cfe-commits
Mordante accepted this revision.
Mordante added a comment.

I'm happy with the libc++ changes, please wait a few days for @ldionne to react.

In D112921#4584704 , @aaron.ballman 
wrote:

> In D112921#4581641 , @rnk wrote:
>
>> What are the next steps here? Have concerns been addressed? The CI failures 
>> seem unrelated (libcxx tests is an AIX bot out of disk, clang CI is an 
>> interpreter test that seems unrelated, but please confirm).
>
> We definitely need the libc++ reviewers to approve before we move forward. 
> IMO. the clang bits look to be in reasonable shape in terms of code quality.

I leave the approval of the clang part to @aaron.ballman




Comment at: 
libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp:29
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-17
+

Mordante wrote:
> The bootstrap build fails. Currently main is clang-18. Since you intend to 
> backport the patch it needs to be disabled on clang-17 too.
Based on the timing I'm no longer in favor of backporting this patch.

For the future please mark comments as done when addressed. That makes 
reviewing easier.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112921

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 550800.
victorkingi added a comment.

added support for backend remarks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,58 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+
+! Check "unknown remark option" warning
+! RUN: %flang %s -O1 -R 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-WARN
+
+! Check "unknown remark option" warning with suggestion
+! RUN: %flang %s -O1 -Rpas 2>&1 | FileCheck %s --check-prefix=CHECK-WARN-SUGGEST
+
+! Check -Rno-pass, -Rno-pass-analysis, -Rno-pass-missed nothing emitted
+! RUN: %flang %s -O1 -Rno-pass 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-missed 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang %s -O1 -Rno-pass-analysis 2>&1 | FileCheck %s --allow-empty --check-prefix=CHECK-NO-REMARKS
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+! Check a backend pass can be generated
+! RUN: %flang %s -O1 -Rpass-analysis 2>&1 | FileCheck %s --check-prefix=BACKEND
+
+
+! CHECK: optimization-remark.f90:54:5: remark: Loop deleted because it is invariant [-Rpass=loop-delete]
+! CHECK-REMARKS-MISSED: optimization-remark.f90:49:5: remark: loop not vectorized [-Rpass-missed=loop-vectorize]
+! CHECK-REMARKS-ANALYSIS: optimization-remark.f90:49:5: remark: loop not vectorized: instruction cannot be vectorized [-Rpass-analysis=loop-vectorize]
+! CHECK-REMARKS: remark:
+! CHECK-NO-REMARKS-NOT: remark:
+
+! CHECK-REMARKS-WARN: warning: unknown remark option '-R' [-Wunknown-warning-option]
+! CHECK-WARN-SUGGEST: warning: unknown remark option '-Rpas'; did you mean '-Rpass'? [-Wunknown-warning-option]
+
+! BACKEND: optimization-remark.f90:1:0: remark: 25 instructions in function [-Rpass-analysis=asm-printer]
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -22,6 +22,7 @@
 #include "mlir/IR/AsmState.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Pass/PassManager.h"
+#include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Driver/Options.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
@@ -100,6 +101,54 @@
   llvm_unreachable("Invalid program action!");
 }
 
+// Emit a warning and typo hint for unknown warning opts
+static void emitUnknownDiagWarning(clang::DiagnosticsEngine &diags,
+   clang::diag::Flavor flavor,
+   llvm::StringRef prefix,
+   llvm::StringRef opt) {
+  llvm::StringRef suggestion =
+  clang::DiagnosticIDs::getNearestOption(flavor, opt);
+  diags.Report(clang::diag::warn_unknown_diag_option)
+  << (flavor == clang::diag::Flavor::WarningOrError ? 0 : 1)
+  << (prefix.str() += std::string(opt)) << !suggestion.empty()
+  << (prefix.str() += std::string(suggestion));
+}
+
+// Remarks are ignored by default in Diagnostic.td, hence, we have to
+// enable them here before execution. Clang follows same idea using
+// ProcessWarningOptions in Warnings.cpp
+// This function is also responsible for emitting early warnings for
+// invalid -R options.
+static void
+updateDiagEngineForOptRemarks(clang::DiagnosticsEngine &diagsEng,
+  const clang::DiagnosticOptions &opts) {
+  llvm::SmallVector diags;
+  cons

[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-16 Thread victorkingi via Phabricator via cfe-commits
victorkingi added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:1032-1043
+case llvm::DK_MachineOptimizationRemark:
+  optimizationRemarkHandler(
+  llvm::cast(di));
+  break;
+case llvm::DK_MachineOptimizationRemarkMissed:
+  optimizationRemarkHandler(
+  llvm::cast(di));

This cases should handle back-end passes as the previous cases only handled 
middle-end


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D155713: [clang] Fix interaction between dllimport and exclude_from_explicit_instantiation

2023-08-16 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

> That doesn't handle the second of your test cases though, where dllimport is 
> put on the member directly:
> ...
> It's not clear to me how we'd want to handle that. I don't think it comes up 
> in libc++, and I can't think of any code that would want to do that either, 
> really.

I think this does actually matter for libc++, I think I have seen this pattern:

  template 
  struct Foo {
_LIBCPP_FUNC_VIS _LIBCPP_EXCLUDE_FROM_ABI void method() { }
  };

I can't find an instance right now, though. I think it comes up when you want 
to have a default visibility function, and also keep it out of the libc++ DSO 
interface.

This is a somewhat weird and contradictory case, though, the attributes 
directly conflict. I think it would be reasonable to teach SemaDeclAttr to 
ignore the dllimport attribute if the other attribute is already present.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155713

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


[clang] 063c42e - [clang-format] Handle NamespaceMacro string arg for FixNamespaceComments

2023-08-16 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-08-16T10:45:54-07:00
New Revision: 063c42e919c01d7e64c1af5a10898fc84b06dfe8

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

LOG: [clang-format] Handle NamespaceMacro string arg for FixNamespaceComments

Fixes #63795.

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

Added: 


Modified: 
clang/lib/Format/NamespaceEndCommentsFixer.cpp
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index 32c2592834555a..4d3bd3b33f0f11 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -174,7 +174,7 @@ bool validEndComment(const FormatToken *RBraceTok, 
StringRef NamespaceName,
   llvm::Regex::IgnoreCase);
   static const llvm::Regex NamespaceMacroCommentPattern =
   llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
-  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*)\\)\\.? *(\\*/)?$",
+  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*|\".+\")\\)\\.? *(\\*/)?$",
   llvm::Regex::IgnoreCase);
 
   SmallVector Groups;

diff  --git a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp 
b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
index 65876a3c668650..ec335c985ebba2 100644
--- a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -40,6 +40,18 @@ class NamespaceEndCommentsFixerTest : public ::testing::Test 
{
 Code,
 /*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
   }
+
+  bool isFormatted(StringRef Code, const std::vector &Ranges,
+   const FormatStyle &Style = getLLVMStyle()) const {
+return clang::format::fixNamespaceEndComments(Style, Code, Ranges,
+  "")
+.empty();
+  }
+
+  bool isFormatted(StringRef Code,
+   const FormatStyle &Style = getLLVMStyle()) const {
+return isFormatted(Code, {1, tooling::Range(0, Code.size())}, Style);
+  }
 };
 
 TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
@@ -688,48 +700,34 @@ TEST_F(NamespaceEndCommentsFixerTest, 
KeepsValidMacroEndComment) {
   FormatStyle Style = getLLVMStyle();
   Style.NamespaceMacros.push_back("TESTSUITE");
 
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-fixNamespaceEndComments("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE() {\n"
+  "int i;\n"
+  "} // end anonymous TESTSUITE()",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "} /* end of TESTSUITE(A) */",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "}   //   TESTS

[PATCH] D157568: [clang-format] Handle NamespaceMacro string arg for FixNamespaceComments

2023-08-16 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG063c42e919c0: [clang-format] Handle NamespaceMacro string 
arg for FixNamespaceComments (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157568

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -40,6 +40,18 @@
 Code,
 /*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
   }
+
+  bool isFormatted(StringRef Code, const std::vector &Ranges,
+   const FormatStyle &Style = getLLVMStyle()) const {
+return clang::format::fixNamespaceEndComments(Style, Code, Ranges,
+  "")
+.empty();
+  }
+
+  bool isFormatted(StringRef Code,
+   const FormatStyle &Style = getLLVMStyle()) const {
+return isFormatted(Code, {1, tooling::Range(0, Code.size())}, Style);
+  }
 };
 
 TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
@@ -688,48 +700,34 @@
   FormatStyle Style = getLLVMStyle();
   Style.NamespaceMacros.push_back("TESTSUITE");
 
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-fixNamespaceEndComments("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE() {\n"
+  "int i;\n"
+  "} // end anonymous TESTSUITE()",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "} /* end of TESTSUITE(A) */",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "}   //   TESTSUITE(A)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A::B) {\n"
+  "int i;\n"
+  "} // end TESTSUITE(A::B)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "}; // end TESTSUITE(A)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE() {\n"
+  "int i;\n"
+  "}; /* unnamed TESTSUITE() */",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(\"foo\") {\n"
+  "int i;\n"
+  "} // TESTSUITE(\"foo\")",
+  Style));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -174,7 +174,7 @@
   llvm::Regex::IgnoreCase);
   static const llvm::Regex Namespa

[PATCH] D157757: [Headers] Replace __need_STDDEF_H_misc with specific __need_ macros

2023-08-16 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik added a comment.

I think these changes would allow us to drop the `stddef.h` compat header from 
libc++, which would be really nice.




Comment at: clang/lib/Headers/stddef.h:36-40
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+(defined(__cplusplus) && defined(_MSC_EXTENSIONS) &&   
\
+ defined(_NATIVE_NULLPTR_SUPPORTED))
+#define __need_nullptr_t
+#endif





Comment at: clang/lib/Headers/stddef.h:118-125
+#ifdef __cplusplus
+namespace std {
+typedef decltype(nullptr) nullptr_t;
+}
+using ::std::nullptr_t;
+#else
 typedef typeof(nullptr) nullptr_t;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157757

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


[PATCH] D157757: [Headers] Replace __need_STDDEF_H_misc with specific __need_ macros

2023-08-16 Thread Ian Anderson via Phabricator via cfe-commits
iana marked an inline comment as done.
iana added a comment.

In D157757#4592766 , @philnik wrote:

> I think these changes would allow us to drop the `stddef.h` compat header 
> from libc++, which would be really nice.

I'd really rather not change how `nullptr_t` gets declared in this change, can 
we do these in another one?




Comment at: clang/lib/Headers/stddef.h:118-122
+#ifdef __cplusplus
+namespace std {
+typedef decltype(nullptr) nullptr_t;
+}
+using ::std::nullptr_t;

aaron.ballman wrote:
> Related:
> 
> https://github.com/llvm/llvm-project/issues/37564
> https://cplusplus.github.io/LWG/issue3484
> 
> CC @ldionne
I don't _think_ this change actually changes the way nullptr_t gets defined in 
C++, does it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157757

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


[PATCH] D157793: [Headers] Add missing __need_ macros to stdarg.h

2023-08-16 Thread Ian Anderson via Phabricator via cfe-commits
iana updated this revision to Diff 550823.
iana added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157793

Files:
  clang/lib/Headers/stdarg.h
  clang/test/Headers/stdarg.c
  clang/test/Headers/stdargneeds.c

Index: clang/test/Headers/stdargneeds.c
===
--- /dev/null
+++ clang/test/Headers/stdargneeds.c
@@ -0,0 +1,91 @@
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds0.c
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds1.c
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds2.c
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds3.c
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds4.c
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror=implicit-function-declaration -std=c89 %t/stdargneeds5.c
+
+// Split the file so that the "implicitly declaring library function" errors get repeated.
+// Use C89 to verify that __need_ can be used to get types that wouldn't normally be available.
+
+//--- stdargneeds0.c
+static void f(int p, ...) {
+__gnuc_va_list g; // expected-error{{undeclared identifier '__gnuc_va_list'}}
+va_list v; // expected-error{{undeclared identifier 'va_list'}}
+va_start(v, p); // expected-error{{implicitly declaring library function 'va_start'}} expected-note{{include the header  or explicitly provide a declaration for 'va_start'}} expected-error{{undeclared identifier 'v'}}
+int i = va_arg(v, int); // expected-error{{implicit declaration of function 'va_arg'}} expected-error{{expected expression}} expected-error{{use of undeclared identifier 'v'}}
+va_end(v); // expected-error{{implicitly declaring library function 'va_end'}} expected-note{{include the header  or explicitly provide a declaration for 'va_end'}} expected-error{{undeclared identifier 'v'}}
+__va_copy(g, v); // expected-error{{implicit declaration of function '__va_copy'}} expected-error{{use of undeclared identifier 'g'}} expected-error{{use of undeclared identifier 'v'}}
+va_copy(g, v); // expected-error{{implicitly declaring library function 'va_copy'}} expected-note{{include the header  or explicitly provide a declaration for 'va_copy'}} expected-error{{use of undeclared identifier 'g'}} expected-error{{use of undeclared identifier 'v'}}
+}
+
+//--- stdargneeds1.c
+#define __need___va_list
+#include 
+static void f(int p, ...) {
+__gnuc_va_list g;
+va_list v; // expected-error{{undeclared identifier}}
+va_start(v, p); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}} expected-error{{undeclared identifier}}
+int i = va_arg(v, int); // expected-error{{implicit declaration of function}} expected-error{{expected expression}} expected-error{{undeclared identifier}}
+va_end(v); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}} expected-error{{undeclared identifier}}
+__va_copy(g, v); // expected-error{{implicit declaration of function}} expected-error{{undeclared identifier}}
+va_copy(g, v); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}} expected-error{{undeclared identifier}}
+}
+
+//--- stdargneeds2.c
+#define __need_va_list
+#include 
+static void f(int p, ...) {
+__gnuc_va_list g; // expected-error{{undeclared identifier}}
+va_list v;
+va_start(v, p); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}}
+int i = va_arg(v, int); // expected-error{{implicit declaration of function}} expected-error{{expected expression}}
+va_end(v); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}}
+__va_copy(g, v); // expected-error{{implicit declaration of function}} expected-error{{undeclared identifier}}
+va_copy(g, v); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}} expected-error{{undeclared identifier}}
+}
+
+//--- stdargneeds3.c
+#define __need_va_list
+#define __need_va_arg
+#include 
+static void f(int p, ...) {
+__gnuc_va_list g; // expected-error{{undeclared identifier}}
+va_list v;
+va_start(v, p);
+int i = va_arg(v, int);
+va_end(v);
+__va_copy(g, v); // expected-error{{implicit declaration of function}} expected-error{{undeclared identifier}}
+va_copy(g, v); // expected-error{{implicitly declaring library function}} expected-note{{provide a declaration}} expected-error{{undeclared identifier}}
+}
+
+//--- stdargneeds4.c
+#define __need___va_list
+#define __need_va_list
+#define __need___v

[PATCH] D157757: [Headers] Replace __need_STDDEF_H_misc with specific __need_ macros

2023-08-16 Thread Ian Anderson via Phabricator via cfe-commits
iana updated this revision to Diff 550826.
iana added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157757

Files:
  clang/lib/Headers/stddef.h
  clang/test/Headers/stddef.c
  clang/test/Headers/stddefneeds.c

Index: clang/test/Headers/stddefneeds.c
===
--- /dev/null
+++ clang/test/Headers/stddefneeds.c
@@ -0,0 +1,169 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=c99 -std=c99 %s
+// RUN: %clang_cc1 -fsyntax-only -verify=c23 -std=c23 %s
+
+// Use C99 to verify that __need_ can be used to get types that wouldn't normally be available.
+
+struct astruct { char member; };
+
+ptrdiff_t p0; // c99-error{{unknown type name 'ptrdiff_t'}} c23-error{{unknown type}}
+size_t s0; // c99-error{{unknown type name 'size_t'}} c23-error{{unknown type}}
+rsize_t r0; // c99-error{{unknown type name 'rsize_t'}} c23-error{{unknown type}}
+wchar_t wc0; // c99-error{{unknown type name 'wchar_t'}} c23-error{{unknown type}}
+void *v0 = NULL; // c99-error{{use of undeclared identifier 'NULL'}} c23-error{{undeclared identifier}}
+nullptr_t n0; // c99-error{{unknown type name 'nullptr_t'}} c23-error{{unknown type}}
+static void f0(void) { unreachable(); } // c99-error{{call to undeclared function 'unreachable'}} c23-error{{undeclared identifier 'unreachable'}}
+max_align_t m0; // c99-error{{unknown type name 'max_align_t'}} c23-error{{unknown type}}
+size_t o0 = offsetof(struct astruct, member); // c99-error{{unknown type name 'size_t'}} c99-error{{call to undeclared function 'offsetof'}} c99-error{{expected expression}} c99-error{{use of undeclared identifier 'member'}} \
+ c23-error{{unknown type name 'size_t'}} c23-error{{undeclared identifier 'offsetof'}} c23-error{{expected expression}} c23-error{{use of undeclared identifier 'member'}}
+wint_t wi0; // c99-error{{unknown type name 'wint_t'}} c23-error{{unknown type}}
+
+#define __need_ptrdiff_t
+#include 
+
+ptrdiff_t p1;
+size_t s1; // c99-error{{unknown type}} c23-error{{unknown type}}
+rsize_t r1; // c99-error{{unknown type}} c23-error{{unknown type}}
+wchar_t wc1; // c99-error{{unknown type}} c23-error{{unknown type}}
+void *v1 = NULL; // c99-error{{undeclared identifier}} c23-error{{undeclared identifier}}
+nullptr_t n1; // c99-error{{unknown type}} c23-error{{unknown type}}
+static void f1(void) { unreachable(); } // c99-error{{undeclared function}} c23-error{{undeclared identifier}}
+max_align_t m1; // c99-error{{unknown type}} c23-error{{unknown type}}
+size_t o1 = offsetof(struct astruct, member); // c99-error{{unknown type}} c99-error{{expected expression}} c99-error{{undeclared identifier}} \
+ c23-error{{unknown type}} c23-error{{undeclared identifier}} c23-error{{expected expression}} c23-error{{undeclared identifier}}
+wint_t wi1; // c99-error{{unknown type}} c23-error{{unknown type}}
+
+#define __need_size_t
+#include 
+
+ptrdiff_t p2;
+size_t s2;
+rsize_t r2; // c99-error{{unknown type}} c23-error{{unknown type}}
+// c99-note@stddef.h:*{{'size_t' declared here}} c23-note@stddef.h:*{{'size_t' declared here}}
+wchar_t wc2; // c99-error{{unknown type}} c23-error{{unknown type}}
+void *v2 = NULL; // c99-error{{undeclared identifier}} c23-error{{undeclared identifier}}
+nullptr_t n2; // c99-error{{unknown type}} c23-error{{unknown type}}
+static void f2(void) { unreachable(); } // c99-error{{undeclared function}} c23-error{{undeclared identifier}}
+max_align_t m2; // c99-error{{unknown type}} c23-error{{unknown type}}
+size_t o2 = offsetof(struct astruct, member); // c99-error{{expected expression}} c99-error{{undeclared identifier}} \
+ c23-error{{undeclared identifier}} c23-error{{expected expression}} c23-error{{undeclared identifier}}
+wint_t wi2; // c99-error{{unknown type}} c23-error{{unknown type}}
+
+#define __need_rsize_t
+#include 
+
+ptrdiff_t p3;
+size_t s3;
+rsize_t r3;
+wchar_t wc3; // c99-error{{unknown type}} c23-error{{unknown type}}
+void *v3 = NULL; // c99-error{{undeclared identifier}} c23-error{{undeclared identifier}}
+nullptr_t n3; // c99-error{{unknown type}} c23-error{{unknown type}}
+static void f3(void) { unreachable(); } // c99-error{{undeclared function}} c23-error{{undeclared identifier}}
+max_align_t m3; // c99-error{{unknown type}} c23-error{{unknown type}}
+size_t o3 = offsetof(struct astruct, member); // c99-error{{expected expression}} c99-error{{undeclared identifier}} \
+ c23-error{{undeclared identifier}} c23-error{{expected expression}} c23-error{{undeclared identifier}}
+wint_t wi3; // c99-error{{unknown type}} c23-error{{unknown type}}
+
+#define __need_wchar_t
+#include 
+
+ptrdiff_t p4;
+size_t s4;
+rsize_t r4;
+wchar_t wc4;
+void *v4 = NULL; // c99-error{{und

[PATCH] D156571: [DebugInfo] Alternate MD5 fix, NFC

2023-08-16 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

Ping


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

https://reviews.llvm.org/D156571

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


[PATCH] D157757: [Headers] Replace __need_STDDEF_H_misc with specific __need_ macros

2023-08-16 Thread Ian Anderson via Phabricator via cfe-commits
iana added a comment.

In D157757#4592794 , @iana wrote:

> In D157757#4592766 , @philnik wrote:
>
>> I think these changes would allow us to drop the `stddef.h` compat header 
>> from libc++, which would be really nice.
>
> I'd really rather not change how `nullptr_t` gets declared in this change, 
> can we do these in another one?

Also my preference would be that we take the c++ stuff _out_ of this header and 
put it in the libc++ one, but I'm guessing that would cause issues for 
libstdc++?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157757

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


[PATCH] D158104: [clang-format][NFC] Simplify getFirstNonComment() in the annotator

2023-08-16 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, MyDeveloperDay.
owenpan requested review of this revision.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158104

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


Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -151,6 +151,11 @@
startsWith(tok::kw_export, tok::kw_namespace);
   }
 
+  FormatToken *getFirstNonComment() const {
+assert(First);
+return First->is(tok::comment) ? First->getNextNonComment() : First;
+  }
+
   FormatToken *First;
   FormatToken *Last;
 
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4763,16 +4763,6 @@
  !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
 }
 
-// Returns the first token on the line that is not a comment.
-static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) {
-  const FormatToken *Next = Line.First;
-  if (!Next)
-return Next;
-  if (Next->is(tok::comment))
-Next = Next->getNextNonComment();
-  return Next;
-}
-
 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
  const FormatToken &Right) const {
   const FormatToken &Left = *Right.Previous;
@@ -5044,7 +5034,7 @@
 return Right.HasUnescapedNewline;
 
   if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
-auto FirstNonComment = getFirstNonComment(Line);
+auto *FirstNonComment = Line.getFirstNonComment();
 bool AccessSpecifier =
 FirstNonComment &&
 FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public,


Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -151,6 +151,11 @@
startsWith(tok::kw_export, tok::kw_namespace);
   }
 
+  FormatToken *getFirstNonComment() const {
+assert(First);
+return First->is(tok::comment) ? First->getNextNonComment() : First;
+  }
+
   FormatToken *First;
   FormatToken *Last;
 
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4763,16 +4763,6 @@
  !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
 }
 
-// Returns the first token on the line that is not a comment.
-static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) {
-  const FormatToken *Next = Line.First;
-  if (!Next)
-return Next;
-  if (Next->is(tok::comment))
-Next = Next->getNextNonComment();
-  return Next;
-}
-
 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
  const FormatToken &Right) const {
   const FormatToken &Left = *Right.Previous;
@@ -5044,7 +5034,7 @@
 return Right.HasUnescapedNewline;
 
   if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
-auto FirstNonComment = getFirstNonComment(Line);
+auto *FirstNonComment = Line.getFirstNonComment();
 bool AccessSpecifier =
 FirstNonComment &&
 FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >