[clang-tools-extra] [InstCombine] Fold icmp(constants[x]) when the range of x is given (PR #67093)

2023-09-22 Thread via cfe-commits

https://github.com/XChy updated https://github.com/llvm/llvm-project/pull/67093

>From e7314709fc812736a357b50654b08ef722fb89a4 Mon Sep 17 00:00:00 2001
From: XChy 
Date: Mon, 31 Jul 2023 17:10:45 +0800
Subject: [PATCH 1/2] [InstCombine] Tests for simplifying icmp(constants[x])

---
 llvm/test/Transforms/InstCombine/load-cmp.ll | 146 +++
 1 file changed, 146 insertions(+)

diff --git a/llvm/test/Transforms/InstCombine/load-cmp.ll 
b/llvm/test/Transforms/InstCombine/load-cmp.ll
index 7fb6e7a3a37b388..4c74e73ee991c93 100644
--- a/llvm/test/Transforms/InstCombine/load-cmp.ll
+++ b/llvm/test/Transforms/InstCombine/load-cmp.ll
@@ -334,3 +334,149 @@ define i1 @test10_struct_arr_noinbounds_i64(i64 %x) {
   %r = icmp eq i32 %q, 9
   ret i1 %r
 }
+
+
+@CG = constant [4 x i32] [i32 1, i32 2, i32 3, i32 4]
+
+define i1 @cmp_load_constant_array0(i64 %x){
+; CHECK-LABEL: @cmp_load_constant_array0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[COND:%.*]] = icmp ult i64 [[X:%.*]], 2
+; CHECK-NEXT:br i1 [[COND]], label [[CASE1:%.*]], label [[CASE2:%.*]]
+; CHECK:   case2:
+; CHECK-NEXT:ret i1 false
+; CHECK:   case1:
+; CHECK-NEXT:[[TMP0:%.*]] = trunc i64 [[X]] to i32
+; CHECK-NEXT:[[ISOK_PTR:%.*]] = getelementptr inbounds i32, ptr @CG, i32 
[[TMP0]]
+; CHECK-NEXT:[[ISOK:%.*]] = load i32, ptr [[ISOK_PTR]], align 4
+; CHECK-NEXT:[[COND_INFERRED:%.*]] = icmp ult i32 [[ISOK]], 3
+; CHECK-NEXT:ret i1 [[COND_INFERRED]]
+;
+entry:
+  %cond = icmp ult i64 %x, 2
+  br i1 %cond, label %case1, label %case2
+
+case2:
+  ret i1 0
+
+case1:
+  %isOK_ptr = getelementptr inbounds i32, ptr @CG, i64 %x
+  %isOK = load i32, ptr %isOK_ptr
+  %cond_inferred = icmp ult i32 %isOK, 3
+  ret i1 %cond_inferred
+}
+
+define i1 @cmp_load_constant_array1(i64 %x){
+; CHECK-LABEL: @cmp_load_constant_array1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[COND:%.*]] = icmp ult i64 [[X:%.*]], 2
+; CHECK-NEXT:br i1 [[COND]], label [[CASE1:%.*]], label [[CASE2:%.*]]
+; CHECK:   case2:
+; CHECK-NEXT:ret i1 false
+; CHECK:   case1:
+; CHECK-NEXT:[[TMP0:%.*]] = trunc i64 [[X]] to i32
+; CHECK-NEXT:[[ISOK_PTR:%.*]] = getelementptr inbounds i32, ptr @CG, i32 
[[TMP0]]
+; CHECK-NEXT:[[ISOK:%.*]] = load i32, ptr [[ISOK_PTR]], align 4
+; CHECK-NEXT:[[COND_INFERRED:%.*]] = icmp ugt i32 [[ISOK]], 10
+; CHECK-NEXT:ret i1 [[COND_INFERRED]]
+;
+entry:
+  %cond = icmp ult i64 %x, 2
+  br i1 %cond, label %case1, label %case2
+
+case2:
+  ret i1 0
+
+case1:
+  %isOK_ptr = getelementptr inbounds i32, ptr @CG, i64 %x
+  %isOK = load i32, ptr %isOK_ptr
+  %cond_inferred = icmp ugt i32 %isOK, 10
+  ret i1 %cond_inferred
+}
+
+@CG_MESSY = constant [9 x i32] [i32 1, i32 7, i32 -1, i32 5, i32 4, i32 1, i32 
1, i32 5, i32 4]
+
+define i1 @cmp_load_constant_array_messy(i64 %x){
+; CHECK-LABEL: @cmp_load_constant_array_messy(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[COND:%.*]] = icmp slt i64 [[X:%.*]], 6
+; CHECK-NEXT:br i1 [[COND]], label [[CASE1:%.*]], label [[CASE2:%.*]]
+; CHECK:   case2:
+; CHECK-NEXT:ret i1 false
+; CHECK:   case1:
+; CHECK-NEXT:[[TMP0:%.*]] = trunc i64 [[X]] to i32
+; CHECK-NEXT:[[ISOK_PTR:%.*]] = getelementptr i32, ptr @CG_MESSY, i32 
[[TMP0]]
+; CHECK-NEXT:[[ISOK:%.*]] = load i32, ptr [[ISOK_PTR]], align 4
+; CHECK-NEXT:[[COND_INFERRED:%.*]] = icmp slt i32 [[ISOK]], 5
+; CHECK-NEXT:ret i1 [[COND_INFERRED]]
+;
+entry:
+  %cond = icmp slt i64 %x, 6
+  br i1 %cond, label %case1, label %case2
+
+case2:
+  ret i1 0
+
+case1:
+  %isOK_ptr = getelementptr i32, ptr @CG_MESSY, i64 %x
+  %isOK = load i32, ptr %isOK_ptr
+  %cond_inferred = icmp slt i32 %isOK, 5
+  ret i1 %cond_inferred
+}
+
+define i1 @cmp_diff_load_constant_array_messy0(i64 %x){
+; CHECK-LABEL: @cmp_diff_load_constant_array_messy0(
+; CHECK-NEXT:[[TMP1:%.*]] = trunc i64 [[X:%.*]] to i32
+; CHECK-NEXT:[[ISOK_PTR:%.*]] = getelementptr i32, ptr @CG_MESSY, i32 
[[TMP1]]
+; CHECK-NEXT:[[ISOK:%.*]] = load i16, ptr [[ISOK_PTR]], align 4
+; CHECK-NEXT:[[COND_INFERRED:%.*]] = icmp slt i16 [[ISOK]], 5
+; CHECK-NEXT:ret i1 [[COND_INFERRED]]
+;
+  %isOK_ptr = getelementptr i32, ptr @CG_MESSY, i64 %x
+  %isOK = load i16, ptr %isOK_ptr
+  %cond_inferred = icmp slt i16 %isOK, 5
+  ret i1 %cond_inferred
+}
+
+define i1 @cmp_diff_load_constant_array_messy1(i64 %x){
+; CHECK-LABEL: @cmp_diff_load_constant_array_messy1(
+; CHECK-NEXT:[[TMP1:%.*]] = trunc i64 [[X:%.*]] to i32
+; CHECK-NEXT:[[ISOK_PTR:%.*]] = getelementptr i6, ptr @CG_MESSY, i32 
[[TMP1]]
+; CHECK-NEXT:[[ISOK:%.*]] = load i16, ptr [[ISOK_PTR]], align 2
+; CHECK-NEXT:[[COND_INFERRED:%.*]] = icmp slt i16 [[ISOK]], 5
+; CHECK-NEXT:ret i1 [[COND_INFERRED]]
+;
+%isOK_ptr = getelementptr i6, ptr @CG_MESSY, i64 %x
+  %isOK = load i16, ptr %isOK_ptr
+  %cond_inferred = icmp slt i16 %isOK, 5
+  ret i1 %cond_inferred
+}
+
+define i1 @cmp_load_constant_array_fail0(i64 %x, i32 %y) {
+; CHECK-LABEL: @cmp_load

[PATCH] D19385: [scan-build] fix warnings emitted on Clang Format code base

2023-09-22 Thread Apelete Seketeli via Phabricator via cfe-commits
apelete added a comment.

I guess it can be closed, thanks.


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

https://reviews.llvm.org/D19385

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


[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

2023-09-22 Thread Prabhu Karthikeyan Rajasekaran via Phabricator via cfe-commits
Prabhuk updated this revision to Diff 557221.
Prabhuk added a comment.

Datalayout update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

Files:
  llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp
  llvm/lib/Target/X86/X86CallingConv.td
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/lib/Target/X86/X86RegisterInfo.h
  llvm/lib/Target/X86/X86Subtarget.h

Index: llvm/lib/Target/X86/X86Subtarget.h
===
--- llvm/lib/Target/X86/X86Subtarget.h
+++ llvm/lib/Target/X86/X86Subtarget.h
@@ -334,6 +334,10 @@
 
   bool isOSWindows() const { return TargetTriple.isOSWindows(); }
 
+  bool isUEFI() const { return TargetTriple.isUEFI(); }
+
+  bool isTargetUEFI64() const { return Is64Bit && isUEFI(); }
+
   bool isTargetWin64() const { return Is64Bit && isOSWindows(); }
 
   bool isTargetWin32() const { return !Is64Bit && isOSWindows(); }
@@ -349,7 +353,8 @@
 
   bool isCallingConvWin64(CallingConv::ID CC) const {
 switch (CC) {
-// On Win64, all these conventions just use the default convention.
+// On Win64 and UEFI64, all these conventions just use the default
+// convention.
 case CallingConv::C:
 case CallingConv::Fast:
 case CallingConv::Tail:
@@ -360,7 +365,7 @@
 case CallingConv::X86_ThisCall:
 case CallingConv::X86_VectorCall:
 case CallingConv::Intel_OCL_BI:
-  return isTargetWin64();
+  return isTargetWin64() || isTargetUEFI64();
 // This convention allows using the Win64 convention on other targets.
 case CallingConv::Win64:
   return true;
Index: llvm/lib/Target/X86/X86RegisterInfo.h
===
--- llvm/lib/Target/X86/X86RegisterInfo.h
+++ llvm/lib/Target/X86/X86RegisterInfo.h
@@ -27,10 +27,14 @@
   ///
   bool Is64Bit;
 
-  /// IsWin64 - Is the target on of win64 flavours
+  /// IsWin64 - Is the target one of win64 flavours
   ///
   bool IsWin64;
 
+  /// IsUEFI64 - Is this UEFI 64 bit target
+  ///
+  bool IsUEFI64;
+
   /// SlotSize - Stack slot size in bytes.
   ///
   unsigned SlotSize;
Index: llvm/lib/Target/X86/X86RegisterInfo.cpp
===
--- llvm/lib/Target/X86/X86RegisterInfo.cpp
+++ llvm/lib/Target/X86/X86RegisterInfo.cpp
@@ -55,6 +55,7 @@
   // Cache some information.
   Is64Bit = TT.isArch64Bit();
   IsWin64 = Is64Bit && TT.isOSWindows();
+  IsUEFI64 = Is64Bit && TT.isUEFI();
 
   // Use a callee-saved register as the base pointer.  These registers must
   // not conflict with any ABI requirements.  For example, in 32-bit mode PIC
@@ -232,7 +233,7 @@
 const TargetRegisterClass *
 X86RegisterInfo::getGPRsForTailCall(const MachineFunction &MF) const {
   const Function &F = MF.getFunction();
-  if (IsWin64 || (F.getCallingConv() == CallingConv::Win64))
+  if (IsWin64 || IsUEFI64 || (F.getCallingConv() == CallingConv::Win64))
 return &X86::GR64_TCW64RegClass;
   else if (Is64Bit)
 return &X86::GR64_TCRegClass;
@@ -331,7 +332,7 @@
   }
   case CallingConv::X86_RegCall:
 if (Is64Bit) {
-  if (IsWin64) {
+  if (IsWin64 || IsUEFI64) {
 return (HasSSE ? CSR_Win64_RegCall_SaveList :
  CSR_Win64_RegCall_NoSSE_SaveList);
   } else {
@@ -391,7 +392,7 @@
   return IsWin64 ? CSR_Win64_SwiftError_SaveList
  : CSR_64_SwiftError_SaveList;
 
-if (IsWin64)
+if (IsWin64 || IsUEFI64)
   return HasSSE ? CSR_Win64_SaveList : CSR_Win64_NoSSE_SaveList;
 if (CallsEHReturn)
   return CSR_64EHRet_SaveList;
@@ -451,7 +452,7 @@
   }
   case CallingConv::X86_RegCall:
 if (Is64Bit) {
-  if (IsWin64) {
+  if (IsWin64 || IsUEFI64) {
 return (HasSSE ? CSR_Win64_RegCall_RegMask :
  CSR_Win64_RegCall_NoSSE_RegMask);
   } else {
@@ -509,7 +510,7 @@
 if (IsSwiftCC)
   return IsWin64 ? CSR_Win64_SwiftError_RegMask : CSR_64_SwiftError_RegMask;
 
-return IsWin64 ? CSR_Win64_RegMask : CSR_64_RegMask;
+return (IsWin64 || IsUEFI64) ? CSR_Win64_RegMask : CSR_64_RegMask;
   }
 
   return CSR_32_RegMask;
Index: llvm/lib/Target/X86/X86CallingConv.td
===
--- llvm/lib/Target/X86/X86CallingConv.td
+++ llvm/lib/Target/X86/X86CallingConv.td
@@ -521,6 +521,9 @@
   // Mingw64 and native Win64 use Win64 CC
   CCIfSubtarget<"isTargetWin64()", CCDelegateTo>,
 
+  // UEFI64 uses Win64 CC
+  CCIfSubtarget<"isTargetUEFI64()", CCDelegateTo>,
+
   // Otherwise, drop to normal X86-64 CC
   CCDelegateTo
 ]>;
@@ -1127,6 +1130,9 @@
   // Mingw64 and native Win64 use Win64 CC
   CCIfSubtarget<"isTargetWin64()", CCDelegateTo>,
 
+  // UEFI64 uses Win64 CC
+  CCIfSubtarget<"isTargetUEFI64()", CCDelegateTo>,
+
   // Otherwise, drop to normal X86-64 CC
   CCDelegateTo
 ]>;
Index: llvm/lib/Target/X86/MCTargetDesc/

[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-09-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/67095

This was much easier than expected actually.

I'm sure I'm missing a lot of changes and test coverage though.

@aaronpuchert I'm starting a new review here instead of continuing the one in 
Phab since this is a completely different attempt. I hope that's ok.

>From 02b58a9f1ddc0dc00fec60461d611f6c61ff801c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 22 Sep 2023 08:42:05 +0200
Subject: [PATCH] [clang][TSA] Make RequiresCapability a DeclOrType attribute

---
 clang/include/clang/Basic/Attr.td |  6 +++---
 clang/test/Sema/warn-thread-safety-analysis.c | 11 +++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 21a3b5226623cf2..7eab87dac6921f1 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3305,7 +3305,7 @@ def ReleaseCapability : InheritableAttr {
   let Documentation = [ReleaseCapabilityDocs];
 }
 
-def RequiresCapability : InheritableAttr {
+def RequiresCapability : DeclOrTypeAttr {
   let Spellings = [Clang<"requires_capability", 0>,
Clang<"exclusive_locks_required", 0>,
Clang<"requires_shared_capability", 0>,
@@ -3314,8 +3314,8 @@ def RequiresCapability : InheritableAttr {
   let LateParsed = 1;
   let TemplateDependent = 1;
   let ParseArgumentsAsUnevaluated = 1;
-  let InheritEvenIfAlreadyPresent = 1;
-  let Subjects = SubjectList<[Function]>;
+  /*let InheritEvenIfAlreadyPresent = 1;*/
+  /*let Subjects = SubjectList<[Function]>;*/
   let Accessors = [Accessor<"isShared", [Clang<"requires_shared_capability", 
0>,
  Clang<"shared_locks_required", 0>]>];
   let Documentation = [Undocumented];
diff --git a/clang/test/Sema/warn-thread-safety-analysis.c 
b/clang/test/Sema/warn-thread-safety-analysis.c
index 642ea88ec3c96f7..cd852efac21cb81 100644
--- a/clang/test/Sema/warn-thread-safety-analysis.c
+++ b/clang/test/Sema/warn-thread-safety-analysis.c
@@ -136,6 +136,17 @@ int main(void) {
 // Cleanup happens automatically -> no warning.
   }
 
+  /// Function pointers
+  {
+int __attribute__((requires_capability(&mu1))) (*function_ptr)(int) = 
Foo_fun1;
+
+function_ptr(5); // expected-warning {{calling function 'function_ptr' 
requires holding mutex 'mu1'}}
+
+mutex_exclusive_lock(&mu1);
+int five = function_ptr(5);
+mutex_exclusive_unlock(&mu1);
+  }
+
   return 0;
 }
 

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


[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This was much easier than expected actually.

I'm sure I'm missing a lot of changes and test coverage though.

@aaronpuchert I'm starting a new review here instead of continuing the 
one in Phab since this is a completely different attempt. I hope that's ok.

---
Full diff: https://github.com/llvm/llvm-project/pull/67095.diff


2 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+3-3) 
- (modified) clang/test/Sema/warn-thread-safety-analysis.c (+11) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 21a3b5226623cf2..7eab87dac6921f1 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3305,7 +3305,7 @@ def ReleaseCapability : InheritableAttr {
   let Documentation = [ReleaseCapabilityDocs];
 }
 
-def RequiresCapability : InheritableAttr {
+def RequiresCapability : DeclOrTypeAttr {
   let Spellings = [Clang<"requires_capability", 0>,
Clang<"exclusive_locks_required", 0>,
Clang<"requires_shared_capability", 0>,
@@ -3314,8 +3314,8 @@ def RequiresCapability : InheritableAttr {
   let LateParsed = 1;
   let TemplateDependent = 1;
   let ParseArgumentsAsUnevaluated = 1;
-  let InheritEvenIfAlreadyPresent = 1;
-  let Subjects = SubjectList<[Function]>;
+  /*let InheritEvenIfAlreadyPresent = 1;*/
+  /*let Subjects = SubjectList<[Function]>;*/
   let Accessors = [Accessor<"isShared", [Clang<"requires_shared_capability", 
0>,
  Clang<"shared_locks_required", 0>]>];
   let Documentation = [Undocumented];
diff --git a/clang/test/Sema/warn-thread-safety-analysis.c 
b/clang/test/Sema/warn-thread-safety-analysis.c
index 642ea88ec3c96f7..cd852efac21cb81 100644
--- a/clang/test/Sema/warn-thread-safety-analysis.c
+++ b/clang/test/Sema/warn-thread-safety-analysis.c
@@ -136,6 +136,17 @@ int main(void) {
 // Cleanup happens automatically -> no warning.
   }
 
+  /// Function pointers
+  {
+int __attribute__((requires_capability(&mu1))) (*function_ptr)(int) = 
Foo_fun1;
+
+function_ptr(5); // expected-warning {{calling function 'function_ptr' 
requires holding mutex 'mu1'}}
+
+mutex_exclusive_lock(&mu1);
+int five = function_ptr(5);
+mutex_exclusive_unlock(&mu1);
+  }
+
   return 0;
 }
 

``




https://github.com/llvm/llvm-project/pull/67095
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

2023-09-22 Thread Prabhu Karthikeyan Rajasekaran via Phabricator via cfe-commits
Prabhuk updated this revision to Diff 557223.
Prabhuk added a comment.

Update patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

Files:
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/TargetParser/Triple.cpp
  llvm/unittests/TargetParser/TripleTest.cpp


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-09-22 Thread Timm Baeder via cfe-commits


@@ -136,6 +136,17 @@ int main(void) {
 // Cleanup happens automatically -> no warning.
   }
 
+  /// Function pointers
+  {
+int __attribute__((requires_capability(&mu1))) (*function_ptr)(int) = 
Foo_fun1;

tbaederr wrote:

This assignment also works if `Foo_fun1` does not have the 
`requires_capability(&mu1)` attribute, it would be better if we warned here I 
guess.

https://github.com/llvm/llvm-project/pull/67095
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

2023-09-22 Thread Prabhu Karthikeyan Rajasekaran via Phabricator via cfe-commits
Prabhuk added a comment.

@phosek -- Regarding the abandoning commit. I had messed up the commit 
splitting process earlier. Uploaded the correct set of files for this change 
now. Please take a look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

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


[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

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


[clang] [flang][Driver] Support -rpath, -shared, and -static in the frontend (PR #66702)

2023-09-22 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

> Thanks @MaskRay and @banach-space for taking a look at this. I have marked 
> the test as unsupported on windows because of a failing buildkite. I don't 
> have access to a Windows machine so I can't add an equivalent test for that 
> platform.

Thanks for working for this! We should investigate the Windows situation rather 
than disabling this test altogether - a lot of effort has gone into making it 
work and we should maintain that. Perhaps @mstorsjo or @DavidTruby could help?

https://github.com/llvm/llvm-project/pull/66702
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159541: [UEFI] X86_64 UEFI Clang Driver

2023-09-22 Thread Prabhu Karthikeyan Rajasekaran via Phabricator via cfe-commits
Prabhuk updated this revision to Diff 557227.
Prabhuk added a comment.

Addressed review comments about the inline comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159541

Files:
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/UEFI.cpp
  clang/lib/Driver/ToolChains/UEFI.h
  clang/test/Driver/uefi.c

Index: clang/test/Driver/uefi.c
===
--- /dev/null
+++ clang/test/Driver/uefi.c
@@ -0,0 +1,10 @@
+// RUN: %clang -### %s --target=x86_64-unknown-uefi \
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+// RUN: %clang -### %s --target=x86_64-uefi \
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-triple" "x86_64-unknown-uefi"
+// CHECK-SAME: "-mrelocation-model" "pic" "-pic-level" "2"
+// CHECK-SAME: "-mframe-pointer=all"
Index: clang/lib/Driver/ToolChains/UEFI.h
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/UEFI.h
@@ -0,0 +1,62 @@
+//===--- UEFI.h - UEFI ToolChain Implementations --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_UEFI_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_UEFI_H
+
+#include "clang/Driver/Tool.h"
+#include "clang/Driver/ToolChain.h"
+
+namespace clang {
+namespace driver {
+namespace tools {
+namespace uefi {
+class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
+public:
+  Linker(const ToolChain &TC) : Tool("uefi::Linker", "lld-link", TC) {}
+
+  bool hasIntegratedCPP() const override { return false; }
+  bool isLinkJob() const override { return true; }
+
+  void ConstructJob(Compilation &C, const JobAction &JA,
+const InputInfo &Output, const InputInfoList &Inputs,
+const llvm::opt::ArgList &TCArgs,
+const char *LinkingOutput) const override;
+};
+} // end namespace uefi
+} // end namespace tools
+
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY UEFI : public ToolChain {
+public:
+  UEFI(const Driver &D, const llvm::Triple &Triple,
+   const llvm::opt::ArgList &Args);
+
+protected:
+  Tool *buildLinker() const override;
+
+public:
+  bool HasNativeLLVMSupport() const override { return true; }
+  bool IsIntegratedAssemblerDefault() const override { return true; }
+  UnwindTableLevel
+  getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override {
+return UnwindTableLevel::Asynchronous;
+  }
+  bool isPICDefault() const override { return true; }
+  bool isPIEDefault(const llvm::opt::ArgList &Args) const override {
+return false;
+  }
+  bool isPICDefaultForced() const override { return true; }
+};
+
+} // namespace toolchains
+} // namespace driver
+} // namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_UEFI_H
Index: clang/lib/Driver/ToolChains/UEFI.cpp
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/UEFI.cpp
@@ -0,0 +1,115 @@
+//===--- UEFI.h - UEFI ToolChain Implementations --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UEFI.h"
+#include "CommonArgs.h"
+#include "Darwin.h"
+#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/Options.h"
+#include "clang/Driver/SanitizerArgs.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/TargetParser/Host.h"
+
+using namespace clang::driver;
+using namespace clang::driver::toolchains;
+using namespace clang;
+using namespace llvm::opt;
+
+UEFI::UEFI(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
+: ToolChain(D, Triple, Args) {
+  getProgramPaths().push_back(getDriver().getInstalledDir());
+  if (getDriver().getInstalledDir() != getDriver().Dir)
+getProgramPaths().push_back(getDriver().Dir);
+

[libunwind] 058222b - [libunwind][WebAssembly] Support Wasm EH

2023-09-22 Thread Heejin Ahn via cfe-commits

Author: Heejin Ahn
Date: 2023-09-22T00:35:37-07:00
New Revision: 058222b2316615194c089f2bc68d11341f39d26e

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

LOG: [libunwind][WebAssembly] Support Wasm EH

This adds Wasm-specific libunwind port to support Wasm exception
handling (https://github.com/WebAssembly/exception-handling).

Wasm EH requires `__USING_WASM_EXCEPTIONS__` to be defined. This adds
`Unwind-wasm.c`, which defines libunwind APIs for Wasm. This also adds a
`thread_local` struct of type `_Unwind_LandingPadContext`, which serves
as a medium for input/output data between the user code and the
personality function. How all these work is explained in
https://github.com/WebAssembly/tool-conventions/blob/main/EHScheme.md.
(The doc is old and "You Shouldn't Prune Unreachable Resumes" section
doesn't apply anymore, but otherwise it should be good)

The bulk of these changes was added back in Mar 2020 in
https://github.com/emscripten-core/emscripten/pull/10577 to emscripten
repo and has been used ever since. Now we'd like to upstream this so
that other toolchains that don't use emscripten libraries, e.g., WASI,
can use this too.

Companion patch: D158918

Reviewed By: dschuff, #libunwind, phosek

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

Added: 
libunwind/src/Unwind-wasm.c

Modified: 
libunwind/src/config.h

Removed: 




diff  --git a/libunwind/src/Unwind-wasm.c b/libunwind/src/Unwind-wasm.c
new file mode 100644
index 000..35f2f9aeab08048
--- /dev/null
+++ b/libunwind/src/Unwind-wasm.c
@@ -0,0 +1,121 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//
+//  Implements Wasm exception handling proposal
+//  (https://github.com/WebAssembly/exception-handling) based C++ exceptions
+//
+//===--===//
+
+#include "config.h"
+#include "unwind.h"
+#include 
+#include 
+
+#ifdef __USING_WASM_EXCEPTIONS__
+
+_Unwind_Reason_Code __gxx_personality_wasm0(int version, _Unwind_Action 
actions,
+uint64_t exceptionClass,
+_Unwind_Exception 
*unwind_exception,
+_Unwind_Context *context);
+
+struct _Unwind_LandingPadContext {
+  // Input information to personality function
+  uintptr_t lpad_index; // landing pad index
+  uintptr_t lsda;   // LSDA address
+
+  // Output information computed by personality function
+  uintptr_t selector; // selector value
+};
+
+// Communication channel between compiler-generated user code and personality
+// function
+thread_local struct _Unwind_LandingPadContext __wasm_lpad_context;
+
+/// Calls to this function is in landing pads in compiler-generated user code.
+/// In other EH schemes, stack unwinding is done by libunwind library, which
+/// calls the personality function for each each frame it lands. On the other
+/// hand, WebAssembly stack unwinding process is performed by a VM, and the
+/// personality function cannot be called from there. So the compiler inserts
+/// a call to this function in landing pads in the user code, which in turn
+/// calls the personality function.
+_Unwind_Reason_Code _Unwind_CallPersonality(void *exception_ptr) {
+  struct _Unwind_Exception *exception_object =
+  (struct _Unwind_Exception *)exception_ptr;
+  _LIBUNWIND_TRACE_API("_Unwind_CallPersonality(exception_object=%p)",
+   (void *)exception_object);
+
+  // Reset the selector.
+  __wasm_lpad_context.selector = 0;
+
+  // Call personality function. Wasm does not have two-phase unwinding, so we
+  // only do the cleanup phase.
+  return __gxx_personality_wasm0(
+  1, _UA_SEARCH_PHASE, exception_object->exception_class, exception_object,
+  (struct _Unwind_Context *)&__wasm_lpad_context);
+}
+
+/// Called by __cxa_throw.
+_LIBUNWIND_EXPORT _Unwind_Reason_Code
+_Unwind_RaiseException(_Unwind_Exception *exception_object) {
+  _LIBUNWIND_TRACE_API("_Unwind_RaiseException(exception_object=%p)",
+   (void *)exception_object);
+  // Use Wasm EH's 'throw' instruction.
+  __builtin_wasm_throw(0, exception_object);
+}
+
+/// Called by __cxa_end_catch.
+_LIBUNWIND_EXPORT void
+_Unwind_DeleteException(_Unwind_Exception *exception_object) {
+  _LIBUNWIND_TRACE_API("_Unwind_DeleteException(ex_obj=%p)",
+   (void *)(exception_object));
+  if (exception_object->exception_cleanup != NULL)
+(*exception_object->exception_cleanup)(_URC_FOREIGN_

[clang] [flang][Driver] Support -rpath, -shared, and -static in the frontend (PR #66702)

2023-09-22 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space requested changes to this pull request.

Please re-enable the tests in linker-flags.f90. 

If these options don't work on Windows then we should try to document it. Also, 
tests for `-rpath` can be moved to a dedicated file if we need to disable them 
on a particular platform.

https://github.com/llvm/llvm-project/pull/66702
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 73779bb - [clang] Enable descriptions for --print-supported-extensions (#66715)

2023-09-22 Thread via cfe-commits

Author: Balint Cristian
Date: 2023-09-22T08:43:17+01:00
New Revision: 73779bb2093310bf129017f2f504ec93b1ca4a1d

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

LOG: [clang] Enable descriptions for --print-supported-extensions (#66715)

Enables summary descriptions along with the names of the feature.
Descriptions here are simply looked up via the available llvm tablegen
data.

Added: 


Modified: 
clang/test/Driver/print-supported-extensions.c
clang/tools/driver/cc1_main.cpp
llvm/include/llvm/MC/MCSubtargetInfo.h
llvm/include/llvm/Support/RISCVISAInfo.h
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/include/llvm/TargetParser/ARMTargetParser.h
llvm/lib/Support/RISCVISAInfo.cpp
llvm/lib/TargetParser/AArch64TargetParser.cpp
llvm/lib/TargetParser/ARMTargetParser.cpp
llvm/unittests/Support/RISCVISAInfoTest.cpp
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/Driver/print-supported-extensions.c 
b/clang/test/Driver/print-supported-extensions.c
index 8daf4d8a34b8a60..17894fc0f7ee0b4 100644
--- a/clang/test/Driver/print-supported-extensions.c
+++ b/clang/test/Driver/print-supported-extensions.c
@@ -4,14 +4,20 @@
 // RUN: %if aarch64-registered-target %{ %clang --target=aarch64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
AARCH64 %}
 // AARCH64: All available -march extensions for AArch64
+// AARCH64: NameDescription
+// AARCH64: aes Enable AES support (FEAT_AES, FEAT_PMULL)
 
 // RUN: %if riscv-registered-target %{ %clang --target=riscv64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
RISCV %}
 // RISCV: All available -march extensions for RISC-V
+// RISCV: NameVersion   Description
+// RISCV: i   2.1
 
 // RUN: %if arm-registered-target %{ %clang --target=arm-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix ARM 
%}
 // ARM: All available -march extensions for ARM
+// ARM: NameDescription
+// ARM: crc Enable support for CRC instructions
 
 // RUN: %if x86-registered-target %{ not %clang --target=x86_64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix X86 
%}

diff  --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index f0d7b5c3889dc1f..e9d2c6aad371dbb 100644
--- a/clang/tools/driver/cc1_main.cpp
+++ b/clang/tools/driver/cc1_main.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/LinkAllPasses.h"
+#include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
@@ -198,13 +199,20 @@ static int PrintSupportedExtensions(std::string 
TargetStr) {
   std::unique_ptr TheTargetMachine(
   TheTarget->createTargetMachine(TargetStr, "", "", Options, 
std::nullopt));
   const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
+  const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
+  const llvm::ArrayRef Features =
+MCInfo->getAllProcessorFeatures();
+
+  llvm::StringMap DescMap;
+  for (const llvm::SubtargetFeatureKV &feature : Features)
+DescMap.insert({feature.Key, feature.Desc});
 
   if (MachineTriple.isRISCV())
-llvm::riscvExtensionsHelp();
+llvm::riscvExtensionsHelp(DescMap);
   else if (MachineTriple.isAArch64())
-llvm::AArch64::PrintSupportedExtensions();
+llvm::AArch64::PrintSupportedExtensions(DescMap);
   else if (MachineTriple.isARM())
-llvm::ARM::PrintSupportedExtensions();
+llvm::ARM::PrintSupportedExtensions(DescMap);
   else {
 // The option was already checked in Driver::HandleImmediateArgs,
 // so we do not expect to get here if we are not a supported architecture.

diff  --git a/llvm/include/llvm/MC/MCSubtargetInfo.h 
b/llvm/include/llvm/MC/MCSubtargetInfo.h
index c1533ac8d0059f5..f172a799aa3331c 100644
--- a/llvm/include/llvm/MC/MCSubtargetInfo.h
+++ b/llvm/include/llvm/MC/MCSubtargetInfo.h
@@ -230,10 +230,16 @@ class MCSubtargetInfo {
 return Found != ProcDesc.end() && StringRef(Found->Key) == CPU;
   }
 
+  /// Return processor descriptions.
   ArrayRef getAllProcessorDescriptions() const {
 return ProcDesc;
   }
 
+  /// Return processor features.
+  ArrayRef getAllProcessorFeatures() const {
+return ProcFeatures;
+  }
+
   virtual unsigned getHwMode() const { return 0; }
 
   /// Return the cache size in bytes for the given level of cache.

diff  --git a/llvm/include/llvm/Support/RISCVISAInfo.h 
b/llvm/include/llvm/Support/RISCVISAInfo.h
index 9092fe5c272a994

[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-22 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett closed 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155572: [clang][Interp] Start implementing binary operators for complex types

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

Ping


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

https://reviews.llvm.org/D155572

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


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-22 Thread David Spickett via cfe-commits

DavidSpickett wrote:

If you are doing more contributions you can get commit access by doing 
https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access. Though with 
the switch to Github it's super easy to ask the reviewer to click the merge 
button, so it's not required.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Extend `retcon.once` coroutines lowering to optionally produce a normal result (PR #66333)

2023-09-22 Thread Anton Korobeynikov via cfe-commits

https://github.com/asl resolved https://github.com/llvm/llvm-project/pull/66333
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159351: [Sema] Change order of displayed overloads in diagnostics

2023-09-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

@cor3ntin any suggestions on how to proceed here?

I hope the approach taken in the current patch should already provide 
meaningful and improved results in most cases.
It only affects the diagnostics output, so changing or reverting it should be 
relatively easy in the future.

I'm happy to ask someone from my team to do the detailed code review, but I 
just wanted to make sure the Clang contributors are generally ok with the 
direction here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159351

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


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-22 Thread Sam McCall via cfe-commits

sam-mccall wrote:

Thanks! This will fix the double-slash issue (despite the name, `add_dots` 
normalizes those).

symlinks and progra~1 mean normalization based on actual filesystem access, and 
choosing between multiple forms that are in some sense equally valid.

I don't think I'm opposed if someone wants to take a shot at solving that (we 
can *afford* to do IO here), but it's definitely a more complicated idea.

https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 01d3045 - [clangd] Allow --query-driver to match a dot-normalized form of the path (#66757)

2023-09-22 Thread via cfe-commits

Author: Sam McCall
Date: 2023-09-22T11:09:18+02:00
New Revision: 01d3045d1261c72abcf9cc1071be87434cf7086d

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

LOG: [clangd] Allow --query-driver to match a dot-normalized form of the path 
(#66757)

(In addition to the un-normalized form, so this is back-compatible)

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 88df5b04ccb09f3..74bae786425c829 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -343,7 +343,13 @@ extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", InputArgs.Lang);
 
-  if (!QueryDriverRegex.match(Driver)) {
+  // If driver was "../foo" then having to allowlist "/path/a/../foo" rather
+  // than "/path/foo" is absurd.
+  // Allow either to match the allowlist, then proceed with "/path/a/../foo".
+  // This was our historical behavior, and it *could* resolve to something 
else.
+  llvm::SmallString<256> NoDots(Driver);
+  llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);
+  if (!QueryDriverRegex.match(Driver) && !QueryDriverRegex.match(NoDots)) {
 vlog("System include extraction: not allowed driver {0}", Driver);
 return std::nullopt;
   }



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


[clang] docs: Fix misplaced apostrophe (PR #67103)

2023-09-22 Thread via cfe-commits

https://github.com/Alcaro created 
https://github.com/llvm/llvm-project/pull/67103

None

>From 59f00d06056ff88acf014c339d64ac3c3ec85466 Mon Sep 17 00:00:00 2001
From: Alcaro 
Date: Fri, 22 Sep 2023 11:08:56 +0200
Subject: [PATCH] docs: Fix misplaced apostrophe

---
 clang/include/clang/Basic/AttrDocs.td | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c3fe7cea29afbf1..b13baa46754cfd4 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1163,7 +1163,7 @@ caveats to this use of name mangling:
 * The ``overloadable`` attribute has almost no meaning when used in C++,
   because names will already be mangled and functions are already overloadable.
   However, when an ``overloadable`` function occurs within an ``extern "C"``
-  linkage specification, it's name *will* be mangled in the same way as it
+  linkage specification, its name *will* be mangled in the same way as it
   would in C.
 
 For the purpose of backwards compatibility, at most one function with the same

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


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall closed 
https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Serialization] Do less redundant work computing affecting module maps (PR #66933)

2023-09-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall closed 
https://github.com/llvm/llvm-project/pull/66933
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0f05096 - [Serialization] Do less redundant work computing affecting module maps (#66933)

2023-09-22 Thread via cfe-commits

Author: Sam McCall
Date: 2023-09-22T11:23:11+02:00
New Revision: 0f05096540bc90125df47983d7013dd440617055

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

LOG: [Serialization] Do less redundant work computing affecting module maps 
(#66933)

We're traversing the same chains of module ancestors and include
locations repeatedly, despite already populating sets that can detect
it!

This is a problem because translateFile() is expensive. I think we can
avoid it entirely, but this seems like an improvement either way.

I removed a callback indirection rather than giving it a more
complicated
signature, and accordingly renamed the lambdas to be more concrete.

Added: 


Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 65bee806d2c5571..216ca94111e156b 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -163,8 +163,6 @@ namespace {
 
 std::set GetAffectingModuleMaps(const Preprocessor &PP,
Module *RootModule) {
-  std::set ModuleMaps{};
-  std::set ProcessedModules;
   SmallVector ModulesToProcess{RootModule};
 
   const HeaderSearch &HS = PP.getHeaderSearchInfo();
@@ -195,42 +193,45 @@ std::set GetAffectingModuleMaps(const 
Preprocessor &PP,
   const ModuleMap &MM = HS.getModuleMap();
   SourceManager &SourceMgr = PP.getSourceManager();
 
-  auto ForIncludeChain = [&](FileEntryRef F,
- llvm::function_ref CB) {
-CB(F);
+  std::set ModuleMaps{};
+  auto CollectIncludingModuleMaps = [&](FileEntryRef F) {
+if (!ModuleMaps.insert(F).second)
+  return;
 FileID FID = SourceMgr.translateFile(F);
 SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
 // The include location of inferred module maps can point into the header
 // file that triggered the inferring. Cut off the walk if that's the case.
 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) 
{
   FID = SourceMgr.getFileID(Loc);
-  CB(*SourceMgr.getFileEntryRefForID(FID));
+  if (!ModuleMaps.insert(*SourceMgr.getFileEntryRefForID(FID)).second)
+break;
   Loc = SourceMgr.getIncludeLoc(FID);
 }
   };
 
-  auto ProcessModuleOnce = [&](const Module *M) {
-for (const Module *Mod = M; Mod; Mod = Mod->Parent)
-  if (ProcessedModules.insert(Mod).second) {
-auto Insert = [&](FileEntryRef F) { ModuleMaps.insert(F); };
-// The containing module map is affecting, because it's being pointed
-// into by Module::DefinitionLoc.
-if (auto ModuleMapFile = MM.getContainingModuleMapFile(Mod))
-  ForIncludeChain(*ModuleMapFile, Insert);
-// For inferred modules, the module map that allowed inferring is not 
in
-// the include chain of the virtual containing module map file. It did
-// affect the compilation, though.
-if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
-  ForIncludeChain(*ModuleMapFile, Insert);
-  }
+  std::set ProcessedModules;
+  auto CollectIncludingMapsFromAncestors = [&](const Module *M) {
+for (const Module *Mod = M; Mod; Mod = Mod->Parent) {
+  if (!ProcessedModules.insert(Mod).second)
+break;
+  // The containing module map is affecting, because it's being pointed
+  // into by Module::DefinitionLoc.
+  if (auto ModuleMapFile = MM.getContainingModuleMapFile(Mod))
+CollectIncludingModuleMaps(*ModuleMapFile);
+  // For inferred modules, the module map that allowed inferring is not in
+  // the include chain of the virtual containing module map file. It did
+  // affect the compilation, though.
+  if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
+CollectIncludingModuleMaps(*ModuleMapFile);
+}
   };
 
   for (const Module *CurrentModule : ModulesToProcess) {
-ProcessModuleOnce(CurrentModule);
+CollectIncludingMapsFromAncestors(CurrentModule);
 for (const Module *ImportedModule : CurrentModule->Imports)
-  ProcessModuleOnce(ImportedModule);
+  CollectIncludingMapsFromAncestors(ImportedModule);
 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
-  ProcessModuleOnce(UndeclaredModule);
+  CollectIncludingMapsFromAncestors(UndeclaredModule);
   }
 
   return ModuleMaps;



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


[clang] b2bbf69 - [clang][Sema][NFC] _or_null -> _if_present

2023-09-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-09-22T11:23:18+02:00
New Revision: b2bbf6947cae64934ff35a6a467bad34c1096155

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

LOG: [clang][Sema][NFC] _or_null -> _if_present

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index cc98713241395ec..090a54eedaa07d0 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -1050,10 +1050,10 @@ static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl 
*D,
   FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
 if (!AL.isArgExpr(0))
   return nullptr;
-auto *F = dyn_cast_or_null(AL.getArgAsExpr(0));
+auto *F = dyn_cast_if_present(AL.getArgAsExpr(0));
 if (!F)
   return nullptr;
-return dyn_cast_or_null(F->getFoundDecl());
+return dyn_cast_if_present(F->getFoundDecl());
   }();
 
   if (!AttrFD || !AttrFD->getBuiltinID(true)) {
@@ -1452,7 +1452,7 @@ static void handlePreferredName(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   if (!T.hasQualifiers() && T->isTypedefNameType()) {
 // Find the template name, if this type names a template specialization.
 const TemplateDecl *Template = nullptr;
-if (const auto *CTSD = dyn_cast_or_null(
+if (const auto *CTSD = 
dyn_cast_if_present(
 T->getAsCXXRecordDecl())) {
   Template = CTSD->getSpecializedTemplate();
 } else if (const auto *TST = T->getAs()) {
@@ -2643,10 +2643,11 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
   bool IsUnavailable = AL.getUnavailableLoc().isValid();
   bool IsStrict = AL.getStrictLoc().isValid();
   StringRef Str;
-  if (const auto *SE = dyn_cast_or_null(AL.getMessageExpr()))
+  if (const auto *SE = dyn_cast_if_present(AL.getMessageExpr()))
 Str = SE->getString();
   StringRef Replacement;
-  if (const auto *SE = 
dyn_cast_or_null(AL.getReplacementExpr()))
+  if (const auto *SE =
+  dyn_cast_if_present(AL.getReplacementExpr()))
 Replacement = SE->getString();
 
   if (II->isStr("swift")) {
@@ -2863,14 +2864,14 @@ static void handleExternalSourceSymbolAttr(Sema &S, 
Decl *D,
 return;
 
   StringRef Language;
-  if (const auto *SE = dyn_cast_or_null(AL.getArgAsExpr(0)))
+  if (const auto *SE = dyn_cast_if_present(AL.getArgAsExpr(0)))
 Language = SE->getString();
   StringRef DefinedIn;
-  if (const auto *SE = dyn_cast_or_null(AL.getArgAsExpr(1)))
+  if (const auto *SE = dyn_cast_if_present(AL.getArgAsExpr(1)))
 DefinedIn = SE->getString();
   bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
   StringRef USR;
-  if (const auto *SE = dyn_cast_or_null(AL.getArgAsExpr(3)))
+  if (const auto *SE = dyn_cast_if_present(AL.getArgAsExpr(3)))
 USR = SE->getString();
 
   D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
@@ -6148,7 +6149,7 @@ static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
   const auto *Method = cast(D);
 
   const DeclContext *DC = Method->getDeclContext();
-  if (const auto *PDecl = dyn_cast_or_null(DC)) {
+  if (const auto *PDecl = dyn_cast_if_present(DC)) {
 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
   << 0;
 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);



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


[clang] 3f78d6a - [dataflow] Parse formulas from text (#66424)

2023-09-22 Thread via cfe-commits

Author: Sam McCall
Date: 2023-09-22T11:24:24+02:00
New Revision: 3f78d6ab146874d20144f9f5fcbb894931279c7d

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

LOG: [dataflow] Parse formulas from text (#66424)

My immediate use for this is not in checked-in code, but rather the
ability to plug printed flow conditions (from analysis logs) back into
sat solver unittests to reproduce slowness.

It does allow simplifying some of the existing solver tests, though.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/Arena.h
clang/include/clang/Analysis/FlowSensitive/Formula.h
clang/lib/Analysis/FlowSensitive/Arena.cpp
clang/lib/Analysis/FlowSensitive/Formula.cpp
clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
clang/unittests/Analysis/FlowSensitive/SolverTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/Arena.h 
b/clang/include/clang/Analysis/FlowSensitive/Arena.h
index 373697dc7379c53..4e07053aae1af53 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Arena.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Arena.h
@@ -11,6 +11,7 @@
 #include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/StringRef.h"
 #include 
 
 namespace clang::dataflow {
@@ -109,6 +110,10 @@ class Arena {
 return makeAtomRef(Value ? True : False);
   }
 
+  // Parses a formula from its textual representation.
+  // This may refer to atoms that were not produced by makeAtom() yet!
+  llvm::Expected parseFormula(llvm::StringRef);
+
   /// Returns a new atomic boolean variable, distinct from any other.
   Atom makeAtom() { return static_cast(NextAtom++); };
 

diff  --git a/clang/include/clang/Analysis/FlowSensitive/Formula.h 
b/clang/include/clang/Analysis/FlowSensitive/Formula.h
index 64fe8f5b630a0f7..5126fda8440 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Formula.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Formula.h
@@ -18,7 +18,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
-#include 
 
 namespace clang::dataflow {
 

diff  --git a/clang/lib/Analysis/FlowSensitive/Arena.cpp 
b/clang/lib/Analysis/FlowSensitive/Arena.cpp
index a12da2d9b555eb7..b043a52b609df36 100644
--- a/clang/lib/Analysis/FlowSensitive/Arena.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Arena.cpp
@@ -7,7 +7,10 @@
 
//===--===//
 
 #include "clang/Analysis/FlowSensitive/Arena.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/Support/Error.h"
+#include 
 
 namespace clang::dataflow {
 
@@ -95,4 +98,96 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatSpaces = [&] { In = In.ltrim(' '); };
+  EatSpaces();
+
+  if (In.consume_front("!")) {
+if (auto *Arg = parse(A, In))
+  return &A.makeNot(*Arg);
+return nullptr;
+  }
+
+  if (In.consume_front("(")) {
+auto *Arg1 = parse(A, In);
+if (!Arg1)
+  return nullptr;
+
+EatSpaces();
+decltype(&Arena::makeOr) Op;
+if (In.consume_front("|"))
+  Op = &Arena::makeOr;
+else if (In.consume_front("&"))
+  Op = &Arena::makeAnd;
+else if (In.consume_front("=>"))
+  Op = &Arena::makeImplies;
+else if (In.consume_front("="))
+  Op = &Arena::makeEquals;
+else
+  return nullptr;
+
+auto *Arg2 = parse(A, In);
+if (!Arg2)
+  return nullptr;
+
+EatSpaces();
+if (!In.consume_front(")"))
+  return nullptr;
+
+return &(A.*Op)(*Arg1, *Arg2);
+  }
+
+  // For now, only support unnamed variables V0, V1 etc.
+  // FIXME: parse e.g. "X" by allocating an atom and storing a name somewhere.
+  if (In.consume_front("V")) {
+std::underlying_type_t At;
+if (In.consumeInteger(10, At))
+  return nullptr;
+return &A.makeAtomRef(static_cast(At));
+  }
+
+  if (In.consume_front("true"))
+return &A.makeLiteral(true);
+  if (In.consume_front("false"))
+return &A.makeLiteral(false);
+
+  return nullptr;
+}
+
+class FormulaParseError : public llvm::ErrorInfo {
+  std::string Formula;
+  unsigned Offset;
+
+public:
+  static char ID;
+  FormulaParseError(llvm::StringRef Formula, unsigned Offset)
+  : Formula(Formula), Offset(Offset) {}
+
+  void log(raw_ostream &OS) const override {
+OS << "bad formula at offset " << Offset << "\n";
+OS << Formula << "\n";
+OS.indent(Offset) << "^";
+  }
+
+  std::error_code convertToErrorCode() const override {
+return std::make_error_code(std::errc::invalid_argument);
+  }
+};
+
+char FormulaPa

[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall closed 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [include-cleaner] Respect the UsingShadowDecl when find headers for ambiguous std symbols. (PR #66485)

2023-09-22 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet edited 
https://github.com/llvm/llvm-project/pull/66485
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [include-cleaner] Respect the UsingShadowDecl when find headers for ambiguous std symbols. (PR #66485)

2023-09-22 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet approved this pull request.

thanks, lgtm!

https://github.com/llvm/llvm-project/pull/66485
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [include-cleaner] Respect the UsingShadowDecl when find headers for ambiguous std symbols. (PR #66485)

2023-09-22 Thread kadir çetinkaya via cfe-commits


@@ -587,6 +588,36 @@ TEST_F(HeadersForSymbolTest, AmbiguousStdSymbols) {
   }
 }
 
+TEST_F(HeadersForSymbolTest, AmbiguousStdSymbolsUsingShadow) {

kadircet wrote:

might be easier to test this in AnalysisTest, rather than writing a new 
ASTVisitor, but up to you.

https://github.com/llvm/llvm-project/pull/66485
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Link Flang runtime on Solaris (PR #65644)

2023-09-22 Thread Rainer Orth via cfe-commits

rorth wrote:

The different behaviour can easily be seen since Solaris `clang` supports 
linker selection at compile time:
```
$ clang -r -o hello-r.o hello.o -fuse-ld=gld
/usr/gnu/bin/ld: warning: cannot find entry symbol _start; not setting start 
address
$ clang -r -o hello-r.o hello.o
ld: fatal: option '-Bdynamic' is incompatible with building a relocatable object
ld: fatal: option '-e _start' is incompatible with building a relocatable object
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
I'll either fix the Solaris driver code not to pass `-Bdynamic -e _start` with 
`-r` or do a full comparison of `Gnu.cpp` and `Solaris.cpp` to check for 
undesirable differences.

However, for the patch at hand this is moot while
```
$ flang-new -r -o hello-r.o hello.o
flang-new: error: unknown argument: '-r'
```

I wonder how to proceed with the patch at hand.

https://github.com/llvm/llvm-project/pull/65644
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperand for inline asm (PR #67018)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD edited https://github.com/llvm/llvm-project/pull/67018
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67018)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD edited https://github.com/llvm/llvm-project/pull/67018
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67018)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD edited https://github.com/llvm/llvm-project/pull/67018
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67109)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD created https://github.com/llvm/llvm-project/pull/67109

This PR is based on #67018. This PR fixes compilation issue for RVV tuple types 
as InputOperands for inline asm.

---

Currently the compiler generates https://godbolt.org/z/djebPfqxf for tuple type 
as inline asm inputs and cannot be code generated successfully 
https://godbolt.org/z/na7T19Krc. This PR fixes Clang by generating 
https://godbolt.org/z/MsovoxbY9 instead, which can be successfully handled by 
the back-end.

A follow-up PR will handle interactions of RVV tuple type InputOperands and 
OutputOperands correctly.

>From a26eb9fe0c09fc0fd504d261874630d8b5edae26 Mon Sep 17 00:00:00 2001
From: eopXD 
Date: Thu, 21 Sep 2023 06:34:57 -0700
Subject: [PATCH 1/3] [Clang][RISCV] Handle RVV tuple types correctly as
 OutputOperand for inline asm

The RVV tuple type maps to an aggregate type with homogeneous scalable
vectors. EmitAsmStmt does not handle this correctly and this commit
attempts to fix it.

Expressing the type as a structure in inline asm calls will complicate
the current code base, so instead, the return type is set to be
a single scalable vector, then reconstructed with `vector.extract` and
`insertvalue`.

A follow-up commit will deal with details when associated with
InputOperands.
---
 clang/lib/CodeGen/CGStmt.cpp  | 69 ++-
 .../rvv-inline-asm.c  | 41 +++
 2 files changed, 108 insertions(+), 2 deletions(-)
 create mode 100644 
clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-asm.c

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 6674aa2409a5947..948539ea546084e 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PrettyStackTrace.h"
@@ -29,10 +30,13 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/Assumptions.h"
+#include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/SaveAndRestore.h"
 #include 
 
@@ -2392,6 +2396,26 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
+  } else if (TruncTy->isStructTy() && ResultRegQualTys[i]->isRVVType()) {
+auto *STy = cast(TruncTy);
+auto *VTy = cast(STy->getElementType(0));
+
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   "Must be dealing with RVV tuple type");
+
+unsigned MinElts = VTy->getElementCount().getKnownMinValue();
+llvm::Value *StructValue = llvm::PoisonValue::get(STy);
+
+for (unsigned Idx = 0, TupleSize = STy->getNumElements();
+ Idx != TupleSize; ++Idx) {
+  llvm::Value *IdxValue =
+  llvm::ConstantInt::get(CGM.Int64Ty, Idx * MinElts);
+  llvm::Value *SubVec = Builder.CreateExtractVector(VTy, Tmp, 
IdxValue);
+
+  StructValue = Builder.CreateInsertValue(StructValue, SubVec, Idx);
+}
+
+Tmp = StructValue;
   }
 }
 
@@ -2399,7 +2423,13 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 // ResultTypeRequiresCast elements correspond to the first
 // ResultTypeRequiresCast.size() elements of RegResults.
 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
-  unsigned Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
+  unsigned Size;
+  if (ResultRegQualTys[i]->isRVVType() && TruncTy->isStructTy()) {
+Size = cast(
+   cast(TruncTy)->getElementType(0))
+   ->getScalarSizeInBits();
+  } else
+Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
   Address A = Dest.getAddress(CGF).withElementType(ResultRegTypes[i]);
   if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
 Builder.CreateStore(Tmp, A);
@@ -2524,11 +2554,32 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   ResultRegIsFlagReg.push_back(IsFlagReg);
 
   llvm::Type *Ty = ConvertTypeForMem(QTy);
+  ResultTruncRegTypes.push_back(Ty);
+
+  // Expressing the type as a structure in inline asm calls will complicate
+  // the current code case, so instead, the return type is set to be a
+  // single scalable vector, then reconstructed with `vector.extract` and
+  // `insertvalue`. The type is derived here, and the reconstruction is 
done
+  // under EmitAsmStores.
+  if (QTy->isRVVType() && isa(Ty)) {
+// F

[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67109)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This PR is based on #67018. This PR fixes compilation issue for RVV 
tuple types as InputOperands for inline asm.

---

Currently the compiler generates https://godbolt.org/z/djebPfqxf for tuple type 
as inline asm inputs and cannot be code generated successfully 
https://godbolt.org/z/na7T19Krc. This PR fixes Clang by generating 
https://godbolt.org/z/MsovoxbY9 instead, which can be successfully handled by 
the back-end.

A follow-up PR will handle interactions of RVV tuple type InputOperands and 
OutputOperands correctly.

---
Full diff: https://github.com/llvm/llvm-project/pull/67109.diff


2 Files Affected:

- (modified) clang/lib/CodeGen/CGStmt.cpp (+101-6) 
- (added) clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-asm.c 
(+54) 


``diff
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 6674aa2409a5947..4a2bdde56c5704e 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PrettyStackTrace.h"
@@ -29,10 +30,13 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/Assumptions.h"
+#include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/SaveAndRestore.h"
 #include 
 
@@ -2392,6 +2396,26 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
+  } else if (TruncTy->isStructTy() && ResultRegQualTys[i]->isRVVType()) {
+auto *STy = cast(TruncTy);
+auto *VTy = cast(STy->getElementType(0));
+
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   "Must be dealing with RVV tuple type");
+
+unsigned MinElts = VTy->getElementCount().getKnownMinValue();
+llvm::Value *StructValue = llvm::PoisonValue::get(STy);
+
+for (unsigned Idx = 0, TupleSize = STy->getNumElements();
+ Idx != TupleSize; ++Idx) {
+  llvm::Value *IdxValue =
+  llvm::ConstantInt::get(CGM.Int64Ty, Idx * MinElts);
+  llvm::Value *SubVec = Builder.CreateExtractVector(VTy, Tmp, 
IdxValue);
+
+  StructValue = Builder.CreateInsertValue(StructValue, SubVec, Idx);
+}
+
+Tmp = StructValue;
   }
 }
 
@@ -2399,7 +2423,13 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 // ResultTypeRequiresCast elements correspond to the first
 // ResultTypeRequiresCast.size() elements of RegResults.
 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
-  unsigned Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
+  unsigned Size;
+  if (ResultRegQualTys[i]->isRVVType() && TruncTy->isStructTy()) {
+Size = cast(
+   cast(TruncTy)->getElementType(0))
+   ->getScalarSizeInBits();
+  } else
+Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
   Address A = Dest.getAddress(CGF).withElementType(ResultRegTypes[i]);
   if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
 Builder.CreateStore(Tmp, A);
@@ -2524,11 +2554,32 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   ResultRegIsFlagReg.push_back(IsFlagReg);
 
   llvm::Type *Ty = ConvertTypeForMem(QTy);
+  ResultTruncRegTypes.push_back(Ty);
+
+  // Expressing the type as a structure in inline asm calls will complicate
+  // the current code case, so instead, the return type is set to be a
+  // single scalable vector, then reconstructed with `vector.extract` and
+  // `insertvalue`. The type is derived here, and the reconstruction is 
done
+  // under EmitAsmStores.
+  if (QTy->isRVVType() && isa(Ty)) {
+// Flatten the structure into a single ScalableVectorType
+auto *STy = cast(Ty);
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   isa(STy->getElementType(0)) &&
+   "Dealing with RVV tuple (aggregate with homogeneous scalable "
+   "vectors");
+
+auto *VecTy = cast(STy->getElementType(0));
+
+Ty = llvm::ScalableVectorType::get(VecTy->getScalarType(),
+   STy->getNumElements() *
+   VecTy->getMinNumElements());
+  }
+
   const bool RequiresCast = Info.allowsRegister() &&
   (getTargetHooks().isScalarizableAsmOperand(*this, Ty) ||
Ty->isAggregateType());
 

[clang] 10217b9 - docs: Fix misplaced apostrophe (#67103)

2023-09-22 Thread via cfe-commits

Author: Alcaro
Date: 2023-09-22T11:58:32+02:00
New Revision: 10217b9d9b4814eb086cffd7f008cb72967cd739

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

LOG: docs: Fix misplaced apostrophe (#67103)

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c3fe7cea29afbf1..b13baa46754cfd4 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1163,7 +1163,7 @@ caveats to this use of name mangling:
 * The ``overloadable`` attribute has almost no meaning when used in C++,
   because names will already be mangled and functions are already overloadable.
   However, when an ``overloadable`` function occurs within an ``extern "C"``
-  linkage specification, it's name *will* be mangled in the same way as it
+  linkage specification, its name *will* be mangled in the same way as it
   would in C.
 
 For the purpose of backwards compatibility, at most one function with the same



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


[clang] docs: Fix misplaced apostrophe (PR #67103)

2023-09-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr closed 
https://github.com/llvm/llvm-project/pull/67103
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits

https://github.com/jchlanda resolved 
https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits

https://github.com/jchlanda updated 
https://github.com/llvm/llvm-project/pull/66496

>From 9c8caed3c8def15ccdbfdf831f36d0befed1fc84 Mon Sep 17 00:00:00 2001
From: Jakub Chlanda 
Date: Fri, 15 Sep 2023 12:08:04 +0100
Subject: [PATCH 1/4] [NVPTX] Add support for maxclusterrank in launch_bounds

Since SM_90 CUDA supports specifying additional argument to the
launch_bounds attribute: maxBlocksPerCluster, to express the maximum
number of CTAs that can be part of the cluster. See:
https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#cluster-dimension-directives-maxclusterrank
and
https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#launch-bounds
for details.
---
 clang/include/clang/Basic/Attr.td |  3 +-
 .../clang/Basic/DiagnosticSemaKinds.td|  4 +
 clang/include/clang/Sema/Sema.h   |  5 +-
 clang/lib/CodeGen/Targets/NVPTX.cpp   | 12 ++-
 clang/lib/Parse/ParseOpenMP.cpp   |  3 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 46 +--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 10 ++-
 clang/test/CodeGenCUDA/launch-bounds.cu   | 69 
 clang/test/SemaCUDA/launch_bounds.cu  |  4 +-
 clang/test/SemaCUDA/launch_bounds_sm_90.cu| 45 +++
 llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp | 79 +--
 llvm/lib/Target/NVPTX/NVPTXUtilities.cpp  |  4 +
 llvm/lib/Target/NVPTX/NVPTXUtilities.h|  1 +
 13 files changed, 227 insertions(+), 58 deletions(-)
 create mode 100644 clang/test/SemaCUDA/launch_bounds_sm_90.cu

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index c95db7e8049d47a..3c51261bd3eb081 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1267,7 +1267,8 @@ def CUDAInvalidTarget : InheritableAttr {
 
 def CUDALaunchBounds : InheritableAttr {
   let Spellings = [GNU<"launch_bounds">, Declspec<"__launch_bounds__">];
-  let Args = [ExprArgument<"MaxThreads">, ExprArgument<"MinBlocks", 1>];
+  let Args = [ExprArgument<"MaxThreads">, ExprArgument<"MinBlocks", 1>,
+  ExprArgument<"MaxBlocks", 1>];
   let LangOpts = [CUDA];
   let Subjects = SubjectList<[ObjCMethod, FunctionLike]>;
   // An AST node is created for this attribute, but is not used by other parts
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..088e3a45c7babba 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11836,6 +11836,10 @@ def err_sycl_special_type_num_init_method : Error<
   "types with 'sycl_special_class' attribute must have one and only one 
'__init' "
   "method defined">;
 
+def warn_cuda_maxclusterrank_sm_90 : Warning<
+  "maxclusterrank requires sm_90 or higher, CUDA arch provided: %0, ignoring "
+  "%1 attribute">, InGroup;
+
 def err_bit_int_bad_size : Error<"%select{signed|unsigned}0 _BitInt must "
  "have a bit size of at least %select{2|1}0">;
 def err_bit_int_max_size : Error<"%select{signed|unsigned}0 _BitInt of bit "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 47379e00a7445e3..dca7b66da3796d9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11051,12 +11051,13 @@ class Sema final {
   /// Create an CUDALaunchBoundsAttr attribute.
   CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
Expr *MaxThreads,
-   Expr *MinBlocks);
+   Expr *MinBlocks,
+   Expr *MaxBlocks);
 
   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
   /// declaration.
   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
-   Expr *MaxThreads, Expr *MinBlocks);
+   Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
 
   /// AddModeAttr - Adds a mode attribute to a particular declaration.
   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo 
*Name,
diff --git a/clang/lib/CodeGen/Targets/NVPTX.cpp 
b/clang/lib/CodeGen/Targets/NVPTX.cpp
index 0d4bbd795648008..64d019a10514d60 100644
--- a/clang/lib/CodeGen/Targets/NVPTX.cpp
+++ b/clang/lib/CodeGen/Targets/NVPTX.cpp
@@ -296,8 +296,8 @@ void CodeGenModule::handleCUDALaunchBoundsAttr(
 NVPTXTargetCodeGenInfo::addNVVMMetadata(F, "maxntidx",
 MaxThreads.getExtValue());
 
-  // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
-  // not specified in __launch_bounds__ or if the user specified a 0 value,
+  // min and max blocks is an optional argument for CUDALaunchBoundsAttr. If it
+  // was not specified in __launch_bounds__ or if the user specified

[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/66947

>From 00ef242c40dd453157ee3b31e367fd6240d68a5a Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Wed, 20 Sep 2023 21:19:03 +0200
Subject: [PATCH 1/2] [Driver] Fix detection of libc++ with empty sysroot.

b1e3cd1d79443603dc003441e07cdd8d30bb7f26 dropped the leading slash here,
presumably unintentionally.

(I don't understand Driver well enough to know how/where this is supposed
to be tested, but it broke clangd on any project that uses the
system-installed -stdlib=libc++ on a standard debian install)
---
 clang/lib/Driver/ToolChains/Gnu.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index e909549d20708fe..f2fd85021a777b4 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -3139,11 +3139,11 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
   // not be found at ../include/c++ but it likely to be found at
   // one of the following two locations:
   SmallString<128> UsrLocalIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
+  llvm::sys::path::append(UsrLocalIncludeDir, "/usr", "local", "include");
   if (AddIncludePath(UsrLocalIncludeDir))
 return;
   SmallString<128> UsrIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrIncludeDir, "usr", "include");
+  llvm::sys::path::append(UsrIncludeDir, "/usr", "include");
   if (AddIncludePath(UsrIncludeDir))
 return;
 }

>From a7f9a86ac30bcb93b255e9dd6f4b1f27bb99c502 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Fri, 22 Sep 2023 12:03:39 +0200
Subject: [PATCH 2/2] use / locally for default sysroot, add test

---
 clang/lib/Driver/ToolChains/Gnu.cpp  |  6 ++--
 clang/unittests/Driver/ToolChainTest.cpp | 46 
 2 files changed, 50 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index f2fd85021a777b4..61f5100f1385a13 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -3100,6 +3100,8 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const {
   const Driver &D = getDriver();
   std::string SysRoot = computeSysRoot();
+  if (SysRoot.empty())
+SysRoot = llvm::sys::path::get_separator();
 
   auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
 std::string Version = detectLibcxxVersion(Path);
@@ -3139,11 +3141,11 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
   // not be found at ../include/c++ but it likely to be found at
   // one of the following two locations:
   SmallString<128> UsrLocalIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrLocalIncludeDir, "/usr", "local", "include");
+  llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
   if (AddIncludePath(UsrLocalIncludeDir))
 return;
   SmallString<128> UsrIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrIncludeDir, "/usr", "include");
+  llvm::sys::path::append(UsrIncludeDir, "usr", "include");
   if (AddIncludePath(UsrIncludeDir))
 return;
 }
diff --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index ae567abb81a9bb4..85beea4e94ca252 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -19,10 +19,12 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -316,6 +318,50 @@ TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
   }
 }
 
+MATCHER_P(jobHasArgs, Substr, "") {
+  const driver::Command &C = arg;
+  std::string Args = "";
+  llvm::ListSeparator Sep(" ");
+  for (const char *Arg : C.getArguments()) {
+Args += Sep;
+Args += Arg;
+  }
+  if (llvm::StringRef(Args).contains(Substr))
+return true;
+  *result_listener << "whose args are '" << Args << "'";
+  return false;
+}
+
+TEST(ToolChainTest, VFSGnuLibcxxPathNoSysroot) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  const char *EmptyFiles[] = {
+  "foo.cpp",
+  "/bin/clang",
+  "/usr/include/c++/v1/cstdio",
+  };
+
+  for (const char *Path : EmptyFiles)
+InMemoryFileSystem->addFile(Path, 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  

[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-22 Thread Sam McCall via cfe-commits

sam-mccall wrote:

> I just meant to change [...] It's a local fix, but all the code here is 
> pretty inconsistent anyway, so I don't feel too bad about it.

Oops, of course. Done & I worked out the testing.

https://github.com/llvm/llvm-project/pull/66947
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits


@@ -5607,6 +5607,21 @@ bool Sema::CheckRegparmAttr(const ParsedAttr &AL, 
unsigned &numParams) {
   return false;
 }
 
+// Helper to get CudaArch.
+static CudaArch getCudaArch(const TargetInfo &TI) {

jchlanda wrote:

Is that the kind of thing you had in mind:
```diff
diff --git a/clang/lib/Basic/Targets/NVPTX.h b/clang/lib/Basic/Targets/NVPTX.h
index 6fa0b8df97d7..20d76b702a94 100644
--- a/clang/lib/Basic/Targets/NVPTX.h
+++ b/clang/lib/Basic/Targets/NVPTX.h
@@ -181,6 +181,8 @@ public:

   bool hasBitIntType() const override { return true; }
   bool hasBFloat16Type() const override { return true; }
+
+  CudaArch getGPU() const { return GPU; }
 };
 } // namespace targets
 } // namespace clang
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index c4ecaec7728b..636bb0694d36 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -10,6 +10,7 @@
 //
 
//===--===//

+#include "../Basic/Targets/NVPTX.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTMutationListener.h"
@@ -5609,17 +5610,7 @@ bool Sema::CheckRegparmAttr(const ParsedAttr &AL, 
unsigned &numParams) {

 // Helper to get CudaArch.
 static CudaArch getCudaArch(const TargetInfo &TI) {
-  if (!TI.hasFeature("ptx")) {
-return CudaArch::UNKNOWN;
-  }
-  for (const auto &Feature : TI.getTargetOpts().FeatureMap) {
-if (Feature.getValue()) {
-  CudaArch Arch = StringToCudaArch(Feature.getKey());
-  if (Arch != CudaArch::UNKNOWN)
-return Arch;
-}
-  }
-  return CudaArch::UNKNOWN;
+  return static_cast(&TI)->getGPU();
 }

 // Checks whether an argument of launch_bounds attribute is
```

https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits


@@ -11836,6 +11836,10 @@ def err_sycl_special_type_num_init_method : Error<
   "types with 'sycl_special_class' attribute must have one and only one 
'__init' "
   "method defined">;
 
+def warn_cuda_maxclusterrank_sm_90 : Warning<
+  "maxclusterrank requires sm_90 or higher, CUDA arch provided: %0, ignoring "
+  "%1 attribute">, InGroup;

jchlanda wrote:

The whole thing, this is analogous to how we currently handle:
```
__launch_bounds__(128, -2)
```

we issue a warning:
```
/home/dev/llvm/clang/test/SemaCUDA/launch_bounds_running_test.cu:5:24: warning: 
'launch_bounds' attribute parameter 1 is negative and will be ignored 
[-Wcuda-compat]
5 | __launch_bounds__(128, -2) void Test2Args(void);
  |^~
/home/dev/llvm/clang/test/SemaCUDA/Inputs/cuda.h:14:61: note: expanded from 
macro '__launch_bounds__'
   14 | #define __launch_bounds__(...) 
__attribute__((launch_bounds(__VA_ARGS__)))
  | ^~~
1 warning generated when compiling for host.
```
vs max cluster rank:
```
/home/dev/llvm/clang/test/SemaCUDA/launch_bounds_running_test.cu:5:27: warning: 
'launch_bounds' attribute parameter 2 is negative and will be ignored 
[-Wcuda-compat]
5 | __launch_bounds__(128, 2, -8) void Test2Args(void);
  |   ^~
/home/dev/llvm/clang/test/SemaCUDA/Inputs/cuda.h:14:61: note: expanded from 
macro '__launch_bounds__'
   14 | #define __launch_bounds__(...) 
__attribute__((launch_bounds(__VA_ARGS__)))
  | ^~~
1 warning generated when compiling for host.
```

and the resulting asm contains neither of the directives. 

https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits


@@ -537,59 +537,46 @@ void NVPTXAsmPrinter::emitKernelFunctionDirectives(const 
Function &F,
raw_ostream &O) const {
   // If the NVVM IR has some of reqntid* specified, then output
   // the reqntid directive, and set the unspecified ones to 1.
-  // If none of reqntid* is specified, don't output reqntid directive.
-  unsigned reqntidx, reqntidy, reqntidz;
-  bool specified = false;
-  if (!getReqNTIDx(F, reqntidx))
-reqntidx = 1;
-  else
-specified = true;
-  if (!getReqNTIDy(F, reqntidy))
-reqntidy = 1;
-  else
-specified = true;
-  if (!getReqNTIDz(F, reqntidz))
-reqntidz = 1;
-  else
-specified = true;
-
-  if (specified)
-O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
+  // If none of Reqntid* is specified, don't output reqntid directive.
+  unsigned Reqntidx, Reqntidy, Reqntidz;
+  Reqntidx = Reqntidy = Reqntidz = 1;
+  bool ReqSpecified = false;
+  ReqSpecified |= getReqNTIDx(F, Reqntidx);
+  ReqSpecified |= getReqNTIDy(F, Reqntidy);
+  ReqSpecified |= getReqNTIDz(F, Reqntidz);
+
+  if (ReqSpecified)
+O << ".reqntid " << Reqntidx << ", " << Reqntidy << ", " << Reqntidz
   << "\n";
 
   // If the NVVM IR has some of maxntid* specified, then output
   // the maxntid directive, and set the unspecified ones to 1.
   // If none of maxntid* is specified, don't output maxntid directive.
-  unsigned maxntidx, maxntidy, maxntidz;
-  specified = false;
-  if (!getMaxNTIDx(F, maxntidx))
-maxntidx = 1;
-  else
-specified = true;
-  if (!getMaxNTIDy(F, maxntidy))
-maxntidy = 1;
-  else
-specified = true;
-  if (!getMaxNTIDz(F, maxntidz))
-maxntidz = 1;
-  else
-specified = true;
-
-  if (specified)
-O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
+  unsigned Maxntidx, Maxntidy, Maxntidz;
+  Maxntidx = Maxntidy = Maxntidz = 1;
+  bool MaxSpecified = false;
+  MaxSpecified |= getMaxNTIDx(F, Maxntidx);
+  MaxSpecified |= getMaxNTIDy(F, Maxntidy);
+  MaxSpecified |= getMaxNTIDz(F, Maxntidz);
+
+  if (MaxSpecified)
+O << ".maxntid " << Maxntidx << ", " << Maxntidy << ", " << Maxntidz
   << "\n";
 
-  unsigned mincta;
-  if (getMinCTASm(F, mincta))
-O << ".minnctapersm " << mincta << "\n";
+  unsigned Mincta = 0;
+  if (getMinCTASm(F, Mincta))
+O << ".minnctapersm " << Mincta << "\n";
 
-  unsigned maxnreg;
-  if (getMaxNReg(F, maxnreg))
-O << ".maxnreg " << maxnreg << "\n";
+  unsigned Maxnreg = 0;
+  if (getMaxNReg(F, Maxnreg))
+O << ".maxnreg " << Maxnreg << "\n";
+
+  unsigned Maxclusterrank = 0;

jchlanda wrote:

You are right, `ptxas` reacts to a sample with `.maxclusterrank` with pre SM_90 
with a hard error:
```
ptxas --gpu-name sm_75 --output-file cluster_rank.o cluster_rank.s

ptxas cluster_rank.s, line 18; error   : Feature '.maxclusterrank' requires 
.target sm_90 or higher
ptxas fatal   : Ptx assembly aborted due to errors
```

Do I understand you right, that you'd like to see a [check similar to what we 
do in 
SemaDeclAttr](https://github.com/llvm/llvm-project/pull/66496/files#diff-2a5bdb2d9f07f8d77de51d5403d349c22978141b6de6bd87fc5e449f5ed95becR5683)
 and filter out the directive on targets < SM_90?

https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67109)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD edited https://github.com/llvm/llvm-project/pull/67109
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-09-22 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/66481

From ce62d3e1924b497b3e7160579a87557119c9e35d Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 15 Sep 2023 10:21:30 +0200
Subject: [PATCH] [analyzer] Add std::variant checker

Adding a checker that checks for bad std::variant type access.
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   4 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/StdVariantChecker.cpp| 327 
 .../Checkers/TaggedUnionModeling.h| 104 +
 .../Inputs/system-header-simulator-cxx.h  | 122 ++
 .../diagnostics/explicit-suppression.cpp  |   2 +-
 clang/test/Analysis/std-variant-checker.cpp   | 358 ++
 7 files changed, 917 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h
 create mode 100644 clang/test/Analysis/std-variant-checker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..052cf5f884f2773 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -318,6 +318,10 @@ def C11LockChecker : Checker<"C11Lock">,
   Dependencies<[PthreadLockBase]>,
   Documentation;
 
+def StdVariantChecker : Checker<"StdVariant">,
+  HelpText<"Check for bad type access for std::variant.">,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index ae849f59f90d3d9..d7cb51e1a0819a8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -108,6 +108,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   SmartPtrModeling.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp
+  StdVariantChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
   StringChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
new file mode 100644
index 000..680c5567431bbfb
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp
@@ -0,0 +1,327 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include 
+#include 
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace tagged_union_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext || CallLocationContext->inTopFrame())
+return nullptr;
+
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext)
+return nullptr;
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall)
+return nullptr;
+
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  if (const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call))
+return ConstructorDecl->isCopyConstructor();
+  return false;
+}
+
+bool isCopyAssignmentCall(const CallEvent

[clang] Introduce paged vector (PR #66430)

2023-09-22 Thread Giulio Eulisse via cfe-commits

https://github.com/ktf updated https://github.com/llvm/llvm-project/pull/66430

>From dd75b18a8497381f478a85f1bf7b622583c5ca29 Mon Sep 17 00:00:00 2001
From: Giulio Eulisse <10544+...@users.noreply.github.com>
Date: Thu, 14 Sep 2023 21:58:21 +0200
Subject: [PATCH] Introduce PagedVector class

The goal of the class is to be an (almost) drop in replacement for
SmallVector and std::vector when those are presized and filled later,
as it happens in SourceManager and ASTReader.

By splitting the actual vector in pages of the same size and allocating
the pages only when they are needed, using this containers reduces the
memory usage by a factor 4 for the cases relevant to the ALICE
experiment ROOT / cling usage.
---
 clang/include/clang/Basic/SourceManager.h |   3 +-
 clang/include/clang/Serialization/ASTReader.h |   5 +-
 clang/lib/Basic/SourceManager.cpp |  10 +-
 clang/lib/Serialization/ASTReader.cpp |   5 +-
 llvm/docs/ProgrammersManual.rst   |  33 ++
 llvm/include/llvm/ADT/PagedVector.h   | 307 
 llvm/unittests/ADT/CMakeLists.txt |   1 +
 llvm/unittests/ADT/PagedVectorTest.cpp| 342 ++
 8 files changed, 696 insertions(+), 10 deletions(-)
 create mode 100644 llvm/include/llvm/ADT/PagedVector.h
 create mode 100644 llvm/unittests/ADT/PagedVectorTest.cpp

diff --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 2f846502d6f3327..e37caa2252532f9 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -43,6 +43,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/PagedVector.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -699,7 +700,7 @@ class SourceManager : public RefCountedBase {
   ///
   /// Negative FileIDs are indexes into this table. To get from ID to an index,
   /// use (-ID - 2).
-  SmallVector LoadedSLocEntryTable;
+  llvm::PagedVector LoadedSLocEntryTable;
 
   /// The starting offset of the next local SLocEntry.
   ///
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index dc1eb21c27801fe..65e19c6e44cf571 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -38,6 +38,7 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/PagedVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -487,7 +488,7 @@ class ASTReader
   ///
   /// When the pointer at index I is non-NULL, the type with
   /// ID = (I + 1) << FastQual::Width has already been loaded
-  std::vector TypesLoaded;
+  llvm::PagedVector TypesLoaded;
 
   using GlobalTypeMapType =
   ContinuousRangeMap;
@@ -501,7 +502,7 @@ class ASTReader
   ///
   /// When the pointer at index I is non-NULL, the declaration with ID
   /// = I + 1 has already been loaded.
-  std::vector DeclsLoaded;
+  llvm::PagedVector DeclsLoaded;
 
   using GlobalDeclMapType =
   ContinuousRangeMap;
diff --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 0521ac7b30339ab..7fa8b8096ac4931 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -2344,11 +2344,11 @@ SourceManager::MemoryBufferSizes 
SourceManager::getMemoryBufferSizes() const {
 }
 
 size_t SourceManager::getDataStructureSizes() const {
-  size_t size = llvm::capacity_in_bytes(MemBufferInfos)
-+ llvm::capacity_in_bytes(LocalSLocEntryTable)
-+ llvm::capacity_in_bytes(LoadedSLocEntryTable)
-+ llvm::capacity_in_bytes(SLocEntryLoaded)
-+ llvm::capacity_in_bytes(FileInfos);
+  size_t size = llvm::capacity_in_bytes(MemBufferInfos) +
+llvm::capacity_in_bytes(LocalSLocEntryTable) +
+llvm::capacity_in_bytes(LoadedSLocEntryTable) +
+llvm::capacity_in_bytes(SLocEntryLoaded) +
+llvm::capacity_in_bytes(FileInfos);
 
   if (OverriddenFilesInfo)
 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 0952244d037a77c..badd54987af18dd 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -7944,9 +7944,10 @@ void ASTReader::PrintStats() {
   std::fprintf(stderr, "*** AST File Statistics:\n");
 
   unsigned NumTypesLoaded =
-  TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
+  TypesLoaded.size() - llvm::count(TypesLoaded.materialised(), QualType());
   unsigned NumDeclsLoaded =
-  DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
+  DeclsLoaded.size() -
+  llvm::count(DeclsLoaded.materialised(), (

[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67018)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD updated https://github.com/llvm/llvm-project/pull/67018

>From dc77e5c7bca87badecc314b24cab4c10be0e02fa Mon Sep 17 00:00:00 2001
From: eopXD 
Date: Thu, 21 Sep 2023 06:34:57 -0700
Subject: [PATCH] [Clang][RISCV] Handle RVV tuple types correctly as
 OutputOperand for inline asm

The RVV tuple type maps to an aggregate type with homogeneous scalable
vectors. EmitAsmStmt does not handle this correctly and this commit
attempts to fix it.

Expressing the type as a structure in inline asm calls will complicate
the current code base, so instead, the return type is set to be
a single scalable vector, then reconstructed with `vector.extract` and
`insertvalue`.

A follow-up commit will deal with details when associated with
InputOperands.
---
 clang/lib/CodeGen/CGStmt.cpp  | 52 ++-
 .../rvv-inline-asm.c  | 41 +++
 2 files changed, 91 insertions(+), 2 deletions(-)
 create mode 100644 
clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-asm.c

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 6674aa2409a5947..755f30b9c9e6369 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -29,6 +29,7 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/Assumptions.h"
+#include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
@@ -2392,6 +2393,26 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
+  } else if (TruncTy->isStructTy() && ResultRegQualTys[i]->isRVVType()) {
+auto *STy = cast(TruncTy);
+auto *VTy = cast(STy->getElementType(0));
+
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   "Must be dealing with RVV tuple type");
+
+unsigned MinElts = VTy->getElementCount().getKnownMinValue();
+llvm::Value *StructValue = llvm::PoisonValue::get(STy);
+
+for (unsigned Idx = 0, TupleSize = STy->getNumElements();
+ Idx != TupleSize; ++Idx) {
+  llvm::Value *IdxValue =
+  llvm::ConstantInt::get(CGM.Int64Ty, Idx * MinElts);
+  llvm::Value *SubVec = Builder.CreateExtractVector(VTy, Tmp, 
IdxValue);
+
+  StructValue = Builder.CreateInsertValue(StructValue, SubVec, Idx);
+}
+
+Tmp = StructValue;
   }
 }
 
@@ -2399,7 +2420,13 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 // ResultTypeRequiresCast elements correspond to the first
 // ResultTypeRequiresCast.size() elements of RegResults.
 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
-  unsigned Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
+  unsigned Size;
+  if (ResultRegQualTys[i]->isRVVType() && TruncTy->isStructTy()) {
+Size = cast(
+   cast(TruncTy)->getElementType(0))
+   ->getScalarSizeInBits();
+  } else
+Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
   Address A = Dest.getAddress(CGF).withElementType(ResultRegTypes[i]);
   if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
 Builder.CreateStore(Tmp, A);
@@ -2524,11 +2551,32 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   ResultRegIsFlagReg.push_back(IsFlagReg);
 
   llvm::Type *Ty = ConvertTypeForMem(QTy);
+  ResultTruncRegTypes.push_back(Ty);
+
+  // Expressing the type as a structure in inline asm calls will complicate
+  // the current code case, so instead, the return type is set to be a
+  // single scalable vector, then reconstructed with `vector.extract` and
+  // `insertvalue`. The type is derived here, and the reconstruction is 
done
+  // under EmitAsmStores.
+  if (QTy->isRVVType() && isa(Ty)) {
+// Flatten the structure into a single ScalableVectorType
+auto *STy = cast(Ty);
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   isa(STy->getElementType(0)) &&
+   "Dealing with RVV tuple (aggregate with homogeneous scalable "
+   "vectors");
+
+auto *VecTy = cast(STy->getElementType(0));
+
+Ty = llvm::ScalableVectorType::get(VecTy->getScalarType(),
+   STy->getNumElements() *
+   VecTy->getMinNumElements());
+  }
+
   const bool RequiresCast = Info.allowsRegister() &&
   (getTargetHooks().isScalarizableAsmOperand(*this, Ty) ||
Ty->isAggregateType());
 
-  ResultTruncRegTypes.push_back(Ty);
   ResultTypeRequiresCast.push_back(RequiresCast);
 
   if (RequiresCast) {
diff --git 
a/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-asm.c

[clang] [Clang][RISCV] Handle RVV tuple types correctly as OutputOperands for inline asm (PR #67109)

2023-09-22 Thread Yueh-Ting Chen via cfe-commits

https://github.com/eopXD updated https://github.com/llvm/llvm-project/pull/67109

>From dc77e5c7bca87badecc314b24cab4c10be0e02fa Mon Sep 17 00:00:00 2001
From: eopXD 
Date: Thu, 21 Sep 2023 06:34:57 -0700
Subject: [PATCH 1/3] [Clang][RISCV] Handle RVV tuple types correctly as
 OutputOperand for inline asm

The RVV tuple type maps to an aggregate type with homogeneous scalable
vectors. EmitAsmStmt does not handle this correctly and this commit
attempts to fix it.

Expressing the type as a structure in inline asm calls will complicate
the current code base, so instead, the return type is set to be
a single scalable vector, then reconstructed with `vector.extract` and
`insertvalue`.

A follow-up commit will deal with details when associated with
InputOperands.
---
 clang/lib/CodeGen/CGStmt.cpp  | 52 ++-
 .../rvv-inline-asm.c  | 41 +++
 2 files changed, 91 insertions(+), 2 deletions(-)
 create mode 100644 
clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-asm.c

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 6674aa2409a5947..755f30b9c9e6369 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -29,6 +29,7 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/Assumptions.h"
+#include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
@@ -2392,6 +2393,26 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
+  } else if (TruncTy->isStructTy() && ResultRegQualTys[i]->isRVVType()) {
+auto *STy = cast(TruncTy);
+auto *VTy = cast(STy->getElementType(0));
+
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   "Must be dealing with RVV tuple type");
+
+unsigned MinElts = VTy->getElementCount().getKnownMinValue();
+llvm::Value *StructValue = llvm::PoisonValue::get(STy);
+
+for (unsigned Idx = 0, TupleSize = STy->getNumElements();
+ Idx != TupleSize; ++Idx) {
+  llvm::Value *IdxValue =
+  llvm::ConstantInt::get(CGM.Int64Ty, Idx * MinElts);
+  llvm::Value *SubVec = Builder.CreateExtractVector(VTy, Tmp, 
IdxValue);
+
+  StructValue = Builder.CreateInsertValue(StructValue, SubVec, Idx);
+}
+
+Tmp = StructValue;
   }
 }
 
@@ -2399,7 +2420,13 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
 // ResultTypeRequiresCast elements correspond to the first
 // ResultTypeRequiresCast.size() elements of RegResults.
 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
-  unsigned Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
+  unsigned Size;
+  if (ResultRegQualTys[i]->isRVVType() && TruncTy->isStructTy()) {
+Size = cast(
+   cast(TruncTy)->getElementType(0))
+   ->getScalarSizeInBits();
+  } else
+Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
   Address A = Dest.getAddress(CGF).withElementType(ResultRegTypes[i]);
   if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
 Builder.CreateStore(Tmp, A);
@@ -2524,11 +2551,32 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   ResultRegIsFlagReg.push_back(IsFlagReg);
 
   llvm::Type *Ty = ConvertTypeForMem(QTy);
+  ResultTruncRegTypes.push_back(Ty);
+
+  // Expressing the type as a structure in inline asm calls will complicate
+  // the current code case, so instead, the return type is set to be a
+  // single scalable vector, then reconstructed with `vector.extract` and
+  // `insertvalue`. The type is derived here, and the reconstruction is 
done
+  // under EmitAsmStores.
+  if (QTy->isRVVType() && isa(Ty)) {
+// Flatten the structure into a single ScalableVectorType
+auto *STy = cast(Ty);
+assert(STy->containsHomogeneousScalableVectorTypes() &&
+   isa(STy->getElementType(0)) &&
+   "Dealing with RVV tuple (aggregate with homogeneous scalable "
+   "vectors");
+
+auto *VecTy = cast(STy->getElementType(0));
+
+Ty = llvm::ScalableVectorType::get(VecTy->getScalarType(),
+   STy->getNumElements() *
+   VecTy->getMinNumElements());
+  }
+
   const bool RequiresCast = Info.allowsRegister() &&
   (getTargetHooks().isScalarizableAsmOperand(*this, Ty) ||
Ty->isAggregateType());
 
-  ResultTruncRegTypes.push_back(Ty);
   ResultTypeRequiresCast.push_back(RequiresCast);
 
   if (RequiresCast) {
diff --git 
a/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-inline-a

[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits

https://github.com/jchlanda updated 
https://github.com/llvm/llvm-project/pull/66496

>From 9c8caed3c8def15ccdbfdf831f36d0befed1fc84 Mon Sep 17 00:00:00 2001
From: Jakub Chlanda 
Date: Fri, 15 Sep 2023 12:08:04 +0100
Subject: [PATCH 1/5] [NVPTX] Add support for maxclusterrank in launch_bounds

Since SM_90 CUDA supports specifying additional argument to the
launch_bounds attribute: maxBlocksPerCluster, to express the maximum
number of CTAs that can be part of the cluster. See:
https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#cluster-dimension-directives-maxclusterrank
and
https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#launch-bounds
for details.
---
 clang/include/clang/Basic/Attr.td |  3 +-
 .../clang/Basic/DiagnosticSemaKinds.td|  4 +
 clang/include/clang/Sema/Sema.h   |  5 +-
 clang/lib/CodeGen/Targets/NVPTX.cpp   | 12 ++-
 clang/lib/Parse/ParseOpenMP.cpp   |  3 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 46 +--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 10 ++-
 clang/test/CodeGenCUDA/launch-bounds.cu   | 69 
 clang/test/SemaCUDA/launch_bounds.cu  |  4 +-
 clang/test/SemaCUDA/launch_bounds_sm_90.cu| 45 +++
 llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp | 79 +--
 llvm/lib/Target/NVPTX/NVPTXUtilities.cpp  |  4 +
 llvm/lib/Target/NVPTX/NVPTXUtilities.h|  1 +
 13 files changed, 227 insertions(+), 58 deletions(-)
 create mode 100644 clang/test/SemaCUDA/launch_bounds_sm_90.cu

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index c95db7e8049d47a..3c51261bd3eb081 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1267,7 +1267,8 @@ def CUDAInvalidTarget : InheritableAttr {
 
 def CUDALaunchBounds : InheritableAttr {
   let Spellings = [GNU<"launch_bounds">, Declspec<"__launch_bounds__">];
-  let Args = [ExprArgument<"MaxThreads">, ExprArgument<"MinBlocks", 1>];
+  let Args = [ExprArgument<"MaxThreads">, ExprArgument<"MinBlocks", 1>,
+  ExprArgument<"MaxBlocks", 1>];
   let LangOpts = [CUDA];
   let Subjects = SubjectList<[ObjCMethod, FunctionLike]>;
   // An AST node is created for this attribute, but is not used by other parts
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..088e3a45c7babba 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11836,6 +11836,10 @@ def err_sycl_special_type_num_init_method : Error<
   "types with 'sycl_special_class' attribute must have one and only one 
'__init' "
   "method defined">;
 
+def warn_cuda_maxclusterrank_sm_90 : Warning<
+  "maxclusterrank requires sm_90 or higher, CUDA arch provided: %0, ignoring "
+  "%1 attribute">, InGroup;
+
 def err_bit_int_bad_size : Error<"%select{signed|unsigned}0 _BitInt must "
  "have a bit size of at least %select{2|1}0">;
 def err_bit_int_max_size : Error<"%select{signed|unsigned}0 _BitInt of bit "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 47379e00a7445e3..dca7b66da3796d9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11051,12 +11051,13 @@ class Sema final {
   /// Create an CUDALaunchBoundsAttr attribute.
   CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
Expr *MaxThreads,
-   Expr *MinBlocks);
+   Expr *MinBlocks,
+   Expr *MaxBlocks);
 
   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
   /// declaration.
   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
-   Expr *MaxThreads, Expr *MinBlocks);
+   Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
 
   /// AddModeAttr - Adds a mode attribute to a particular declaration.
   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo 
*Name,
diff --git a/clang/lib/CodeGen/Targets/NVPTX.cpp 
b/clang/lib/CodeGen/Targets/NVPTX.cpp
index 0d4bbd795648008..64d019a10514d60 100644
--- a/clang/lib/CodeGen/Targets/NVPTX.cpp
+++ b/clang/lib/CodeGen/Targets/NVPTX.cpp
@@ -296,8 +296,8 @@ void CodeGenModule::handleCUDALaunchBoundsAttr(
 NVPTXTargetCodeGenInfo::addNVVMMetadata(F, "maxntidx",
 MaxThreads.getExtValue());
 
-  // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
-  // not specified in __launch_bounds__ or if the user specified a 0 value,
+  // min and max blocks is an optional argument for CUDALaunchBoundsAttr. If it
+  // was not specified in __launch_bounds__ or if the user specified

[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits


@@ -12,7 +12,7 @@ __launch_bounds__(0x1) void 
TestWayTooBigArg(void); // expected-
 __launch_bounds__(-128, 7) void TestNegArg1(void); // expected-warning 
{{'launch_bounds' attribute parameter 0 is negative and will be ignored}}
 __launch_bounds__(128, -7) void TestNegArg2(void); // expected-warning 
{{'launch_bounds' attribute parameter 1 is negative and will be ignored}}

jchlanda wrote:

Done in 028d270290218f3cc4fb35acc721b0645f2118ea

https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-22 Thread Jakub Chlanda via cfe-commits


@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -triple nvptx-unknown-unknown 
-target-cpu sm_90  -verify %s
+
+#include "Inputs/cuda.h"
+
+__launch_bounds__(128, 7) void Test2Args(void);
+__launch_bounds__(128) void Test1Arg(void);
+
+__launch_bounds__(0x) void TestMaxArg(void);
+__launch_bounds__(0x1) void TestTooBigArg(void); // expected-error 
{{integer constant expression evaluates to value 4294967296 that cannot be 
represented in a 32-bit unsigned integer type}}
+__launch_bounds__(0x1) void TestWayTooBigArg(void); // 
expected-error {{integer literal is too large to be represented in any integer 
type}}
+__launch_bounds__(1, 1, 0x1) void TestWayTooBigArg(void); // 
expected-error {{integer literal is too large to be represented in any integer 
type}}
+
+__launch_bounds__(-128, 7) void TestNegArg1(void); // expected-warning 
{{'launch_bounds' attribute parameter 0 is negative and will be ignored}}
+__launch_bounds__(128, -7) void TestNegArg2(void); // expected-warning 
{{'launch_bounds' attribute parameter 1 is negative and will be ignored}}
+__launch_bounds__(128, 1, -7) void TestNegArg2(void); // expected-warning 
{{'launch_bounds' attribute parameter 2 is negative and will be ignored}}

jchlanda wrote:

Done in 028d270290218f3cc4fb35acc721b0645f2118ea

https://github.com/llvm/llvm-project/pull/66496
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV] Support floating point VCIX (PR #67094)

2023-09-22 Thread Kito Cheng via cfe-commits


@@ -2441,11 +2441,11 @@ define void @test_sf_vc_fvv_se_e16mf4( %vd, 
 ; CHECK-NEXT:sf.vc.fvv 1, v8, v9, fa0
 ; CHECK-NEXT:ret
 entry:
-  tail call void @llvm.riscv.sf.vc.fvv.se.iXLen.nxv1i16.f16.iXLen(iXLen 1, 
 %vd,  %vs2, half %fs1, iXLen %vl)
+  tail call void @llvm.riscv.sf.vc.fvv.se.iXLen.nxv1i16.i16.iXLen(iXLen 1, 
 %vd,  %vs2, half %fs1, iXLen %vl)

kito-cheng wrote:

Why changed to `i16`? arguments is half, which `f16` should be the right type?

https://github.com/llvm/llvm-project/pull/67094
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV] Support floating point VCIX (PR #67094)

2023-09-22 Thread Kito Cheng via cfe-commits

https://github.com/kito-cheng commented:

The target is support LLVM IR part only, we would like to prevent expose that 
on the C intrinsic level if possible, because that's intentionally to expose 
vector with unsigned integer only.

https://github.com/llvm/llvm-project/pull/67094
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV] Support floating point VCIX (PR #67094)

2023-09-22 Thread Kito Cheng via cfe-commits

https://github.com/kito-cheng edited 
https://github.com/llvm/llvm-project/pull/67094
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (PR #66207)

2023-09-22 Thread via cfe-commits

DonatNagyE wrote:

I tested this commit on several open-source projects, comparing it and its 
parent with a configuration that enables the non-alpha checkers (so 
StdCLibraryFunctions becomes enabled when this commit moves it out of alpha).

The results show that this checker doesn't produce random noise and can provide 
some useful results:
| Project | New reports | Lost reports | Changes |
| --- | --- | --- | --- |
| memcached | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=memcached_1.6.8_baseline&newcheck=memcached_1.6.8_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=memcached_1.6.8_baseline&newcheck=memcached_1.6.8_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| tmux | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tmux_2.6_baseline&newcheck=tmux_2.6_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tmux_2.6_baseline&newcheck=tmux_2.6_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| twin | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=twin_v0.8.1_baseline&newcheck=twin_v0.8.1_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=twin_v0.8.1_baseline&newcheck=twin_v0.8.1_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| vim | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_baseline&newcheck=vim_v8.2.1920_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_baseline&newcheck=vim_v8.2.1920_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| openssl | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_baseline&newcheck=openssl_openssl-3.0.0-alpha7_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_baseline&newcheck=openssl_openssl-3.0.0-alpha7_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| sqlite | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| ffmpeg | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| postgres | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | 5 new TPs [1]
| tinyxml2 | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tinyxml2_8.0.0_baseline&newcheck=tinyxml2_8.0.0_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tinyxml2_8.0.0_baseline&newcheck=tinyxml2_8.0.0_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| libwebm | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=libwebm_libwebm-1.0.0.27_baseline&newcheck=libwebm_libwebm-1.0.0.27_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=libwebm_libwebm-1.0.0.27_baseline&newcheck=libwebm_libwebm-1.0.0.27_with_std_library_functions&is-unique=on&diff-mode=Resolved)
 | no effect |
| xerces | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=xerces_v3.2.3_baseline&newcheck=xerces_v3.2.3_with_std_library_functions&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=xerces_v3.2.3_baseline&newcheck=xerces_v3.2.3_with_std_lib

[clang] [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (PR #66207)

2023-09-22 Thread via cfe-commits

https://github.com/DonatNagyE approved this pull request.

Based on these clean test results I'd say that it's safe to move this checker 
out of alpha.

@haoNoQ @steakhal Do you have any objections?

https://github.com/llvm/llvm-project/pull/66207
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Don't split "DPI"/"DPI-C" in Verilog imports (PR #66951)

2023-09-22 Thread via cfe-commits


@@ -2270,7 +2270,18 @@ ContinuationIndenter::createBreakableToken(const 
FormatToken &Current,
 if (State.Stack.back().IsInsideObjCArrayLiteral)
   return nullptr;
 
+// The "DPI"/"DPI-C" in SystemVerilog direct programming interface imports
+// cannot be split, e.g.
+// `import "DPI" function foo();`
 StringRef Text = Current.TokenText;
+if (Style.isVerilog()) {
+  const FormatToken *Prev = Current.getPreviousNonComment();
+  if (Prev && Prev == State.Line->getFirstNonComment() &&
+  Prev->TokenText == "import") {
+return nullptr;
+  }
+}
+

alexfh wrote:

> > `isOneOf` won't work here, since the token has the type of `identifier` 
> > rather than a keyword:
> 
> Have you tried it? It does work because not only is `import` a 
> `tok::identifier`, it's also a `Keywords.kw_import`.

Ah, right, I had tried it with `tok::kw_import` (and I missed the difference 
between this and your suggestion). Thanks for the clarification!

> > We should leave `Current.getPreviousNonComment()` to handle comments in the 
> > middle of the statement (something like `import /*"DPI"*/ "DPI-C" ...` 
> > comes to mind).
> 
> I was aware of that, but we usually don't call `getPreviousNonComment()` 
> unless a comment before a token makes sense in practice. Otherwise, we would 
> have to write ugly and inefficient code to handle things like the following:
> 
> ```
> /* outer l_square */ [ /* inner l_square */ [ /* attribute */ unlikely /* 
> inner r_square */ ] /* outer r_square */ ] // comment
> ```

I don't think it would add a lot of overhead (one branch on a happy path) or 
hinder readability of the code a lot (`getPreviousNonComment()` vs `Prev`), but 
I also don't think it's super important here.


https://github.com/llvm/llvm-project/pull/66951
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-09-22 Thread via cfe-commits


@@ -463,3 +463,38 @@ static_assert(bit_cast(ld539) == 
fivehundredandthirtynine, "");
 static_assert(round_trip<__int128_t>(34.0L));
 #endif
 }
+
+namespace test_vector {
+
+typedef unsigned uint2 __attribute__((vector_size(2 * sizeof(unsigned;
+typedef char byte8 __attribute__((vector_size(sizeof(unsigned long long;
+
+constexpr uint2 test_vector = { 0x0C05FEFE, 0xCAFEBABE };
+
+static_assert(bit_cast(test_vector) == (LITTLE_END
+? 
0xCAFEBABE0C05FEFE
+: 
0x0C05FEFECAFEBABE), "");
+
+static_assert(round_trip(0xCAFEBABE0C05FEFEULL), "");
+static_assert(round_trip(0xCAFEBABE0C05FEFEULL), "");
+
+typedef bool bool8 __attribute__((ext_vector_type(8)));
+typedef bool bool9 __attribute__((ext_vector_type(9)));
+typedef bool bool17 __attribute__((ext_vector_type(17)));
+typedef bool bool32 __attribute__((ext_vector_type(32)));
+
+static_assert(bit_cast(bool8{1,0,1,0,1,0,1,0}) == 0x55, "");
+static_assert(round_trip(static_cast(0)), "");
+static_assert(round_trip(static_cast(1)), "");
+static_assert(round_trip(static_cast(0x55)), "");
+
+static_assert(bit_cast(bool9{1,1,0,1,0,1,0,1,0}) == 0xAB, "");

DaMatrix wrote:

Sorry, disregard this - further experimentation and [your comment 
above](https://github.com/llvm/llvm-project/pull/66894#discussion_r1333587577) 
has convinced me that this isn't the case.

https://github.com/llvm/llvm-project/pull/66894
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-09-22 Thread via cfe-commits

https://github.com/DaMatrix edited 
https://github.com/llvm/llvm-project/pull/66894
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156890: [clang] Remove outdated INSTALL.txt

2023-09-22 Thread Stephan Lachnit via Phabricator via cfe-commits
stephanlachnit added a comment.

In D156890#4649226 , @cor3ntin wrote:

> @stephanlachnit do you need me to land this on your behalf? What email should 
> we use?

Yes, please! You can use stephanlach...@debian.org


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156890

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-09-22 Thread via cfe-commits


@@ -7095,6 +7096,40 @@ class APValueToBufferConverter {
 return true;
   }
 
+  bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
+const auto *VT = Ty->castAs();
+unsigned VectorLength = Val.getVectorLength();
+
+if (VT->isExtVectorBoolType()) {
+  // Special handling for OpenCL bool vectors: we need to pack the vector
+  // of 1-bit unsigned integers into a single integer with the 
corresponding
+  // bits set, then write out the resulting integer.
+
+  CharUnits VecWidthBits = Info.Ctx.getTypeSizeInChars(VT) * 8;
+
+  APSInt Bits(VecWidthBits.getQuantity());
+  for (unsigned I = 0; I != VectorLength; ++I) {
+const APValue &SubObj = Val.getVectorElt(I);
+assert(SubObj.isInt() && "Bool vector element isn't an int?");
+Bits.setBitVal(I, !SubObj.getInt().isZero());

DaMatrix wrote:

I've come to the same conclusion as you that I don't think this is possible 
with non-byte-sized vectors. Since this is only an issue for OpenCL bool 
vectors, should I just have it fail with an unsupported exception when the 
number of bool elements isn't a multiple of the char size?

https://github.com/llvm/llvm-project/pull/66894
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-09-22 Thread via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


cor3ntin wrote:

I have concerns about Lexing twice every single file for which we display a 
warning.

Did you try something along the lines of what Richard suggested? Keeping track 
of where lines start does seem like a good idea.

We could even keep track of ranges of good lines which would reduce even 
further how much state we need to keep in the lexer.

We can then parse starting from the nearest good line start. We could still 
cache that further if we wanted.

https://github.com/llvm/llvm-project/pull/66514
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-09-22 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

> I have concerns about Lexing twice every single file for which we display a 
> warning.

Sure. Because of performance, memory usage or code complexity?

> Did you try something along the lines of what Richard suggested? Keeping 
> track of where lines start does seem like a good idea.
> 
> We could even keep track of ranges of good lines which would reduce even 
> further how much state we need to keep in the lexer.
> 
> We can then parse starting from the nearest good line start. We could still 
> cache that further if we wanted.

So, my general procedure for diagnostics is that they shouldn't complicate the 
non-diagnostic code. And when we emit a diagnostic, performance is basically 
out the window anyway (printing to stdout is _slow_ and the way we emit code 
snippets is also slow, etc.)

For build servers, none of this matters since they don't colorize output at 
all, so this is really only interesting for actual developers who usually have 
a clean build (no diagnostics emitted at all), but want to have maximal 
usefulness of the ones they encounter while working on their project.


https://github.com/llvm/llvm-project/pull/66514
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/66947

>From 00ef242c40dd453157ee3b31e367fd6240d68a5a Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Wed, 20 Sep 2023 21:19:03 +0200
Subject: [PATCH 1/3] [Driver] Fix detection of libc++ with empty sysroot.

b1e3cd1d79443603dc003441e07cdd8d30bb7f26 dropped the leading slash here,
presumably unintentionally.

(I don't understand Driver well enough to know how/where this is supposed
to be tested, but it broke clangd on any project that uses the
system-installed -stdlib=libc++ on a standard debian install)
---
 clang/lib/Driver/ToolChains/Gnu.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index e909549d20708fe..f2fd85021a777b4 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -3139,11 +3139,11 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
   // not be found at ../include/c++ but it likely to be found at
   // one of the following two locations:
   SmallString<128> UsrLocalIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
+  llvm::sys::path::append(UsrLocalIncludeDir, "/usr", "local", "include");
   if (AddIncludePath(UsrLocalIncludeDir))
 return;
   SmallString<128> UsrIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrIncludeDir, "usr", "include");
+  llvm::sys::path::append(UsrIncludeDir, "/usr", "include");
   if (AddIncludePath(UsrIncludeDir))
 return;
 }

>From a7f9a86ac30bcb93b255e9dd6f4b1f27bb99c502 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Fri, 22 Sep 2023 12:03:39 +0200
Subject: [PATCH 2/3] use / locally for default sysroot, add test

---
 clang/lib/Driver/ToolChains/Gnu.cpp  |  6 ++--
 clang/unittests/Driver/ToolChainTest.cpp | 46 
 2 files changed, 50 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index f2fd85021a777b4..61f5100f1385a13 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -3100,6 +3100,8 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const {
   const Driver &D = getDriver();
   std::string SysRoot = computeSysRoot();
+  if (SysRoot.empty())
+SysRoot = llvm::sys::path::get_separator();
 
   auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
 std::string Version = detectLibcxxVersion(Path);
@@ -3139,11 +3141,11 @@ Generic_GCC::addLibCxxIncludePaths(const 
llvm::opt::ArgList &DriverArgs,
   // not be found at ../include/c++ but it likely to be found at
   // one of the following two locations:
   SmallString<128> UsrLocalIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrLocalIncludeDir, "/usr", "local", "include");
+  llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
   if (AddIncludePath(UsrLocalIncludeDir))
 return;
   SmallString<128> UsrIncludeDir(SysRoot);
-  llvm::sys::path::append(UsrIncludeDir, "/usr", "include");
+  llvm::sys::path::append(UsrIncludeDir, "usr", "include");
   if (AddIncludePath(UsrIncludeDir))
 return;
 }
diff --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index ae567abb81a9bb4..85beea4e94ca252 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -19,10 +19,12 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 
@@ -316,6 +318,50 @@ TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
   }
 }
 
+MATCHER_P(jobHasArgs, Substr, "") {
+  const driver::Command &C = arg;
+  std::string Args = "";
+  llvm::ListSeparator Sep(" ");
+  for (const char *Arg : C.getArguments()) {
+Args += Sep;
+Args += Arg;
+  }
+  if (llvm::StringRef(Args).contains(Substr))
+return true;
+  *result_listener << "whose args are '" << Args << "'";
+  return false;
+}
+
+TEST(ToolChainTest, VFSGnuLibcxxPathNoSysroot) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  const char *EmptyFiles[] = {
+  "foo.cpp",
+  "/bin/clang",
+  "/usr/include/c++/v1/cstdio",
+  };
+
+  for (const char *Path : EmptyFiles)
+InMemoryFileSystem->addFile(Path, 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  

[clang-tools-extra] [mlir] Implement DestinationStyleOpInterface for scf::ForallOp (PR #66981)

2023-09-22 Thread Felix Schneider via cfe-commits

https://github.com/ubfx updated https://github.com/llvm/llvm-project/pull/66981

>From a84378d0f4e67cd7f68a27c87e12939fa40b65b4 Mon Sep 17 00:00:00 2001
From: Felix Schneider 
Date: Thu, 21 Sep 2023 06:13:57 +
Subject: [PATCH 1/3] [mlir] Implement DestinationStyleOpInterface for
 scf::ForallOp

`scf::ForallOp` has `shared_outs` tensor operands which are used to
insert partial results into in the parallel terminator. The
`scf::ForallOp` returns one tensor for each `shared_out` which then
contains the combined result from all threads. Since the parallel
terminator cannot change the shape of the `shared_out`, ForallOp is a
`DestinationStyleOp` and this patch implements the interface by declaring
the `outputs` operands as `inits` in the language of the DPS interface.

For this change to work, we need to add an exception to the Pattern
that folds `tensor.cast` Ops into DPS Ops because `scf::Forall` needs
special handling of it's `BlockArgument` Type during this folding.
---
 mlir/include/mlir/Dialect/SCF/IR/SCF.h |  1 +
 mlir/include/mlir/Dialect/SCF/IR/SCFOps.td | 10 ++
 mlir/lib/Dialect/Tensor/IR/TensorOps.cpp   |  4 
 3 files changed, 15 insertions(+)

diff --git a/mlir/include/mlir/Dialect/SCF/IR/SCF.h 
b/mlir/include/mlir/Dialect/SCF/IR/SCF.h
index 915ab3016b688e7..644118ca884c6b1 100644
--- a/mlir/include/mlir/Dialect/SCF/IR/SCF.h
+++ b/mlir/include/mlir/Dialect/SCF/IR/SCF.h
@@ -19,6 +19,7 @@
 #include "mlir/IR/BuiltinTypes.h"
 #include "mlir/IR/RegionKindInterface.h"
 #include "mlir/Interfaces/ControlFlowInterfaces.h"
+#include "mlir/Interfaces/DestinationStyleOpInterface.h"
 #include "mlir/Interfaces/InferTypeOpInterface.h"
 #include "mlir/Interfaces/LoopLikeInterface.h"
 #include "mlir/Interfaces/ParallelCombiningOpInterface.h"
diff --git a/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td 
b/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
index 08b71e20a2bc079..adc7b2e4170cb89 100644
--- a/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
+++ b/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
@@ -17,6 +17,7 @@ include "mlir/Interfaces/ControlFlowInterfaces.td"
 include "mlir/Interfaces/LoopLikeInterface.td"
 include "mlir/IR/RegionKindInterface.td"
 include "mlir/Dialect/SCF/IR/DeviceMappingInterface.td"
+include "mlir/Interfaces/DestinationStyleOpInterface.td"
 include "mlir/Interfaces/InferTypeOpInterface.td"
 include "mlir/Interfaces/ParallelCombiningOpInterface.td"
 include "mlir/Interfaces/SideEffectInterfaces.td"
@@ -333,6 +334,7 @@ def ForallOp : SCF_Op<"forall", [
RecursiveMemoryEffects,
SingleBlockImplicitTerminator<"scf::InParallelOp">,
DeclareOpInterfaceMethods,
+   DestinationStyleOpInterface
  ]> {
   let summary = "evaluate a block multiple times in parallel";
   let description = [{
@@ -630,6 +632,14 @@ def ForallOp : SCF_Op<"forall", [
  Location loc);
 
 InParallelOp getTerminator();
+
+// Implement this to declare all shared_outs as inits/outs to 
+// DestinationStyleOpInterface
+std::pair getDpsInitsPositionRange() {
+  int64_t numOperands = getNumOperands();
+  int64_t numOuts = getOutputs().size();
+  return {numOperands - numOuts, numOperands};
+}
   }];
 }
 
diff --git a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp 
b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
index 3e30e320bee8f83..fa91471f33d4bd3 100644
--- a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
+++ b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
@@ -10,6 +10,7 @@
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Arith/Utils/Utils.h"
 #include "mlir/Dialect/Complex/IR/Complex.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
 #include "mlir/Dialect/Tensor/IR/Tensor.h"
 #include "mlir/Dialect/Utils/IndexingUtils.h"
 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
@@ -3970,6 +3971,9 @@ struct FoldTensorCastProducerOp
 if (isa(op.getOperation()))
   return failure();
 
+if (isa(op.getOperation()))
+  return failure();
+
 // If no operand comes from a tensor::CastOp and can be folded then fail.
 bool hasTensorCastOperand =
 llvm::any_of(op->getOpOperands(), [&](OpOperand &opOperand) {

>From 4e8e45878083490a9adf0fbcc1b4565081c1d7c5 Mon Sep 17 00:00:00 2001
From: Felix Schneider 
Date: Thu, 21 Sep 2023 07:52:23 +
Subject: [PATCH 2/3] add comment clarifying the exception for forallOp folding
 with tensor.cast

---
 mlir/lib/Dialect/Tensor/IR/TensorOps.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp 
b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
index fa91471f33d4bd3..65a834acad8acfb 100644
--- a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
+++ b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
@@ -3971,6 +3971,8 @@ struct FoldTensorCastProducerOp
 if (isa(op.getOperation()))
   return failure();
 
+// scf::ForallOp also has its own folding logic taking the Types of its
+// BlockArguments into consideration.
 if (isa(op.getOperation()))
   return fa

[clang] [mlir] Implement DestinationStyleOpInterface for scf::ForallOp (PR #66981)

2023-09-22 Thread Felix Schneider via cfe-commits

https://github.com/ubfx updated https://github.com/llvm/llvm-project/pull/66981

>From a84378d0f4e67cd7f68a27c87e12939fa40b65b4 Mon Sep 17 00:00:00 2001
From: Felix Schneider 
Date: Thu, 21 Sep 2023 06:13:57 +
Subject: [PATCH 1/3] [mlir] Implement DestinationStyleOpInterface for
 scf::ForallOp

`scf::ForallOp` has `shared_outs` tensor operands which are used to
insert partial results into in the parallel terminator. The
`scf::ForallOp` returns one tensor for each `shared_out` which then
contains the combined result from all threads. Since the parallel
terminator cannot change the shape of the `shared_out`, ForallOp is a
`DestinationStyleOp` and this patch implements the interface by declaring
the `outputs` operands as `inits` in the language of the DPS interface.

For this change to work, we need to add an exception to the Pattern
that folds `tensor.cast` Ops into DPS Ops because `scf::Forall` needs
special handling of it's `BlockArgument` Type during this folding.
---
 mlir/include/mlir/Dialect/SCF/IR/SCF.h |  1 +
 mlir/include/mlir/Dialect/SCF/IR/SCFOps.td | 10 ++
 mlir/lib/Dialect/Tensor/IR/TensorOps.cpp   |  4 
 3 files changed, 15 insertions(+)

diff --git a/mlir/include/mlir/Dialect/SCF/IR/SCF.h 
b/mlir/include/mlir/Dialect/SCF/IR/SCF.h
index 915ab3016b688e7..644118ca884c6b1 100644
--- a/mlir/include/mlir/Dialect/SCF/IR/SCF.h
+++ b/mlir/include/mlir/Dialect/SCF/IR/SCF.h
@@ -19,6 +19,7 @@
 #include "mlir/IR/BuiltinTypes.h"
 #include "mlir/IR/RegionKindInterface.h"
 #include "mlir/Interfaces/ControlFlowInterfaces.h"
+#include "mlir/Interfaces/DestinationStyleOpInterface.h"
 #include "mlir/Interfaces/InferTypeOpInterface.h"
 #include "mlir/Interfaces/LoopLikeInterface.h"
 #include "mlir/Interfaces/ParallelCombiningOpInterface.h"
diff --git a/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td 
b/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
index 08b71e20a2bc079..adc7b2e4170cb89 100644
--- a/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
+++ b/mlir/include/mlir/Dialect/SCF/IR/SCFOps.td
@@ -17,6 +17,7 @@ include "mlir/Interfaces/ControlFlowInterfaces.td"
 include "mlir/Interfaces/LoopLikeInterface.td"
 include "mlir/IR/RegionKindInterface.td"
 include "mlir/Dialect/SCF/IR/DeviceMappingInterface.td"
+include "mlir/Interfaces/DestinationStyleOpInterface.td"
 include "mlir/Interfaces/InferTypeOpInterface.td"
 include "mlir/Interfaces/ParallelCombiningOpInterface.td"
 include "mlir/Interfaces/SideEffectInterfaces.td"
@@ -333,6 +334,7 @@ def ForallOp : SCF_Op<"forall", [
RecursiveMemoryEffects,
SingleBlockImplicitTerminator<"scf::InParallelOp">,
DeclareOpInterfaceMethods,
+   DestinationStyleOpInterface
  ]> {
   let summary = "evaluate a block multiple times in parallel";
   let description = [{
@@ -630,6 +632,14 @@ def ForallOp : SCF_Op<"forall", [
  Location loc);
 
 InParallelOp getTerminator();
+
+// Implement this to declare all shared_outs as inits/outs to 
+// DestinationStyleOpInterface
+std::pair getDpsInitsPositionRange() {
+  int64_t numOperands = getNumOperands();
+  int64_t numOuts = getOutputs().size();
+  return {numOperands - numOuts, numOperands};
+}
   }];
 }
 
diff --git a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp 
b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
index 3e30e320bee8f83..fa91471f33d4bd3 100644
--- a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
+++ b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
@@ -10,6 +10,7 @@
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Arith/Utils/Utils.h"
 #include "mlir/Dialect/Complex/IR/Complex.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
 #include "mlir/Dialect/Tensor/IR/Tensor.h"
 #include "mlir/Dialect/Utils/IndexingUtils.h"
 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
@@ -3970,6 +3971,9 @@ struct FoldTensorCastProducerOp
 if (isa(op.getOperation()))
   return failure();
 
+if (isa(op.getOperation()))
+  return failure();
+
 // If no operand comes from a tensor::CastOp and can be folded then fail.
 bool hasTensorCastOperand =
 llvm::any_of(op->getOpOperands(), [&](OpOperand &opOperand) {

>From 4e8e45878083490a9adf0fbcc1b4565081c1d7c5 Mon Sep 17 00:00:00 2001
From: Felix Schneider 
Date: Thu, 21 Sep 2023 07:52:23 +
Subject: [PATCH 2/3] add comment clarifying the exception for forallOp folding
 with tensor.cast

---
 mlir/lib/Dialect/Tensor/IR/TensorOps.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp 
b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
index fa91471f33d4bd3..65a834acad8acfb 100644
--- a/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
+++ b/mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
@@ -3971,6 +3971,8 @@ struct FoldTensorCastProducerOp
 if (isa(op.getOperation()))
   return failure();
 
+// scf::ForallOp also has its own folding logic taking the Types of its
+// BlockArguments into consideration.
 if (isa(op.getOperation()))
   return fa

[PATCH] D35780: Introduce -nostdlib++ flag to disable linking the C++ standard library.

2023-09-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.
Herald added subscribers: pmatos, asb, abrachet.
Herald added a project: All.

Also useful for random other projects on github: 
https://github.com/mapbox/mason/pull/545#issuecomment-367082479

GCC also added support for this flag: 
https://github.com/gcc-mirror/gcc/commit/fc2fb4fd547fb39d76237a3a1a50f5c4f3646936


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

https://reviews.llvm.org/D35780

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


[clang] [AMDGPU] Remove Code Object V3 (PR #67118)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

V3 has been deprecated for a while as well, so it can safely be removed like V2 
was removed.

- [Clang] Set minimum code object version to 4
- [lld] Fix tests using code object v3
- Remove code object V3 from the AMDGPU backend, and delete or port v3 tests to 
v4.
- Update docs to make it clear V3 can no longer be emitted.

---

Patch is 148.97 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/67118.diff


41 Files Affected:

- (modified) clang/include/clang/Basic/TargetOptions.h (+1-1) 
- (modified) clang/include/clang/Driver/Options.td (+2-2) 
- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+1-1) 
- (modified) clang/test/CodeGenCUDA/amdgpu-code-object-version.cu (-4) 
- (modified) clang/test/Driver/hip-code-object-version.hip (+7-15) 
- (modified) clang/test/Driver/hip-device-libs.hip (-6) 
- (modified) lld/test/ELF/amdgpu-abi-version.s (-8) 
- (modified) llvm/docs/AMDGPUUsage.rst (+3-6) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp (-3) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp (+31-49) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h (+6-16) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp (-5) 
- (modified) llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp (-1) 
- (modified) llvm/lib/Target/AMDGPU/SIISelLowering.cpp (-5) 
- (modified) llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp (-21) 
- (modified) llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h (-4) 
- (modified) 
llvm/test/CodeGen/AMDGPU/GlobalISel/implicit-kernarg-backend-usage-global-isel.ll
 (-162) 
- (removed) llvm/test/CodeGen/AMDGPU/attr-amdgpu-flat-work-group-size-v3.ll 
(-148) 
- (removed) llvm/test/CodeGen/AMDGPU/directive-amdgcn-target-v3.ll (-168) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-enqueue-kernel-.ll (+2-2) 
- (modified) llvm/test/CodeGen/AMDGPU/hsa-metadata-from-llvm-ctor-dtor-list.ll 
(+1-1) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-from-llvm-ir-full.ll (+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-hidden-args-v4.ll (+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-hostcall-present-asan.ll 
(+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-hostcall-v4.ll (+1-1) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-images.ll (+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-invalid-ocl-version-1.ll 
(+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-invalid-ocl-version-3.ll 
(+2-2) 
- (renamed) llvm/test/CodeGen/AMDGPU/hsa-metadata-kernel-code-props.ll (+2-2) 
- (modified) llvm/test/CodeGen/AMDGPU/implicit-kernarg-backend-usage.ll (-157) 
- (modified) llvm/test/CodeGen/AMDGPU/kernarg-size.ll (-9) 
- (modified) llvm/test/CodeGen/AMDGPU/stack-realign-kernel.ll (+1-1) 
- (modified) llvm/test/CodeGen/AMDGPU/trap-abis.ll (+171-346) 
- (renamed) llvm/test/MC/AMDGPU/hsa-diag-v4.s (+9-9) 
- (removed) llvm/test/MC/AMDGPU/hsa-gfx10-v3.s (-226) 
- (removed) llvm/test/MC/AMDGPU/hsa-gfx11-v3.s (-213) 
- (removed) llvm/test/MC/AMDGPU/hsa-gfx90a-v3.s (-184) 
- (removed) llvm/test/MC/AMDGPU/hsa-gfx940-v3.s (-178) 
- (removed) llvm/test/MC/AMDGPU/hsa-v3.s (-304) 
- (modified) llvm/test/MC/AMDGPU/user-sgpr-count-diag.s (+1-1) 
- (modified) llvm/test/MC/AMDGPU/user-sgpr-count.s (+3-3) 


``diff
diff --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index 0dc324ff9ed43d9..cf18c9aba6cf9a6 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -83,7 +83,7 @@ class TargetOptions {
   enum CodeObjectVersionKind {
 COV_None,
 COV_2 = 200, // Unsupported.
-COV_3 = 300,
+COV_3 = 300, // Unsupported.
 COV_4 = 400,
 COV_5 = 500,
   };
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0f93479170d73bc..28a6334300f3894 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4624,9 +4624,9 @@ defm amdgpu_ieee : BoolOption<"m", "amdgpu-ieee",
 def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, 
Group,
   HelpText<"Specify code object ABI version. Defaults to 4. (AMDGPU only)">,
   Visibility<[ClangOption, CC1Option]>,
-  Values<"none,3,4,5">,
+  Values<"none,4,5">,
   NormalizedValuesScope<"TargetOptions">,
-  NormalizedValues<["COV_None", "COV_3", "COV_4", "COV_5"]>,
+  NormalizedValues<["COV_None", "COV_4", "COV_5"]>,
   MarshallingInfoEnum, "COV_4">;
 
 defm cumode : SimpleMFlag<"cumode",
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 6041ef4aeb673ef..7fe6f7df5b60d86 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2323,7 +2323,7 @@ getAMDGPUCodeObjectArgument(const Driver &D, const 
llvm::opt::ArgList &Args) {
 
 void tools::checkAMDGPUCodeObjectVersion(const Driver &

[clang] [AMDGPU] Remove Code Object V3 (PR #67118)

2023-09-22 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 22e2b805ef3c4caa971fad3656976b6e0017aff3 
73934bfbd4231a5abfaad9690977af323be7e9ba -- 
clang/include/clang/Basic/TargetOptions.h 
clang/lib/Driver/ToolChains/CommonArgs.cpp 
llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp 
llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp 
llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h 
llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp 
llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp 
llvm/lib/Target/AMDGPU/SIISelLowering.cpp 
llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp 
llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp
index 74af47e4a6b6..b51a876750b5 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp
@@ -454,9 +454,10 @@ void MetadataStreamerMsgPackV4::emitHiddenKernelArgs(
   }
 }
 
-msgpack::MapDocNode MetadataStreamerMsgPackV4::getHSAKernelProps(
-const MachineFunction &MF, const SIProgramInfo &ProgramInfo,
-unsigned CodeObjectVersion) const {
+msgpack::MapDocNode
+MetadataStreamerMsgPackV4::getHSAKernelProps(const MachineFunction &MF,
+ const SIProgramInfo &ProgramInfo,
+ unsigned CodeObjectVersion) const 
{
   const GCNSubtarget &STM = MF.getSubtarget();
   const SIMachineFunctionInfo &MFI = *MF.getInfo();
   const Function &F = MF.getFunction();
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h 
b/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h
index 370cd39e869e..18a7b5d7a963 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h
+++ b/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h
@@ -121,7 +121,6 @@ protected:
 return HSAMetadataDoc->getRoot();
   }
 
-
 public:
   MetadataStreamerMsgPackV4() = default;
   ~MetadataStreamerMsgPackV4() = default;
diff --git a/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h 
b/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h
index 5fbaff6a515e..24ee9984a4df 100644
--- a/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h
+++ b/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h
@@ -42,10 +42,7 @@ namespace AMDGPU {
 
 struct IsaVersion;
 
-enum {
-  AMDHSA_COV4 = 4,
-  AMDHSA_COV5 = 5
-};
+enum { AMDHSA_COV4 = 4, AMDHSA_COV5 = 5 };
 
 /// \returns True if \p STI is AMDHSA.
 bool isHsaAbi(const MCSubtargetInfo &STI);

``




https://github.com/llvm/llvm-project/pull/67118
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [include-cleaner] Respect the UsingShadowDecl when find headers for ambiguous std symbols. (PR #66485)

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

https://github.com/hokein closed https://github.com/llvm/llvm-project/pull/66485
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 7b3db80 - [include-cleaner] Respect the UsingShadowDecl when find headers for ambiguous std symbols. (#66485)

2023-09-22 Thread via cfe-commits

Author: Haojian Wu
Date: 2023-09-22T14:35:00+02:00
New Revision: 7b3db8079d0a736c07db30388cdedf608f4ed58f

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

LOG: [include-cleaner] Respect the UsingShadowDecl when find headers for 
ambiguous std symbols. (#66485)

In libcpp, the `std::remove(const char*)` is a using decl in std
namespace `using ::remove`, which was not handled correctly in
`headerForAmbiguousStdSymbol`

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp 
b/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
index 06e5e1812ba7218..fd2de6a17ad4a53 100644
--- a/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
+++ b/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
@@ -116,6 +117,8 @@ std::optional
 headerForAmbiguousStdSymbol(const NamedDecl *ND) {
   if (!ND->isInStdNamespace())
 return {};
+  if (auto* USD = llvm::dyn_cast(ND))
+ND = USD->getTargetDecl();
   const auto *FD = ND->getAsFunction();
   if (!FD)
 return std::nullopt;

diff  --git a/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
index 4cdcde1184a0a9e..5a2a41b2d99bdd7 100644
--- a/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -11,6 +11,7 @@
 #include "clang-include-cleaner/Analysis.h"
 #include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/FileManager.h"
@@ -587,6 +588,36 @@ TEST_F(HeadersForSymbolTest, AmbiguousStdSymbols) {
   }
 }
 
+TEST_F(HeadersForSymbolTest, AmbiguousStdSymbolsUsingShadow) {
+  Inputs.Code = R"cpp(
+void remove(char*);
+namespace std { using ::remove; }
+
+void k() {
+  std::remove("abc");
+}
+  )cpp";
+  buildAST();
+
+  // Find the DeclRefExpr in the std::remove("abc") function call.
+  struct Visitor : public RecursiveASTVisitor {
+const DeclRefExpr *Out = nullptr;
+bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
+  EXPECT_TRUE(Out == nullptr) << "Found multiple DeclRefExpr!";
+  Out = DRE;
+  return true;
+}
+  };
+  Visitor V;
+  V.TraverseDecl(AST->context().getTranslationUnitDecl());
+  ASSERT_TRUE(V.Out) << "Couldn't find a DeclRefExpr!";
+  EXPECT_THAT(headersForSymbol(*(V.Out->getFoundDecl()),
+   AST->sourceManager(), &PI),
+  UnorderedElementsAre(
+  Header(*tooling::stdlib::Header::named("";
+}
+
+
 TEST_F(HeadersForSymbolTest, StandardHeaders) {
   Inputs.Code = "void assert();";
   buildAST();



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


[clang] [cmake] Add LLVM_FORCE_VC_REVISION option (PR #67125)

2023-09-22 Thread David Truby via cfe-commits

https://github.com/DavidTruby created 
https://github.com/llvm/llvm-project/pull/67125

This patch adds a LLVM_FORCE_VC_REVISION option to force a custom
VC revision to be included instead of trying to fetch one from a
git command. This is helpful in environments where git is not
available or is non-functional but the vc revision is available
through some other means.


>From 0690521dd83e8fae81f65bce173ed7189ff9307b Mon Sep 17 00:00:00 2001
From: David Truby 
Date: Fri, 22 Sep 2023 12:22:49 +
Subject: [PATCH] [cmake] Add LLVM_FORCE_VC_REVISION option

This patch adds a LLVM_FORCE_VC_REVISION option to force a custom
VC revision to be included instead of trying to fetch one from a
git command. This is helpful in environments where git is not
available or is non-functional but the vc revision is available
through some other means.
---
 clang/lib/Basic/CMakeLists.txt  | 2 ++
 flang/lib/Common/CMakeLists.txt | 4 +++-
 lld/Common/CMakeLists.txt   | 2 ++
 lldb/source/Version/CMakeLists.txt  | 2 ++
 llvm/CMakeLists.txt | 6 ++
 llvm/cmake/modules/GenerateVersionFromVCS.cmake | 9 -
 llvm/include/llvm/Support/CMakeLists.txt| 4 
 7 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index db59d7dd96da0a4..36ccf7d0809453e 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -39,6 +39,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DHEADER_FILE=${version_inc}"
"-DLLVM_VC_REPOSITORY=${llvm_vc_repository}"
"-DLLVM_VC_REVISION=${llvm_vc_revision}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/flang/lib/Common/CMakeLists.txt b/flang/lib/Common/CMakeLists.txt
index 81cee82e04b88ae..c6f818ad27cd19a 100644
--- a/flang/lib/Common/CMakeLists.txt
+++ b/flang/lib/Common/CMakeLists.txt
@@ -12,7 +12,7 @@ endif()
 if(flang_vc AND LLVM_APPEND_VC_REV)
   set(flang_source_dir ${FLANG_SOURCE_DIR})
 endif()
-
+ 
 # Create custom target to generate the VC revision include.
 add_custom_command(OUTPUT "${version_inc}"
   DEPENDS "${llvm_vc}" "${flang_vc}" "${generate_vcs_version_script}"
@@ -20,6 +20,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DLLVM_SOURCE_DIR=${llvm_source_dir}"
"-DFLANG_SOURCE_DIR=${flang_source_dir}"
"-DHEADER_FILE=${version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lld/Common/CMakeLists.txt b/lld/Common/CMakeLists.txt
index c975da2a49b6bda..4f503d04f7844f7 100644
--- a/lld/Common/CMakeLists.txt
+++ b/lld/Common/CMakeLists.txt
@@ -13,6 +13,8 @@ add_custom_command(OUTPUT "${version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLD"
   "-DLLD_SOURCE_DIR=${lld_source_dir}"
   "-DHEADER_FILE=${version_inc}"
+  "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+  "-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
   -P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lldb/source/Version/CMakeLists.txt 
b/lldb/source/Version/CMakeLists.txt
index c1393b5dd6e6b62..90fe53d52cc5d05 100644
--- a/lldb/source/Version/CMakeLists.txt
+++ b/lldb/source/Version/CMakeLists.txt
@@ -17,6 +17,8 @@ add_custom_command(OUTPUT "${vcs_version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLDB"
"-DLLDB_SOURCE_DIR=${lldb_source_dir}"
"-DHEADER_FILE=${vcs_version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 set_source_files_properties("${vcs_version_inc}"
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index fa39c7554de1f61..5985256498dcbb2 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -325,6 +325,12 @@ include(VersionFromVCS)
 option(LLVM_APPEND_VC_REV
   "Embed the version control system revision in LLVM" ON)
 
+set(LLVM_FORCE_VC_REVISION
+  "" CACHE STRING "Force custom VC revision for LLVM_APPEND_VC_REV")
+
+set(LLVM_FORCE_VC_REPOSITORY
+  "" CACHE STRING "Force custom VC repository for LLVM_APPEND_VC_REV")
+
 option(LLVM_TOOL_LLVM_DRIVER_BUILD "Enables building the llvm multicall tool" 
OFF)
 
 set(PACKAGE_NAME LLVM)
diff --git a

[clang] [cmake] Add LLVM_FORCE_VC_REVISION option (PR #67125)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This patch adds a LLVM_FORCE_VC_REVISION option to force a custom
VC revision to be included instead of trying to fetch one from a
git command. This is helpful in environments where git is not
available or is non-functional but the vc revision is available
through some other means.


---
Full diff: https://github.com/llvm/llvm-project/pull/67125.diff


7 Files Affected:

- (modified) clang/lib/Basic/CMakeLists.txt (+2) 
- (modified) flang/lib/Common/CMakeLists.txt (+3-1) 
- (modified) lld/Common/CMakeLists.txt (+2) 
- (modified) lldb/source/Version/CMakeLists.txt (+2) 
- (modified) llvm/CMakeLists.txt (+6) 
- (modified) llvm/cmake/modules/GenerateVersionFromVCS.cmake (+8-1) 
- (modified) llvm/include/llvm/Support/CMakeLists.txt (+4) 


``diff
diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index db59d7dd96da0a4..36ccf7d0809453e 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -39,6 +39,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DHEADER_FILE=${version_inc}"
"-DLLVM_VC_REPOSITORY=${llvm_vc_repository}"
"-DLLVM_VC_REVISION=${llvm_vc_revision}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/flang/lib/Common/CMakeLists.txt b/flang/lib/Common/CMakeLists.txt
index 81cee82e04b88ae..c6f818ad27cd19a 100644
--- a/flang/lib/Common/CMakeLists.txt
+++ b/flang/lib/Common/CMakeLists.txt
@@ -12,7 +12,7 @@ endif()
 if(flang_vc AND LLVM_APPEND_VC_REV)
   set(flang_source_dir ${FLANG_SOURCE_DIR})
 endif()
-
+ 
 # Create custom target to generate the VC revision include.
 add_custom_command(OUTPUT "${version_inc}"
   DEPENDS "${llvm_vc}" "${flang_vc}" "${generate_vcs_version_script}"
@@ -20,6 +20,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DLLVM_SOURCE_DIR=${llvm_source_dir}"
"-DFLANG_SOURCE_DIR=${flang_source_dir}"
"-DHEADER_FILE=${version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lld/Common/CMakeLists.txt b/lld/Common/CMakeLists.txt
index c975da2a49b6bda..4f503d04f7844f7 100644
--- a/lld/Common/CMakeLists.txt
+++ b/lld/Common/CMakeLists.txt
@@ -13,6 +13,8 @@ add_custom_command(OUTPUT "${version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLD"
   "-DLLD_SOURCE_DIR=${lld_source_dir}"
   "-DHEADER_FILE=${version_inc}"
+  "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+  "-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
   -P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lldb/source/Version/CMakeLists.txt 
b/lldb/source/Version/CMakeLists.txt
index c1393b5dd6e6b62..90fe53d52cc5d05 100644
--- a/lldb/source/Version/CMakeLists.txt
+++ b/lldb/source/Version/CMakeLists.txt
@@ -17,6 +17,8 @@ add_custom_command(OUTPUT "${vcs_version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLDB"
"-DLLDB_SOURCE_DIR=${lldb_source_dir}"
"-DHEADER_FILE=${vcs_version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 set_source_files_properties("${vcs_version_inc}"
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index fa39c7554de1f61..5985256498dcbb2 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -325,6 +325,12 @@ include(VersionFromVCS)
 option(LLVM_APPEND_VC_REV
   "Embed the version control system revision in LLVM" ON)
 
+set(LLVM_FORCE_VC_REVISION
+  "" CACHE STRING "Force custom VC revision for LLVM_APPEND_VC_REV")
+
+set(LLVM_FORCE_VC_REPOSITORY
+  "" CACHE STRING "Force custom VC repository for LLVM_APPEND_VC_REV")
+
 option(LLVM_TOOL_LLVM_DRIVER_BUILD "Enables building the llvm multicall tool" 
OFF)
 
 set(PACKAGE_NAME LLVM)
diff --git a/llvm/cmake/modules/GenerateVersionFromVCS.cmake 
b/llvm/cmake/modules/GenerateVersionFromVCS.cmake
index 9cd780e5aa162c0..1b3b2946e62b25c 100644
--- a/llvm/cmake/modules/GenerateVersionFromVCS.cmake
+++ b/llvm/cmake/modules/GenerateVersionFromVCS.cmake
@@ -36,7 +36,14 @@ function(append_info name revision repository)
 endfunction()
 
 foreach(name IN LISTS NAMES)
-  if(${name}_VC_REPOSITORY AND ${name}_VC_REVISION)
+  if(LLVM_FORCE_VC_REVISION AND LLVM_FORCE_VC_REPOSITORY)
+set(re

[clang-tools-extra] [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. (PR #66120)

2023-09-22 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam edited 
https://github.com/llvm/llvm-project/pull/66120
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. (PR #66120)

2023-09-22 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam edited 
https://github.com/llvm/llvm-project/pull/66120
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 265568c - [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. (#66120)

2023-09-22 Thread via cfe-commits

Author: Zahira Ammarguellat
Date: 2023-09-22T08:45:53-04:00
New Revision: 265568c136f94b108790e9be73cd8071e714aad1

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

LOG: [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. 
(#66120)

Predefined macro FUNCTION (and __FUNC__) in clang is not returning the
same string than MS for templated functions.

See https://godbolt.org/z/88n1rGs3b

For this test case MSVC is returning:
function: TestClass::TestClass
func: TestClass

-

Co-authored-by: Reid Kleckner 

Added: 


Modified: 
clang/include/clang/AST/PrettyPrinter.h
clang/lib/AST/Expr.cpp
clang/lib/AST/TypePrinter.cpp
clang/test/AST/Interp/literals.cpp
clang/test/Analysis/eval-predefined-exprs.cpp
clang/test/CodeGenCXX/predefined-expr.cpp
clang/test/SemaCXX/source_location.cpp

Removed: 




diff  --git a/clang/include/clang/AST/PrettyPrinter.h 
b/clang/include/clang/AST/PrettyPrinter.h
index cee3cce7729c30f..17d4e1a326d31ca 100644
--- a/clang/include/clang/AST/PrettyPrinter.h
+++ b/clang/include/clang/AST/PrettyPrinter.h
@@ -76,8 +76,8 @@ struct PrintingPolicy {
 SuppressImplicitBase(false), FullyQualifiedName(false),
 PrintCanonicalTypes(false), PrintInjectedClassNameWithArguments(true),
 UsePreferredNames(true), AlwaysIncludeTypeForTemplateArgument(false),
-CleanUglifiedParameters(false), EntireContentsOfLargeArray(true),
-UseEnumerators(true) {}
+UseClassForTemplateArgument(false), CleanUglifiedParameters(false),
+EntireContentsOfLargeArray(true), UseEnumerators(true) {}
 
   /// Adjust this printing policy for cases where it's known that we're
   /// printing C++ code (for instance, if AST dumping reaches a C++-only
@@ -291,6 +291,10 @@ struct PrintingPolicy {
   /// parameters.
   unsigned AlwaysIncludeTypeForTemplateArgument : 1;
 
+  // Prints "class" keyword before type template arguments. This is used when
+  // printing a function via the _FUNCTION__ or __func__ macro in MSVC mode.
+  unsigned UseClassForTemplateArgument : 1;
+
   /// Whether to strip underscores when printing reserved parameter names.
   /// e.g. std::vector becomes std::vector.
   /// This only affects parameter names, and so describes a compatible API.

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 4f3837371b3fc5e..af82ca0784af413 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -772,18 +772,21 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 return std::string(Out.str());
   }
   if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
-if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
-IK != FuncSig && IK != LFuncSig)
+const auto &LO = Context.getLangOpts();
+if (((IK == Func || IK == Function) && !LO.MicrosoftExt) ||
+(IK == LFunction && LO.MicrosoftExt))
   return FD->getNameAsString();
 
 SmallString<256> Name;
 llvm::raw_svector_ostream Out(Name);
 
-if (const CXXMethodDecl *MD = dyn_cast(FD)) {
-  if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
-Out << "virtual ";
-  if (MD->isStatic())
-Out << "static ";
+if (IK != Function) {
+  if (const CXXMethodDecl *MD = dyn_cast(FD)) {
+if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
+  Out << "virtual ";
+if (MD->isStatic())
+  Out << "static ";
+  }
 }
 
 class PrettyCallbacks final : public PrintingCallbacks {
@@ -798,9 +801,10 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 private:
   const LangOptions &LO;
 };
-PrintingPolicy Policy(Context.getLangOpts());
-PrettyCallbacks PrettyCB(Context.getLangOpts());
+PrintingPolicy Policy(LO);
+PrettyCallbacks PrettyCB(LO);
 Policy.Callbacks = &PrettyCB;
+Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 
@@ -827,6 +831,11 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 
 FD->printQualifiedName(POut, Policy);
 
+if ((IK == Function || IK == Func) && LO.MicrosoftExt) {
+  Out << Proto;
+  return std::string(Name);
+}
+
 POut << "(";
 if (FT) {
   for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {

diff  --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index eb69d0bb8755b48..3771a29f26b173f 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2218,6 +2218,10 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 } else {
   if (!FirstArg)
 OS << Comma;
+  if (Policy.UseClassF

[clang] [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. (PR #66120)

2023-09-22 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam closed 
https://github.com/llvm/llvm-project/pull/66120
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-cl] Fix value of __FUNCTION__ and __FUNC__ in MSVC mode for c++. (PR #66120)

2023-09-22 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam closed 
https://github.com/llvm/llvm-project/pull/66120
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153156: [Clang] CWG1473: do not err on the lack of space after operator""

2023-09-22 Thread James Y Knight via Phabricator via cfe-commits
jyknight reopened this revision.
jyknight added a comment.
This revision is now accepted and ready to land.

Reopening the review since it ended up reverted, but I do think we DO want to 
have at least some of the changes proposed here (and/or from the pending 
D158372 ). At the very least, the existing 
diagnostics are currently quite misleading/wrong, and the work here was helping 
to improve that.

Taking this example:

  float operator ""XXX(const char *);

It results in three diagnostics:

  :1:18: error: invalid suffix on literal; C++11 requires a space 
between literal and identifier [-Wreserved-user-defined-literal]
  1 | float operator ""XXX(const char *);
|  ^
|   
  :1:18: warning: identifier 'XXX' preceded by whitespace in a literal 
operator declaration is deprecated [-Wdeprecated-literal-operator]
  1 | float operator ""XXX(const char *);
|   ~~~^~~
|   operator""XXX
  :1:7: warning: user-defined literal suffixes not starting with '_' 
are reserved; no literal will invoke this operator [-Wuser-defined-literals]
  1 | float operator ""XXX(const char *);
|   ^

The first and third are enabled by default, the second is not.

The first only describes what to do if you wanted it to be string-concat (which 
would be invalid here...), not if you wanted it to be an UDL-operator 
definition. And it's not clear that "identifier" really means "macro expanding 
to a string that I assume you meant" in the message. I think we should not emit 
that message ONLY if there is a macro named "XXX".

The second is just incorrect -- there's already no space in the user’s 
source-code, the compiler just added one internally!

The third seems OK, although if we actually do permit calling such UDLs, would 
want to remove the last phrase...

Then, consider:

  float operator ""XXX(const char *);
  float x1 = ""XXX;

One might reasonably expect to build when -Wno-reserved-user-defined-literal is 
specified. But, currently, it does not.

I think a reasonable compromise behavior would be:

1. If the literal suffix is nonstandard (that is: doesn't start with `_`, and 
isn't a standard-defined UDL suffix), then try macro-expanding the suffix.
2. If there is an expansion, use the macro-expansion, instead of treating it as 
UDL, and diagnose as an error-by-default under -Wreserved-user-defined-literal.
3. On the other hand, if there is no macro-expansion, then let it be parsed as 
a nonstandard UDL, and emit a different diagnostic message under 
error-by-default -Wreserved-user-defined-literal.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153156

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


[clang] [cmake] Add LLVM_FORCE_VC_REVISION option (PR #67125)

2023-09-22 Thread Tobias Hieta via cfe-commits

https://github.com/tru commented:

It looks fine to me, but maybe we should have an entry for it in the 
`CMake.rst` documentation since the other `LLVM_*_VC` options are documented.

https://github.com/llvm/llvm-project/pull/67125
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Better bitfield access units (PR #65742)

2023-09-22 Thread Nathan Sidwell via cfe-commits

urnathan wrote:

Ping?  Anything more I can do to progress this?

https://github.com/llvm/llvm-project/pull/65742
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Interp] Diagnose uninitialized bases (PR #67131)

2023-09-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/67131

None

>From 0f52eec7bba4ecbd5df75d8a663f1c374771e283 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 22 Sep 2023 15:09:14 +0200
Subject: [PATCH] [clang][Interp] Diagnose uninitialized bases

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp  |  4 +-
 clang/lib/AST/Interp/ByteCodeStmtGen.cpp  |  2 +-
 clang/lib/AST/Interp/Interp.cpp   |  6 ++
 clang/lib/AST/Interp/Interp.h |  6 ++
 clang/lib/AST/Interp/Opcodes.td   |  4 +
 .../constexpr-subobj-initialization.cpp   | 73 +++
 6 files changed, 92 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/AST/Interp/constexpr-subobj-initialization.cpp

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e813d4fa651ceaf..3e9af148b7a5aab 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -535,7 +535,7 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits,
 if (!this->visitInitializer(Init))
   return false;
 
-if (!this->emitPopPtr(E))
+if (!this->emitInitPtrPop(E))
   return false;
 // Base initializers don't increase InitIndex, since they don't count
 // into the Record's fields.
@@ -1671,7 +1671,7 @@ bool 
ByteCodeExprGen::visitZeroRecordInitializer(const Record *R,
   return false;
 if (!this->visitZeroRecordInitializer(B.R, E))
   return false;
-if (!this->emitPopPtr(E))
+if (!this->emitInitPtrPop(E))
   return false;
   }
 
diff --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 22a6908daf8b3c2..302e04e84fe4af7 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -194,7 +194,7 @@ bool ByteCodeStmtGen::visitFunc(const FunctionDecl 
*F) {
   return false;
 if (!this->visitInitializer(InitExpr))
   return false;
-if (!this->emitPopPtr(InitExpr))
+if (!this->emitInitPtrPop(InitExpr))
   return false;
   }
 }
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..8e851595963184c 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -467,6 +467,12 @@ static bool CheckFieldsInitialized(InterpState &S, CodePtr 
OpPC,
   // Check Fields in all bases
   for (const Record::Base &B : R->bases()) {
 Pointer P = BasePtr.atField(B.Offset);
+if (!P.isInitialized()) {
+  S.FFDiag(BasePtr.getDeclDesc()->asDecl()->getLocation(),
+   diag::note_constexpr_uninitialized_base)
+  << B.Desc->getType();
+  return false;
+}
 Result &= CheckFieldsInitialized(S, OpPC, P, B.R);
   }
 
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 8453856e526a6b2..14ce1f4c99f3ef1 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1212,6 +1212,12 @@ inline bool GetPtrThisBase(InterpState &S, CodePtr OpPC, 
uint32_t Off) {
   return true;
 }
 
+inline bool InitPtrPop(InterpState &S, CodePtr OpPC) {
+  const Pointer &Ptr = S.Stk.pop();
+  Ptr.initialize();
+  return true;
+}
+
 inline bool VirtBaseHelper(InterpState &S, CodePtr OpPC, const RecordDecl 
*Decl,
const Pointer &Ptr) {
   Pointer Base = Ptr;
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index eeb71db125fef73..73e88939d3734d8 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -301,6 +301,10 @@ def GetPtrBasePop : Opcode {
   let Args = [ArgUint32];
 }
 
+def InitPtrPop : Opcode {
+  let Args = [];
+}
+
 def GetPtrDerivedPop : Opcode {
   let Args = [ArgUint32];
 }
diff --git a/clang/test/AST/Interp/constexpr-subobj-initialization.cpp 
b/clang/test/AST/Interp/constexpr-subobj-initialization.cpp
new file mode 100644
index 000..4976b165468bd61
--- /dev/null
+++ b/clang/test/AST/Interp/constexpr-subobj-initialization.cpp
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s 
-fexperimental-new-constant-interpreter
+
+/// This is like the version in test/SemaCXX/, but some of the
+/// output types and their location has been adapted.
+/// Differences:
+///   1) The type of the uninitialized base class is printed WITH the 
namespace,
+///  i.e. 'baseclass_uninit::DelBase' instead of just 'DelBase'.
+///   2) The location is not the base specifier declaration, but the call site
+///  of the constructor.
+
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been 
explicitly marked deleted here}}
+};
+
+struct Foo : DelBase {
+  constexpr Foo() {}; // expected-error {{call to deleted constructor of 
'DelBase'}}
+};
+constexpr Foo f; // expected-error {{must be initialized by a

[clang] [Clang][CodeGen] Add __builtin_bcopy (PR #67130)

2023-09-22 Thread Carlos Eduardo Seo via cfe-commits

https://github.com/ceseo created https://github.com/llvm/llvm-project/pull/67130

Add __builtin_bcopy to the list of GNU builtins. This was causing a series of 
test failures in glibc.

Adjust the tests to reflect the changes in codegen.

Fixes #51409.
Fixes #63065.

>From af8c9b6d0757c109aa83a35248d58ff15f9384dd Mon Sep 17 00:00:00 2001
From: Carlos Eduardo Seo 
Date: Wed, 16 Aug 2023 21:56:54 +
Subject: [PATCH] [Clang][Codegen] Add __builtin_bcopy

Add __builtin_bcopy to the list of GNU builtins. This was causing a series of
test failures in glibc.

Modify the tests to reflect the addition of the builtin.

Fixes #51409.
Fixes #63065.
---
 clang/include/clang/Basic/Builtins.def |  3 ++-
 clang/lib/AST/Decl.cpp |  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp| 14 ++
 clang/test/Analysis/bstring.c  |  3 +--
 clang/test/Analysis/security-syntax-checks.m   |  4 ++--
 .../CodeGen/PowerPC/builtins-ppc-xlcompat-macros.c |  6 +++---
 6 files changed, 28 insertions(+), 8 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 586dcf05170eb58..6ea8484606cfd5d 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -565,7 +565,7 @@ BUILTIN(__builtin_va_copy, "vAA", "n")
 BUILTIN(__builtin_stdarg_start, "vA.", "nt")
 BUILTIN(__builtin_assume_aligned, "v*vC*z.", "nctE")
 BUILTIN(__builtin_bcmp, "ivC*vC*z", "FnE")
-BUILTIN(__builtin_bcopy, "vv*v*z", "n")
+BUILTIN(__builtin_bcopy, "vvC*v*z", "nF")
 BUILTIN(__builtin_bzero, "vv*z", "nF")
 BUILTIN(__builtin_free, "vv*", "nF")
 BUILTIN(__builtin_malloc, "v*z", "nF")
@@ -1161,6 +1161,7 @@ LIBBUILTIN(strndup, "c*cC*z", "f", STRING_H, 
ALL_GNU_LANGUAGES)
 LIBBUILTIN(index, "c*cC*i",   "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(rindex, "c*cC*i",  "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(bzero, "vv*z", "f", STRINGS_H, ALL_GNU_LANGUAGES)
+LIBBUILTIN(bcopy, "vvC*v*z",  "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(bcmp, "ivC*vC*z",  "fE",STRINGS_H, ALL_GNU_LANGUAGES)
 // In some systems str[n]casejmp is a macro that expands to _str[n]icmp.
 // We undefine then here to avoid wrong name.
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 6109829cf20a678..d5507b7c23c3e5c 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -4356,6 +4356,10 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
   case Builtin::BIbzero:
 return Builtin::BIbzero;
 
+  case Builtin::BI__builtin_bcopy:
+  case Builtin::BIbcopy:
+return Builtin::BIbcopy;
+
   case Builtin::BIfree:
 return Builtin::BIfree;
 
@@ -4387,6 +4391,8 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
 return Builtin::BIstrlen;
   if (FnInfo->isStr("bzero"))
 return Builtin::BIbzero;
+  if (FnInfo->isStr("bcopy"))
+return Builtin::BIbcopy;
 } else if (isInStdNamespace()) {
   if (FnInfo->isStr("free"))
 return Builtin::BIfree;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 27e4eb630356412..d7232e1e620893d 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3676,6 +3676,20 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
 return RValue::get(nullptr);
   }
+
+  case Builtin::BIbcopy:
+  case Builtin::BI__builtin_bcopy: {
+Address Src = EmitPointerWithAlignment(E->getArg(0));
+Address Dest = EmitPointerWithAlignment(E->getArg(1));
+Value *SizeVal = EmitScalarExpr(E->getArg(2));
+EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
+E->getArg(0)->getExprLoc(), FD, 0);
+EmitNonNullArgCheck(RValue::get(Dest.getPointer()), 
E->getArg(1)->getType(),
+E->getArg(1)->getExprLoc(), FD, 0);
+Builder.CreateMemMove(Dest, Src, SizeVal, false);
+return RValue::get(Dest.getPointer());
+  }
+
   case Builtin::BImemcpy:
   case Builtin::BI__builtin_memcpy:
   case Builtin::BImempcpy:
diff --git a/clang/test/Analysis/bstring.c b/clang/test/Analysis/bstring.c
index a7c7bdb23683e76..5d86241a4ac9a81 100644
--- a/clang/test/Analysis/bstring.c
+++ b/clang/test/Analysis/bstring.c
@@ -483,8 +483,7 @@ int memcmp8(char *a, size_t n) {
 //===--===
 
 #define bcopy BUILTIN(bcopy)
-// __builtin_bcopy is not defined with const in Builtins.def.
-void bcopy(/*const*/ void *s1, void *s2, size_t n);
+void bcopy(const void *s1, void *s2, size_t n);
 
 
 void bcopy0 (void) {
diff --git a/clang/test/Analysis/security-syntax-checks.m 
b/clang/test/Analysis/security-syntax-checks.m
index ab6a5311f49efad..154f0c1bae427c0 100644
--- a/clang/test/Analysis/security-syntax-check

[clang] [Clang][CodeGen] Add __builtin_bcopy (PR #67130)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen


Changes

Add __builtin_bcopy to the list of GNU builtins. This was causing a series of 
test failures in glibc.

Adjust the tests to reflect the changes in codegen.

Fixes #51409.
Fixes #63065.

---
Full diff: https://github.com/llvm/llvm-project/pull/67130.diff


6 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.def (+2-1) 
- (modified) clang/lib/AST/Decl.cpp (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+14) 
- (modified) clang/test/Analysis/bstring.c (+1-2) 
- (modified) clang/test/Analysis/security-syntax-checks.m (+2-2) 
- (modified) clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-macros.c (+3-3) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 586dcf05170eb58..6ea8484606cfd5d 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -565,7 +565,7 @@ BUILTIN(__builtin_va_copy, "vAA", "n")
 BUILTIN(__builtin_stdarg_start, "vA.", "nt")
 BUILTIN(__builtin_assume_aligned, "v*vC*z.", "nctE")
 BUILTIN(__builtin_bcmp, "ivC*vC*z", "FnE")
-BUILTIN(__builtin_bcopy, "vv*v*z", "n")
+BUILTIN(__builtin_bcopy, "vvC*v*z", "nF")
 BUILTIN(__builtin_bzero, "vv*z", "nF")
 BUILTIN(__builtin_free, "vv*", "nF")
 BUILTIN(__builtin_malloc, "v*z", "nF")
@@ -1161,6 +1161,7 @@ LIBBUILTIN(strndup, "c*cC*z", "f", STRING_H, 
ALL_GNU_LANGUAGES)
 LIBBUILTIN(index, "c*cC*i",   "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(rindex, "c*cC*i",  "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(bzero, "vv*z", "f", STRINGS_H, ALL_GNU_LANGUAGES)
+LIBBUILTIN(bcopy, "vvC*v*z",  "f", STRINGS_H, ALL_GNU_LANGUAGES)
 LIBBUILTIN(bcmp, "ivC*vC*z",  "fE",STRINGS_H, ALL_GNU_LANGUAGES)
 // In some systems str[n]casejmp is a macro that expands to _str[n]icmp.
 // We undefine then here to avoid wrong name.
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 08ae2087cfe70eb..82d1ddadeac92ba 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -4356,6 +4356,10 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
   case Builtin::BIbzero:
 return Builtin::BIbzero;
 
+  case Builtin::BI__builtin_bcopy:
+  case Builtin::BIbcopy:
+return Builtin::BIbcopy;
+
   case Builtin::BIfree:
 return Builtin::BIfree;
 
@@ -4387,6 +4391,8 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
 return Builtin::BIstrlen;
   if (FnInfo->isStr("bzero"))
 return Builtin::BIbzero;
+  if (FnInfo->isStr("bcopy"))
+return Builtin::BIbcopy;
 } else if (isInStdNamespace()) {
   if (FnInfo->isStr("free"))
 return Builtin::BIfree;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 4a73403cb3b9a72..c175f274319b8c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3703,6 +3703,20 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
 return RValue::get(nullptr);
   }
+
+  case Builtin::BIbcopy:
+  case Builtin::BI__builtin_bcopy: {
+Address Src = EmitPointerWithAlignment(E->getArg(0));
+Address Dest = EmitPointerWithAlignment(E->getArg(1));
+Value *SizeVal = EmitScalarExpr(E->getArg(2));
+EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
+E->getArg(0)->getExprLoc(), FD, 0);
+EmitNonNullArgCheck(RValue::get(Dest.getPointer()), 
E->getArg(1)->getType(),
+E->getArg(1)->getExprLoc(), FD, 0);
+Builder.CreateMemMove(Dest, Src, SizeVal, false);
+return RValue::get(Dest.getPointer());
+  }
+
   case Builtin::BImemcpy:
   case Builtin::BI__builtin_memcpy:
   case Builtin::BImempcpy:
diff --git a/clang/test/Analysis/bstring.c b/clang/test/Analysis/bstring.c
index a7c7bdb23683e76..5d86241a4ac9a81 100644
--- a/clang/test/Analysis/bstring.c
+++ b/clang/test/Analysis/bstring.c
@@ -483,8 +483,7 @@ int memcmp8(char *a, size_t n) {
 //===--===
 
 #define bcopy BUILTIN(bcopy)
-// __builtin_bcopy is not defined with const in Builtins.def.
-void bcopy(/*const*/ void *s1, void *s2, size_t n);
+void bcopy(const void *s1, void *s2, size_t n);
 
 
 void bcopy0 (void) {
diff --git a/clang/test/Analysis/security-syntax-checks.m 
b/clang/test/Analysis/security-syntax-checks.m
index ab6a5311f49efad..154f0c1bae427c0 100644
--- a/clang/test/Analysis/security-syntax-checks.m
+++ b/clang/test/Analysis/security-syntax-checks.m
@@ -57,9 +57,9 @@ int test_bcmp(void *a, void *b, size_t n) {
 }
 
 // Obsolete function bcopy
-void bcopy(void *, void *, size_t);
+void bcopy(const void *, void *, size_t);
 
-void test_bcopy(void *a, void *b, size_t n) {
+void test_bcopy(const void *a, void *b, size_t n) {
   bcopy(a, b, n); // expected-warning{{The bcopy

[clang] [cmake] Add LLVM_FORCE_VC_REVISION option (PR #67125)

2023-09-22 Thread David Truby via cfe-commits

https://github.com/DavidTruby updated 
https://github.com/llvm/llvm-project/pull/67125

>From 0690521dd83e8fae81f65bce173ed7189ff9307b Mon Sep 17 00:00:00 2001
From: David Truby 
Date: Fri, 22 Sep 2023 12:22:49 +
Subject: [PATCH 1/2] [cmake] Add LLVM_FORCE_VC_REVISION option

This patch adds a LLVM_FORCE_VC_REVISION option to force a custom
VC revision to be included instead of trying to fetch one from a
git command. This is helpful in environments where git is not
available or is non-functional but the vc revision is available
through some other means.
---
 clang/lib/Basic/CMakeLists.txt  | 2 ++
 flang/lib/Common/CMakeLists.txt | 4 +++-
 lld/Common/CMakeLists.txt   | 2 ++
 lldb/source/Version/CMakeLists.txt  | 2 ++
 llvm/CMakeLists.txt | 6 ++
 llvm/cmake/modules/GenerateVersionFromVCS.cmake | 9 -
 llvm/include/llvm/Support/CMakeLists.txt| 4 
 7 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index db59d7dd96da0a4..36ccf7d0809453e 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -39,6 +39,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DHEADER_FILE=${version_inc}"
"-DLLVM_VC_REPOSITORY=${llvm_vc_repository}"
"-DLLVM_VC_REVISION=${llvm_vc_revision}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/flang/lib/Common/CMakeLists.txt b/flang/lib/Common/CMakeLists.txt
index 81cee82e04b88ae..c6f818ad27cd19a 100644
--- a/flang/lib/Common/CMakeLists.txt
+++ b/flang/lib/Common/CMakeLists.txt
@@ -12,7 +12,7 @@ endif()
 if(flang_vc AND LLVM_APPEND_VC_REV)
   set(flang_source_dir ${FLANG_SOURCE_DIR})
 endif()
-
+ 
 # Create custom target to generate the VC revision include.
 add_custom_command(OUTPUT "${version_inc}"
   DEPENDS "${llvm_vc}" "${flang_vc}" "${generate_vcs_version_script}"
@@ -20,6 +20,8 @@ add_custom_command(OUTPUT "${version_inc}"
"-DLLVM_SOURCE_DIR=${llvm_source_dir}"
"-DFLANG_SOURCE_DIR=${flang_source_dir}"
"-DHEADER_FILE=${version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lld/Common/CMakeLists.txt b/lld/Common/CMakeLists.txt
index c975da2a49b6bda..4f503d04f7844f7 100644
--- a/lld/Common/CMakeLists.txt
+++ b/lld/Common/CMakeLists.txt
@@ -13,6 +13,8 @@ add_custom_command(OUTPUT "${version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLD"
   "-DLLD_SOURCE_DIR=${lld_source_dir}"
   "-DHEADER_FILE=${version_inc}"
+  "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+  "-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
   -P "${generate_vcs_version_script}")
 
 # Mark the generated header as being generated.
diff --git a/lldb/source/Version/CMakeLists.txt 
b/lldb/source/Version/CMakeLists.txt
index c1393b5dd6e6b62..90fe53d52cc5d05 100644
--- a/lldb/source/Version/CMakeLists.txt
+++ b/lldb/source/Version/CMakeLists.txt
@@ -17,6 +17,8 @@ add_custom_command(OUTPUT "${vcs_version_inc}"
   COMMAND ${CMAKE_COMMAND} "-DNAMES=LLDB"
"-DLLDB_SOURCE_DIR=${lldb_source_dir}"
"-DHEADER_FILE=${vcs_version_inc}"
+   "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}"
+   
"-DLLVM_FORCE_VC_REPOSITORY=${LLVM_FORCE_VC_REPOSITORY}"
-P "${generate_vcs_version_script}")
 
 set_source_files_properties("${vcs_version_inc}"
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index fa39c7554de1f61..5985256498dcbb2 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -325,6 +325,12 @@ include(VersionFromVCS)
 option(LLVM_APPEND_VC_REV
   "Embed the version control system revision in LLVM" ON)
 
+set(LLVM_FORCE_VC_REVISION
+  "" CACHE STRING "Force custom VC revision for LLVM_APPEND_VC_REV")
+
+set(LLVM_FORCE_VC_REPOSITORY
+  "" CACHE STRING "Force custom VC repository for LLVM_APPEND_VC_REV")
+
 option(LLVM_TOOL_LLVM_DRIVER_BUILD "Enables building the llvm multicall tool" 
OFF)
 
 set(PACKAGE_NAME LLVM)
diff --git a/llvm/cmake/modules/GenerateVersionFromVCS.cmake 
b/llvm/cmake/modules/GenerateVersionFromVCS.cmake
index 9cd780e5aa162c0..1b3b2946e62b25c 100644
--- a/llvm/cmake/modules/GenerateVersionFromVCS.cmake
+++ b/llvm/cmake/modules/GenerateVersionFromVCS.cmake
@@ -36,7 +36,14 @@ function

[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-09-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/67147

None

>From 80013d2e1b70aed0f7e225fab72136b6b4599cea Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 22 Sep 2023 16:27:11 +0200
Subject: [PATCH] [clang][Interp] Handle CXXScalarValueInitExprs

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 6 ++
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 1 +
 clang/test/AST/Interp/literals.cpp   | 7 +++
 3 files changed, 14 insertions(+)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e813d4fa651ceaf..c804bab7ce567d0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1488,6 +1488,12 @@ bool ByteCodeExprGen::VisitOffsetOfExpr(const 
OffsetOfExpr *E) {
   return this->emitOffsetOf(T, E, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXScalarValueInitExpr(
+const CXXScalarValueInitExpr *E) {
+  return this->visitZeroInitializer(E->getType(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..7cfe4d9251c5f05 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -106,6 +106,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
+  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index ceda59405ea9105..6ae8df79f52accb 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -31,6 +31,13 @@ static_assert(b, "");
 constexpr int one = true;
 static_assert(one == 1, "");
 
+constexpr bool b2 = bool();
+static_assert(!b2, "");
+constexpr int ScalarInitInt = int();
+static_assert(ScalarInitInt == 0, "");
+constexpr float ScalarInitFloat = float();
+static_assert(ScalarInitInt == 0.0f, "");
+
 namespace IntegralCasts {
   constexpr int i = 12;
   constexpr unsigned int ui = i;

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


[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-09-22 Thread Timm Baeder via cfe-commits


@@ -31,6 +31,13 @@ static_assert(b, "");
 constexpr int one = true;
 static_assert(one == 1, "");
 
+constexpr bool b2 = bool();
+static_assert(!b2, "");
+constexpr int ScalarInitInt = int();
+static_assert(ScalarInitInt == 0, "");
+constexpr float ScalarInitFloat = float();
+static_assert(ScalarInitInt == 0.0f, "");

tbaederr wrote:

```suggestion
static_assert(ScalarInitFloat == 0.0f, "");
```

https://github.com/llvm/llvm-project/pull/67147
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-09-22 Thread Erich Keane via cfe-commits

https://github.com/erichkeane approved this pull request.

Implementation looks simple/right enough.  LGTM.

https://github.com/llvm/llvm-project/pull/67147
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 36bd5bd - [dataflow] use true/false literals in formulas, rather than variables

2023-09-22 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2023-09-22T17:12:20+02:00
New Revision: 36bd5bd888f193b70abf43a09bb4fc04cd2a2ff1

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

LOG: [dataflow] use true/false literals in formulas, rather than variables

And simplify formulas containing true/false
It's unclear to me how useful this is, it does make formulas more
conveniently self-contained now (we can usefully print them without
carrying around the "true/false" labels)

(while here, simplify !!X to X, too)

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/Arena.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/include/clang/Analysis/FlowSensitive/Formula.h
clang/lib/Analysis/FlowSensitive/Arena.cpp
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/lib/Analysis/FlowSensitive/Formula.cpp
clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/Arena.h 
b/clang/include/clang/Analysis/FlowSensitive/Arena.h
index 4e07053aae1af53..4be308c43fb7675 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Arena.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Arena.h
@@ -20,7 +20,9 @@ namespace clang::dataflow {
 /// For example, `Value`, `StorageLocation`, `Atom`, and `Formula`.
 class Arena {
 public:
-  Arena() : True(makeAtom()), False(makeAtom()) {}
+  Arena()
+  : True(Formula::create(Alloc, Formula::Literal, {}, 1)),
+False(Formula::create(Alloc, Formula::Literal, {}, 0)) {}
   Arena(const Arena &) = delete;
   Arena &operator=(const Arena &) = delete;
 
@@ -106,9 +108,7 @@ class Arena {
   const Formula &makeAtomRef(Atom A);
 
   /// Returns a formula for a literal true/false.
-  const Formula &makeLiteral(bool Value) {
-return makeAtomRef(Value ? True : False);
-  }
+  const Formula &makeLiteral(bool Value) { return Value ? True : False; }
 
   // Parses a formula from its textual representation.
   // This may refer to atoms that were not produced by makeAtom() yet!
@@ -144,7 +144,7 @@ class Arena {
   llvm::DenseMap FormulaValues;
   unsigned NextAtom = 0;
 
-  Atom True, False;
+  const Formula &True, &False;
 };
 
 } // namespace clang::dataflow

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c128ee4ea85c928..57e9d2fc87c2f41 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -466,9 +466,8 @@ class Environment {
 
   /// Returns a symbolic boolean value that models a boolean literal equal to
   /// `Value`
-  AtomicBoolValue &getBoolLiteralValue(bool Value) const {
-return cast(
-arena().makeBoolValue(arena().makeLiteral(Value)));
+  BoolValue &getBoolLiteralValue(bool Value) const {
+return arena().makeBoolValue(arena().makeLiteral(Value));
   }
 
   /// Returns an atomic boolean value.

diff  --git a/clang/include/clang/Analysis/FlowSensitive/Formula.h 
b/clang/include/clang/Analysis/FlowSensitive/Formula.h
index 5126fda8440..7cd9f29961ba9ca 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Formula.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Formula.h
@@ -53,7 +53,8 @@ class alignas(const Formula *) Formula {
 /// A reference to an atomic boolean variable.
 /// We name these e.g. "V3", where 3 == atom identity == Value.
 AtomRef,
-// FIXME: add const true/false rather than modeling them as variables
+/// Constant true or false.
+Literal,
 
 Not, /// True if its only operand is false
 
@@ -70,6 +71,11 @@ class alignas(const Formula *) Formula {
 return static_cast(Value);
   }
 
+  bool literal() const {
+assert(kind() == Literal);
+return static_cast(Value);
+  }
+
   ArrayRef operands() const {
 return ArrayRef(reinterpret_cast(this + 1),
 numOperands(kind()));
@@ -82,9 +88,9 @@ class alignas(const Formula *) Formula {
   void print(llvm::raw_ostream &OS, const AtomNames * = nullptr) const;
 
   // Allocate Formulas using Arena rather than calling this function directly.
-  static Formula &create(llvm::BumpPtrAllocator &Alloc, Kind K,
- ArrayRef Operands,
- unsigned Value = 0);
+  static const Formula &create(llvm::BumpPtrAllocator &Alloc, Kind K,
+   ArrayRef Op

[PATCH] D153485: [dataflow] use true/false literals in formulas, rather than variables

2023-09-22 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG36bd5bd888f1: [dataflow] use true/false literals in 
formulas, rather than variables (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D153485?vs=537304&id=557245#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153485

Files:
  clang/include/clang/Analysis/FlowSensitive/Arena.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Formula.h
  clang/lib/Analysis/FlowSensitive/Arena.cpp
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/Formula.cpp
  clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
  clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
  clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3202,14 +3202,14 @@
 ASSERT_THAT(FooDecl, NotNull());
 
 const auto *FooVal =
-dyn_cast_or_null(Env.getValue(*FooDecl));
+dyn_cast_or_null(Env.getValue(*FooDecl));
 ASSERT_THAT(FooVal, NotNull());
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
 ASSERT_THAT(BarDecl, NotNull());
 
 const auto *BarVal =
-dyn_cast_or_null(Env.getValue(*BarDecl));
+dyn_cast_or_null(Env.getValue(*BarDecl));
 ASSERT_THAT(BarVal, NotNull());
 
 EXPECT_EQ(FooVal, &Env.getBoolLiteralValue(true));
@@ -3387,7 +3387,7 @@
 ASSERT_THAT(FooDecl, NotNull());
 
 const auto *FooVal =
-dyn_cast_or_null(Env.getValue(*FooDecl));
+dyn_cast_or_null(Env.getValue(*FooDecl));
 ASSERT_THAT(FooVal, NotNull());
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -482,6 +482,11 @@
 return &Formula::create(A, Formula::AtomRef, {}, NextAtom++);
   }
 
+  // Returns a reference to a literal boolean value.
+  const Formula *literal(bool B) {
+return &Formula::create(A, Formula::Literal, {}, B);
+  }
+
   // Creates a boolean conjunction.
   const Formula *conj(const Formula *LHS, const Formula *RHS) {
 return make(Formula::And, {LHS, RHS});
Index: clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DebugSupportTest.cpp
@@ -30,6 +30,12 @@
   EXPECT_THAT(llvm::to_string(*B), StrEq(Expected));
 }
 
+TEST(BoolValueDebugStringTest, Literal) {
+  ConstraintContext Ctx;
+  EXPECT_EQ("true", llvm::to_string(*Ctx.literal(true)));
+  EXPECT_EQ("false", llvm::to_string(*Ctx.literal(false)));
+}
+
 TEST(BoolValueDebugStringTest, Negation) {
   ConstraintContext Ctx;
   auto B = Ctx.neg(Ctx.atom());
@@ -91,16 +97,14 @@
 
 TEST(BoolValueDebugStringTest, ComplexBooleanWithSomeNames) {
   ConstraintContext Ctx;
-  auto True = Ctx.atom();
-  auto False = Ctx.atom();
-  auto V2 = Ctx.atom();
-  auto V3 = Ctx.atom();
+  auto X = Ctx.atom();
+  auto Y = Ctx.atom();
   Formula::AtomNames Names;
-  Names[True->getAtom()] = "true";
-  Names[False->getAtom()] = "false";
-  auto B = Ctx.disj(Ctx.conj(False, V2), Ctx.disj(True, V3));
+  Names[X->getAtom()] = "X";
+  Names[Y->getAtom()] = "Y";
+  auto B = Ctx.disj(Ctx.conj(Y, Ctx.atom()), Ctx.disj(X, Ctx.atom()));
 
-  auto Expected = R"(((false & V2) | (true | V3)))";
+  auto Expected = R"(((Y & V2) | (X | V3)))";
   std::string Actual;
   llvm::raw_string_ostream OS(Actual);
   B->print(OS, &Names);
Index: clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/ArenaTest.cpp
@@ -34,12 +34,6 @@
   EXPECT_NE(&X, &Y);
 }
 
-TEST_F(ArenaTest, GetOrCreateConjunctionReturnsSameExprGivenSameArgs) {
-  auto &X = A.makeAtomRef(A.makeAtom());
-  auto &XAndX = A.makeAnd(X, X);
-  EXPECT_EQ(&XAndX, &X);
-}
-
 TEST_F(ArenaTest, GetOrCreateConjunctionReturnsSameExprOnSubsequentCalls) {
   auto &X = A.makeAtomRef(A.makeAtom());
   auto &Y = A.makeAtomRef(A.makeAtom());
@@ -55,12 +49,6 @@
   EXPECT_NE(&XAndY1, &XAndZ);
 }
 
-TEST_F(ArenaTest, GetOrCreateDisjunctionRetur

[clang] [clang-format] Disable OuterScope lambda indentation behaviour for constructor initializers (PR #66755)

2023-09-22 Thread Jon Phillips via cfe-commits

https://github.com/jp4a50 updated 
https://github.com/llvm/llvm-project/pull/66755

>From e07d263a37ef37a21bb5cf424b14be83088eed3d Mon Sep 17 00:00:00 2001
From: Jon Phillips 
Date: Tue, 19 Sep 2023 10:29:57 +0100
Subject: [PATCH 1/2] [clang-format] Disable OuterScope lambda indentation
 behaviour for constructor initializers

By default, OuterScope aligns lambdas to the beginning of the current
line. This makes sense for most types of statements within code blocks
but leads to unappealing and misleading indentation for lambdas within
constructor initializers.
---
 clang/lib/Format/ContinuationIndenter.cpp |  3 ++-
 clang/unittests/Format/FormatTest.cpp | 30 +--
 2 files changed, 25 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index deb3e554fdc124b..0fa70eace90f416 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1955,7 +1955,8 @@ void 
ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
 
 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
   if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
-  State.NextToken->is(TT_LambdaLBrace)) {
+  State.NextToken->is(TT_LambdaLBrace) && State.Line &&
+  !State.Line->MightBeFunctionDecl) {
 State.Stack.back().NestedBlockIndent = State.FirstIndent;
   }
   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0d0fbdb84e3271b..cb6b22b32e63350 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22537,10 +22537,12 @@ TEST_F(FormatTest, FormatsLambdas) {
"  }\n"
"}",
Style);
-  verifyFormat("std::sort(v.begin(), v.end(),\n"
-   "  [](const auto &foo, const auto &bar) {\n"
-   "  return foo.baz < bar.baz;\n"
-   "});",
+  verifyFormat("void test() {\n"
+   "  std::sort(v.begin(), v.end(),\n"
+   "[](const auto &foo, const auto &bar) {\n"
+   "return foo.baz < bar.baz;\n"
+   "  });\n"
+   "};",
Style);
   verifyFormat("void test() {\n"
"  (\n"
@@ -22589,9 +22591,23 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
"AnotherLongClassName baz)\n"
": baz{baz}, func{[&] {\n"
-   "  auto qux = bar;\n"
-   "  return aFunkyFunctionCall(qux);\n"
-   "}} {}",
+   "auto qux = bar;\n"
+   "return aFunkyFunctionCall(qux);\n"
+   "  }} {}",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  class Foo {\n"
+   "  public:\n"
+   "Foo()\n"
+   ": qux{[](int quux) {\n"
+   "auto tmp = quux;\n"
+   "return tmp;\n"
+   "  }} {}\n"
+   "\n"
+   "  private:\n"
+   "std::function qux;\n"
+   "  };\n"
+   "}\n",
Style);
   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
   // FIXME: The following test should pass, but fails at the time of writing.

>From 7d7d8e51448f9bcb329c12d738f58e016c0f81ee Mon Sep 17 00:00:00 2001
From: Jon Phillips 
Date: Fri, 22 Sep 2023 16:18:45 +0100
Subject: [PATCH 2/2] [clang-format] Add more tests for constructor initializer
 formatting when using OuterScope lambda body indentation.

---
 clang/lib/Format/ContinuationIndenter.cpp |  2 +-
 clang/unittests/Format/FormatTest.cpp | 25 ++-
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 0fa70eace90f416..70abef1169751ce 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1955,7 +1955,7 @@ void 
ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
 
 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
   if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
-  State.NextToken->is(TT_LambdaLBrace) && State.Line &&
+  State.NextToken->is(TT_LambdaLBrace) &&
   !State.Line->MightBeFunctionDecl) {
 State.Stack.back().NestedBlockIndent = State.FirstIndent;
   }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index cb6b22b32e63350..6c67c4253254da1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22568,6 +22568,12 @@ TEST_F(FormatTest, FormatsLambdas) {
"

[clang] [clang-format] Disable OuterScope lambda indentation behaviour for constructor initializers (PR #66755)

2023-09-22 Thread Jon Phillips via cfe-commits


@@ -22537,10 +22537,12 @@ TEST_F(FormatTest, FormatsLambdas) {
"  }\n"
"}",
Style);
-  verifyFormat("std::sort(v.begin(), v.end(),\n"
-   "  [](const auto &foo, const auto &bar) {\n"
-   "  return foo.baz < bar.baz;\n"
-   "});",

jp4a50 wrote:

I've added a test which puts the `std::sort(...)` in a macro definition. It 
works as expected.

I haven't added the original test back since I still think it's misleading but 
if you still think I should keep it I will add it back (and adjust it to pass 
as-is). Just let me know.

https://github.com/llvm/llvm-project/pull/66755
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Move alpha checker EnumCastOutOfRange to optin (PR #67157)

2023-09-22 Thread via cfe-commits

https://github.com/DonatNagyE created 
https://github.com/llvm/llvm-project/pull/67157

The checker EnumCastOutOfRange verifies the (helpful, but not 
standard-mandated) design rule that integer to enum casts should not produce 
values that don't have a corresponding enumerator. As it was improved and 
cleaned up by recent changes, this commit renames it from 
`alpha.cplusplus.EnumCastOutOfRange` to `optin.core.EnumCastOutOfRange` to 
reflect that it's no longer alpha quality.

As this checker handles a basic language feature (which is also present in 
plain C), I moved it to a "core" subpackage within "optin".

In addition to the renaming, this commit cleans up the documentation in 
`checkers.rst` and adds the new example code to a test file to ensure that it's 
indeed producing the behavior claimend in the documentation.

>From 9fd8def3d6ed3ca533efb63005d4748c8bd62687 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Fri, 22 Sep 2023 17:22:53 +0200
Subject: [PATCH] [analyzer] Move alpha checker EnumCastOutOfRange to optin

The checker EnumCastOutOfRange verifies the (helpful, but not
standard-mandated) design rule that integer to enum casts should not
produce values that don't have a corresponding enumerator. As it was
improved and cleaned up by recent changes, this commit renames it from
`alpha.cplusplus.EnumCastOutOfRange` to `optin.core.EnumCastOutOfRange`
to reflect that it's no longer alpha quality.

As this checker handles a basic language feature (which is also present
in plain C), I moved it to a "core" subpackage within "optin".

In addition to the renaming, this commit cleans up the documentation
in `checkers.rst` and adds the new example code to a test file to ensure
that it's indeed producing the behavior claimend in the documentation.
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 clang/docs/analyzer/checkers.rst  | 39 +++
 .../clang/StaticAnalyzer/Checkers/Checkers.td | 17 ++--
 clang/test/Analysis/enum-cast-out-of-range.c  |  2 +-
 .../test/Analysis/enum-cast-out-of-range.cpp  | 13 ++-
 clang/www/analyzer/alpha_checks.html  | 19 -
 6 files changed, 51 insertions(+), 42 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 477a40630f11097..522272a81c088f1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -491,6 +491,9 @@ Static Analyzer
   Read the PR for the details.
   (`#66086 `_)
 
+- Move checker ``alpha.cplusplus.EnumCastOutOfRange`` out of the ``alpha``
+  package to ``optin.core.EnumCastOutOfRange``.
+
 .. _release-notes-sanitizers:
 
 Sanitizers
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index dbd6d7787823530..552f7676a328371 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -535,6 +535,28 @@ optin
 
 Checkers for portability, performance or coding style specific rules.
 
+.. _optin-core-EnumCastOutOfRange:
+
+optin.core.EnumCastOutOfRange (C, C++)
+""
+Check for integer to enumeration casts that would produce a value with no
+corresponding enumerator. This is not necessarily undefined behavior, but can
+lead to nasty surprises, so projects may decide to use a coding standard that
+disallows these "unusual" conversions.
+
+Note that no warnings are produced when the enum type (e.g. `std::byte`) has no
+enumerators at all.
+
+.. code-block:: cpp
+
+ enum WidgetKind { A=1, B, C, X=99 };
+
+ void foo() {
+   WidgetKind c = static_cast(3);  // OK
+   WidgetKind x = static_cast(99); // OK
+   WidgetKind d = static_cast(4);  // warn
+ }
+
 .. _optin-cplusplus-UninitializedObject:
 
 optin.cplusplus.UninitializedObject (C++)
@@ -1853,23 +1875,6 @@ Reports destructions of polymorphic objects with a 
non-virtual destructor in the
  //   destructor
  }
 
-.. _alpha-cplusplus-EnumCastOutOfRange:
-
-alpha.cplusplus.EnumCastOutOfRange (C++)
-
-Check for integer to enumeration casts that could result in undefined values.
-
-.. code-block:: cpp
-
- enum TestEnum {
-   A = 0
- };
-
- void foo() {
-   TestEnum t = static_cast(-1);
-   // warn: the value provided to the cast expression is not in
-   //   the valid range of values for the enum
-
 .. _alpha-cplusplus-InvalidatedIterator:
 
 alpha.cplusplus.InvalidatedIterator (C++)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..1c859c39cf44d91 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -36,6 +36,7 @@ def CoreAlpha : Package<"core">, ParentPackage;
 // Note: OptIn is *not* intended for checkers that are too noisy to be on by
 // default. Such checkers belong in the alpha package.
 def OptIn

[clang] [analyzer] Move alpha checker EnumCastOutOfRange to optin (PR #67157)

2023-09-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

The checker EnumCastOutOfRange verifies the (helpful, but not 
standard-mandated) design rule that integer to enum casts should not produce 
values that don't have a corresponding enumerator. As it was improved and 
cleaned up by recent changes, this commit renames it from 
`alpha.cplusplus.EnumCastOutOfRange` to `optin.core.EnumCastOutOfRange` to 
reflect that it's no longer alpha quality.

As this checker handles a basic language feature (which is also present in 
plain C), I moved it to a "core" subpackage within "optin".

In addition to the renaming, this commit cleans up the documentation in 
`checkers.rst` and adds the new example code to a test file to ensure that it's 
indeed producing the behavior claimend in the documentation.

---
Full diff: https://github.com/llvm/llvm-project/pull/67157.diff


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/docs/analyzer/checkers.rst (+22-17) 
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+13-4) 
- (modified) clang/test/Analysis/enum-cast-out-of-range.c (+1-1) 
- (modified) clang/test/Analysis/enum-cast-out-of-range.cpp (+12-1) 
- (modified) clang/www/analyzer/alpha_checks.html (-19) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 477a40630f11097..522272a81c088f1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -491,6 +491,9 @@ Static Analyzer
   Read the PR for the details.
   (`#66086 `_)
 
+- Move checker ``alpha.cplusplus.EnumCastOutOfRange`` out of the ``alpha``
+  package to ``optin.core.EnumCastOutOfRange``.
+
 .. _release-notes-sanitizers:
 
 Sanitizers
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index dbd6d7787823530..552f7676a328371 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -535,6 +535,28 @@ optin
 
 Checkers for portability, performance or coding style specific rules.
 
+.. _optin-core-EnumCastOutOfRange:
+
+optin.core.EnumCastOutOfRange (C, C++)
+""
+Check for integer to enumeration casts that would produce a value with no
+corresponding enumerator. This is not necessarily undefined behavior, but can
+lead to nasty surprises, so projects may decide to use a coding standard that
+disallows these "unusual" conversions.
+
+Note that no warnings are produced when the enum type (e.g. `std::byte`) has no
+enumerators at all.
+
+.. code-block:: cpp
+
+ enum WidgetKind { A=1, B, C, X=99 };
+
+ void foo() {
+   WidgetKind c = static_cast(3);  // OK
+   WidgetKind x = static_cast(99); // OK
+   WidgetKind d = static_cast(4);  // warn
+ }
+
 .. _optin-cplusplus-UninitializedObject:
 
 optin.cplusplus.UninitializedObject (C++)
@@ -1853,23 +1875,6 @@ Reports destructions of polymorphic objects with a 
non-virtual destructor in the
  //   destructor
  }
 
-.. _alpha-cplusplus-EnumCastOutOfRange:
-
-alpha.cplusplus.EnumCastOutOfRange (C++)
-
-Check for integer to enumeration casts that could result in undefined values.
-
-.. code-block:: cpp
-
- enum TestEnum {
-   A = 0
- };
-
- void foo() {
-   TestEnum t = static_cast(-1);
-   // warn: the value provided to the cast expression is not in
-   //   the valid range of values for the enum
-
 .. _alpha-cplusplus-InvalidatedIterator:
 
 alpha.cplusplus.InvalidatedIterator (C++)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..1c859c39cf44d91 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -36,6 +36,7 @@ def CoreAlpha : Package<"core">, ParentPackage;
 // Note: OptIn is *not* intended for checkers that are too noisy to be on by
 // default. Such checkers belong in the alpha package.
 def OptIn : Package<"optin">;
+def CoreOptIn : Package<"core">, ParentPackage;
 
 // In the Portability package reside checkers for finding code that relies on
 // implementation-defined behavior. Such checks are wanted for cross-platform
@@ -433,6 +434,18 @@ def UndefinedNewArraySizeChecker : Checker<"NewArraySize">,
 
 } // end "core.uninitialized"
 
+//===--===//
+// Optin checkers for core language features
+//===--===//
+
+let ParentPackage = CoreOptIn in {
+
+def EnumCastOutOfRangeChecker : Checker<"EnumCastOutOfRange">,
+  HelpText<"Check integer to enumeration casts for out of range values">,
+  Documentation;
+
+} // end "optin.core"
+
 
//===--===//
 // Unix API checkers.
 
//===---

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-22 Thread Nick Desaulniers via cfe-commits

nickdesaulniers wrote:

ping @hazohelet . This should be good to land and should help clear some red in 
our CI for Linux kernel builds.

https://github.com/llvm/llvm-project/pull/65969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-22 Thread Shoaib Meenai via cfe-commits


@@ -316,6 +318,52 @@ TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) {
   }
 }
 
+MATCHER_P(jobHasArgs, Substr, "") {
+  const driver::Command &C = arg;
+  std::string Args = "";
+  llvm::ListSeparator Sep(" ");
+  for (const char *Arg : C.getArguments()) {
+Args += Sep;
+Args += Arg;
+  }
+  if (is_style_windows(llvm::sys::path::Style::native))
+std::replace(Args.begin(), Args.end(), '\\', '/');
+  if (llvm::StringRef(Args).contains(Substr))
+return true;
+  *result_listener << "whose args are '" << Args << "'";

smeenai wrote:

Not familiar with the unit testing set up ... do you need the "whose args are" 
bit?

https://github.com/llvm/llvm-project/pull/66947
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-22 Thread Shoaib Meenai via cfe-commits

smeenai wrote:

LGTM, thanks!

https://github.com/llvm/llvm-project/pull/66947
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >