[clang] [APINotes] Upstream Sema logic to apply API Notes to decls (PR #73017)

2024-01-12 Thread Saleem Abdulrasool via cfe-commits


@@ -2622,6 +2641,31 @@ def SwiftPrivate : InheritableAttr {
   let SimpleHandler = 1;
 }
 
+def SwiftVersioned : Attr {
+  // This attribute has no spellings as it is only ever created implicitly
+  // from API notes.
+  let Spellings = [];
+  let Args = [VersionArgument<"Version">, AttrArgument<"AttrToAdd">,

compnerd wrote:

I imagine that we cannot change the attribute name?  I think that `Addition` or 
`AdditionalAttribute` would've been more fitting.

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


[flang] [llvm] [compiler-rt] [lld] [libcxx] [clang] [mlir] [lldb] [clang-tools-extra] [DWARFLinker][NFC] Decrease DWARFLinker dependence on DwarfStreamer. (PR #77932)

2024-01-12 Thread Alexey Lapshin via cfe-commits

https://github.com/avl-llvm updated 
https://github.com/llvm/llvm-project/pull/77932

>From 30a603f6d37afecdb2cb150bd98acd27c8d8baf5 Mon Sep 17 00:00:00 2001
From: Alexey Lapshin 
Date: Fri, 12 Jan 2024 13:07:33 +0300
Subject: [PATCH] [DWARFLinker][NFC] Decrease DWARFLinker dependence on
 DwarfStreamer.

This patch is extracted from #74725.

The DwarfStreamer interface looks overcomplicated and has unnecessary 
dependencies:

1. it contains emitSwiftAST, emitSwiftReflectionSection methods which are not 
used by
DWARFLinker.

2. its interface uses DWARFLinker classes(CompileUnit) which makes it dependend
on DWARFLinker.

3. it has "AsmPrinter ()" method which provides very low level 
interface.

This patch avoids creation of DwarfStreamer by DWARFLinker and simplifies 
interface:

1. dwarf_linker::classic.

   Now client of DWARFLinker creates DwarfStreamer and pass it to the 
DWARFLinker
   through DwarfEmitter interface. It simplifies dependence. Later it would be 
good
   to remove class DwarfStreamer from dwarf_linker::classic completely.

2. dwarf_linker::parallel.

   Now client of DWARFLinker sets handler of output debug sections to the 
DWARFLinker.
   It simplifies dependence to following small interface:

   using SectionHandlerTy =
std::function Section)>;

   virtual void setOutputDWARFHandler(const Triple ,
 SectionHandlerTy SectionHandler) = 0;
---
 .../llvm/DWARFLinker/Classic/DWARFLinker.h|  24 +---
 .../llvm/DWARFLinker/Classic/DWARFStreamer.h  |  18 ++-
 .../llvm/DWARFLinker/DWARFLinkerBase.h|  47 +++
 .../llvm/DWARFLinker/Parallel/DWARFLinker.h   |  57 
 llvm/lib/DWARFLinker/CMakeLists.txt   |   1 +
 llvm/lib/DWARFLinker/Classic/DWARFLinker.cpp  |  33 ++---
 .../lib/DWARFLinker/Classic/DWARFStreamer.cpp |  92 ++---
 llvm/lib/DWARFLinker/DWARFLinkerBase.cpp  |  64 +
 .../DWARFLinker/Parallel/DWARFEmitterImpl.cpp |  66 --
 .../DWARFLinker/Parallel/DWARFEmitterImpl.h   |  23 +---
 .../Parallel/DWARFLinkerCompileUnit.cpp   |  14 +-
 .../Parallel/DWARFLinkerCompileUnit.h |   7 +-
 .../Parallel/DWARFLinkerGlobalData.h  |  29 +++-
 .../DWARFLinker/Parallel/DWARFLinkerImpl.cpp  |  92 +
 .../DWARFLinker/Parallel/DWARFLinkerImpl.h|  23 ++--
 .../Parallel/DWARFLinkerTypeUnit.cpp  |  12 +-
 .../Parallel/DWARFLinkerTypeUnit.h|   2 +-
 .../DWARFLinker/Parallel/OutputSections.cpp   |  53 
 .../lib/DWARFLinker/Parallel/OutputSections.h | 124 ++
 llvm/tools/dsymutil/DwarfLinkerForBinary.cpp  |  36 +++--
 llvm/tools/dsymutil/DwarfLinkerForBinary.h|   4 +-
 llvm/tools/llvm-dwarfutil/DebugInfoLinker.cpp |  25 +++-
 22 files changed, 421 insertions(+), 425 deletions(-)
 create mode 100644 llvm/lib/DWARFLinker/DWARFLinkerBase.cpp

diff --git a/llvm/include/llvm/DWARFLinker/Classic/DWARFLinker.h 
b/llvm/include/llvm/DWARFLinker/Classic/DWARFLinker.h
index d3aaa3baadc47d..bacf07beed95eb 100644
--- a/llvm/include/llvm/DWARFLinker/Classic/DWARFLinker.h
+++ b/llvm/include/llvm/DWARFLinker/Classic/DWARFLinker.h
@@ -59,7 +59,8 @@ class DwarfEmitter {
   virtual ~DwarfEmitter() = default;
 
   /// Emit section named SecName with data SecData.
-  virtual void emitSectionContents(StringRef SecData, StringRef SecName) = 0;
+  virtual void emitSectionContents(StringRef SecData,
+   DebugSectionKind SecKind) = 0;
 
   /// Emit the abbreviation table \p Abbrevs to the .debug_abbrev section.
   virtual void
@@ -205,17 +206,6 @@ class DwarfEmitter {
 
   /// Dump the file to the disk.
   virtual void finish() = 0;
-
-  /// Emit the swift_ast section stored in \p Buffer.
-  virtual void emitSwiftAST(StringRef Buffer) = 0;
-
-  /// Emit the swift reflection section stored in \p Buffer.
-  virtual void emitSwiftReflectionSection(
-  llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind,
-  StringRef Buffer, uint32_t Alignment, uint32_t Size) = 0;
-
-  /// Returns underlying AsmPrinter.
-  virtual AsmPrinter () const = 0;
 };
 
 class DwarfStreamer;
@@ -249,10 +239,10 @@ class DWARFLinker : public DWARFLinkerBase {
  StringsTranslator);
   }
 
-  Error createEmitter(const Triple , OutputFileType FileType,
-  raw_pwrite_stream );
-
-  DwarfEmitter *getEmitter();
+  /// Set output DWARF emitter.
+  void setOutputDWARFEmitter(DwarfEmitter *Emitter) {
+TheDwarfEmitter = Emitter;
+  }
 
   /// Add object file to be linked. Pre-load compile unit die. Call
   /// \p OnCUDieLoaded for each compile unit die. If specified \p File
@@ -779,7 +769,7 @@ class DWARFLinker : public DWARFLinkerBase {
   BumpPtrAllocator DIEAlloc;
   /// @}
 
-  std::unique_ptr TheDwarfEmitter;
+  DwarfEmitter *TheDwarfEmitter = nullptr;
   std::vector ObjectContexts;
 
   /// The CIEs that have been emitted in the output section. The actual CIE
diff --git 

[clang] [RISCV] Support __riscv_v_fixed_vlen for vbool types. (PR #76551)

2024-01-12 Thread Craig Topper via cfe-commits

topperc wrote:

Ping

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> This brings me to conclusion that hand-written style of codegen tests 
> presented above is a better fit for purposes of C++ defect report codegen 
> tests.

I share that conclusion. I think the hand-written IR is easier for people to 
reason because it strips out unrelated details that make the test somewhat more 
brittle than it needs to be for DR testing. I agree that we should use the 
script whenever possible, but DR testing is a bit different from typical 
codegen testing IMO. So I'm fine with the hand-crafted IR unless I'm missing 
something.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,31 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 
+improving readability and promoting the use of standard library functions.
+Note: this transformation may impact performance in performance-critical code 
due to potential 
+additional stores compared to the original if statement.
+
+Examples:
+
+Before:
+
+.. code-block:: c++
+
+  void foo() {
+  int a, b;
+  if (a < b)
+a = b;
+  }
+

11happy wrote:

sorry I am not able to get where is the bracket missing

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


[clang] [llvm] [AArch64][SME2] Refine fcvtu/fcvts/scvtf/ucvtf (PR #77947)

2024-01-12 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-ir
@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-backend-aarch64

Author: Matthew Devereau (MDevereau)


Changes

Rename intrinsics for fcvtu to fcvtzu and fcvts to fcvtzs.

Use llvm_anyvector_ty for both multi vector returns and operands, therefore the 
return and operands can be specified in the intrinsic call, e.g.

@llvm.aarch64.sve.scvtf.x4.nxv4f32.nxv4i32

---

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


8 Files Affected:

- (modified) clang/include/clang/Basic/TargetBuiltins.h (+1) 
- (modified) clang/include/clang/Basic/arm_sve.td (+9-9) 
- (modified) clang/include/clang/Basic/arm_sve_sme_incl.td (+1) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+1-1) 
- (modified) clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_cvt.c 
(+16-16) 
- (modified) llvm/include/llvm/IR/IntrinsicsAArch64.td (+12-24) 
- (modified) llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp (+4-4) 
- (modified) llvm/test/CodeGen/AArch64/sme2-intrinsics-cvt.ll (+16-16) 


``diff
diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index c9f9cbec7493bf..d9eba18dab43f3 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -310,6 +310,7 @@ namespace clang {
 bool isReadZA() const { return Flags & IsReadZA; }
 bool isWriteZA() const { return Flags & IsWriteZA; }
 bool isReductionQV() const { return Flags & IsReductionQV; }
+bool isOverloadMultiVecCvt() const { return Flags & IsOverloadMultiVecCvt; 
}
 uint64_t getBits() const { return Flags; }
 bool isFlagSet(uint64_t Flag) const { return Flags & Flag; }
   };
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 6de940b4da6033..73e430a344d755 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -2238,15 +2238,15 @@ let TargetGuard = "sme2" in {
   def SVCVT_F16_X2  : SInst<"svcvt_f16[_f32_x2]", "e2", "f", MergeNone, 
"aarch64_sve_fcvt_x2", [IsStreaming],[]>;
   def SVCVT_BF16_X2 : SInst<"svcvt_bf16[_f32_x2]", "$2", "f", MergeNone, 
"aarch64_sve_bfcvt_x2", [IsOverloadNone, IsStreaming],[]>;
 
-  def SVCVT_F32_U32_X2 : SInst<"svcvt_{d}[_u32_x2]", "2.d2.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x2", [IsStreaming], []>;
-  def SVCVT_U32_F32_X2 : SInst<"svcvt_u32[_{d}_x2]", "2.u2.d", "f", MergeNone, 
"aarch64_sve_fcvtu_x2", [IsStreaming], []>;
-  def SVCVT_F32_S32_X2 : SInst<"svcvt_{d}[_s32_x2]", "2.d2.x", "f", MergeNone, 
"aarch64_sve_scvtf_x2", [IsStreaming], []>;
-  def SVCVT_S32_F32_X2 : SInst<"svcvt_s32[_{d}_x2]", "2.x2.d", "f", MergeNone, 
"aarch64_sve_fcvts_x2", [IsStreaming], []>;
-
-  def SVCVT_F32_U32_X4 : SInst<"svcvt_{d}[_u32_x4]", "4.d4.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x4", [IsStreaming], []>;
-  def SVCVT_U32_F32_X4 : SInst<"svcvt_u32[_{d}_x4]", "4.u4.d", "f", MergeNone, 
"aarch64_sve_fcvtu_x4", [IsStreaming], []>;
-  def SVCVT_F32_S32_X4 : SInst<"svcvt_{d}[_s32_x4]", "4.d4.x", "f", MergeNone, 
"aarch64_sve_scvtf_x4", [IsStreaming], []>;
-  def SVCVT_S32_F32_X4 : SInst<"svcvt_s32[_{d}_x4]", "4.x4.d", "f", MergeNone, 
"aarch64_sve_fcvts_x4", [IsStreaming], []>;
+  def SVCVT_F32_U32_X2 : SInst<"svcvt_{d}[_u32_x2]", "2.d2.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_U32_F32_X2 : SInst<"svcvt_{d}[_f32_x2]", "2.d2.M", "Ui", 
MergeNone, "aarch64_sve_fcvtzu_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_F32_S32_X2 : SInst<"svcvt_{d}[_s32_x2]", "2.d2.x", "f", MergeNone, 
"aarch64_sve_scvtf_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_S32_F32_X2 : SInst<"svcvt_{d}[_f32_x2]", "2.d2.M", "i", MergeNone, 
"aarch64_sve_fcvtzs_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+
+  def SVCVT_F32_U32_X4 : SInst<"svcvt_{d}[_u32_x4]", "4.d4.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_U32_F32_X4 : SInst<"svcvt_{d}[_f32_x4]", "4.d4.M", "Ui", 
MergeNone, "aarch64_sve_fcvtzu_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_F32_S32_X4 : SInst<"svcvt_{d}[_s32_x4]", "4.d4.x", "f", MergeNone, 
"aarch64_sve_scvtf_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_S32_F32_X4 : SInst<"svcvt_{d}[_f32_x4]", "4.d4.M", "i", MergeNone, 
"aarch64_sve_fcvtzs_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
 }
 
 //
diff --git a/clang/include/clang/Basic/arm_sve_sme_incl.td 
b/clang/include/clang/Basic/arm_sve_sme_incl.td
index ad29864440c96f..9d09d319cc3b8e 100644
--- a/clang/include/clang/Basic/arm_sve_sme_incl.td
+++ b/clang/include/clang/Basic/arm_sve_sme_incl.td
@@ -228,6 +228,7 @@ def IsReadZA  : FlagType<0x200>;
 def IsWriteZA : FlagType<0x400>;
 def IsReductionQV : FlagType<0x800>;
 def IsStreamingOrSVE2p1   : 

[clang] [llvm] [AArch64][SME2] Refine fcvtu/fcvts/scvtf/ucvtf (PR #77947)

2024-01-12 Thread Matthew Devereau via cfe-commits

https://github.com/MDevereau created 
https://github.com/llvm/llvm-project/pull/77947

Rename intrinsics for fcvtu to fcvtzu and fcvts to fcvtzs.

Use llvm_anyvector_ty for both multi vector returns and operands, therefore the 
return and operands can be specified in the intrinsic call, e.g.

@llvm.aarch64.sve.scvtf.x4.nxv4f32.nxv4i32

>From 5b2206518e380e8a5ee020f8ff12137cdda4cfa2 Mon Sep 17 00:00:00 2001
From: Matt Devereau 
Date: Fri, 12 Jan 2024 14:01:10 +
Subject: [PATCH] [AArch64][SME2] Refine fcvtu/fcvts/scvtf/ucvtf

Rename intrinsics for fcvtu to fcvtzu and fcvts to fcvtzs.

Use llvm_anyvector_ty for both multi vector returns and operands,
therefore the return and operands can be specified in the intrinsic
call, e.g.

@llvm.aarch64.sve.scvtf.x4.nxv4f32.nxv4i32
---
 clang/include/clang/Basic/TargetBuiltins.h|  1 +
 clang/include/clang/Basic/arm_sve.td  | 18 +-
 clang/include/clang/Basic/arm_sve_sme_incl.td |  1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  2 +-
 .../aarch64-sme2-intrinsics/acle_sme2_cvt.c   | 32 -
 llvm/include/llvm/IR/IntrinsicsAArch64.td | 36 +++
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp|  8 ++---
 .../CodeGen/AArch64/sme2-intrinsics-cvt.ll| 32 -
 8 files changed, 60 insertions(+), 70 deletions(-)

diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index c9f9cbec7493bf..d9eba18dab43f3 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -310,6 +310,7 @@ namespace clang {
 bool isReadZA() const { return Flags & IsReadZA; }
 bool isWriteZA() const { return Flags & IsWriteZA; }
 bool isReductionQV() const { return Flags & IsReductionQV; }
+bool isOverloadMultiVecCvt() const { return Flags & IsOverloadMultiVecCvt; 
}
 uint64_t getBits() const { return Flags; }
 bool isFlagSet(uint64_t Flag) const { return Flags & Flag; }
   };
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 6de940b4da6033..73e430a344d755 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -2238,15 +2238,15 @@ let TargetGuard = "sme2" in {
   def SVCVT_F16_X2  : SInst<"svcvt_f16[_f32_x2]", "e2", "f", MergeNone, 
"aarch64_sve_fcvt_x2", [IsStreaming],[]>;
   def SVCVT_BF16_X2 : SInst<"svcvt_bf16[_f32_x2]", "$2", "f", MergeNone, 
"aarch64_sve_bfcvt_x2", [IsOverloadNone, IsStreaming],[]>;
 
-  def SVCVT_F32_U32_X2 : SInst<"svcvt_{d}[_u32_x2]", "2.d2.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x2", [IsStreaming], []>;
-  def SVCVT_U32_F32_X2 : SInst<"svcvt_u32[_{d}_x2]", "2.u2.d", "f", MergeNone, 
"aarch64_sve_fcvtu_x2", [IsStreaming], []>;
-  def SVCVT_F32_S32_X2 : SInst<"svcvt_{d}[_s32_x2]", "2.d2.x", "f", MergeNone, 
"aarch64_sve_scvtf_x2", [IsStreaming], []>;
-  def SVCVT_S32_F32_X2 : SInst<"svcvt_s32[_{d}_x2]", "2.x2.d", "f", MergeNone, 
"aarch64_sve_fcvts_x2", [IsStreaming], []>;
-
-  def SVCVT_F32_U32_X4 : SInst<"svcvt_{d}[_u32_x4]", "4.d4.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x4", [IsStreaming], []>;
-  def SVCVT_U32_F32_X4 : SInst<"svcvt_u32[_{d}_x4]", "4.u4.d", "f", MergeNone, 
"aarch64_sve_fcvtu_x4", [IsStreaming], []>;
-  def SVCVT_F32_S32_X4 : SInst<"svcvt_{d}[_s32_x4]", "4.d4.x", "f", MergeNone, 
"aarch64_sve_scvtf_x4", [IsStreaming], []>;
-  def SVCVT_S32_F32_X4 : SInst<"svcvt_s32[_{d}_x4]", "4.x4.d", "f", MergeNone, 
"aarch64_sve_fcvts_x4", [IsStreaming], []>;
+  def SVCVT_F32_U32_X2 : SInst<"svcvt_{d}[_u32_x2]", "2.d2.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_U32_F32_X2 : SInst<"svcvt_{d}[_f32_x2]", "2.d2.M", "Ui", 
MergeNone, "aarch64_sve_fcvtzu_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_F32_S32_X2 : SInst<"svcvt_{d}[_s32_x2]", "2.d2.x", "f", MergeNone, 
"aarch64_sve_scvtf_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_S32_F32_X2 : SInst<"svcvt_{d}[_f32_x2]", "2.d2.M", "i", MergeNone, 
"aarch64_sve_fcvtzs_x2", [IsStreaming, IsOverloadMultiVecCvt], []>;
+
+  def SVCVT_F32_U32_X4 : SInst<"svcvt_{d}[_u32_x4]", "4.d4.u", "f", MergeNone, 
"aarch64_sve_ucvtf_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_U32_F32_X4 : SInst<"svcvt_{d}[_f32_x4]", "4.d4.M", "Ui", 
MergeNone, "aarch64_sve_fcvtzu_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_F32_S32_X4 : SInst<"svcvt_{d}[_s32_x4]", "4.d4.x", "f", MergeNone, 
"aarch64_sve_scvtf_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
+  def SVCVT_S32_F32_X4 : SInst<"svcvt_{d}[_f32_x4]", "4.d4.M", "i", MergeNone, 
"aarch64_sve_fcvtzs_x4", [IsStreaming, IsOverloadMultiVecCvt], []>;
 }
 
 //
diff --git a/clang/include/clang/Basic/arm_sve_sme_incl.td 
b/clang/include/clang/Basic/arm_sve_sme_incl.td
index ad29864440c96f..9d09d319cc3b8e 100644
--- a/clang/include/clang/Basic/arm_sve_sme_incl.td
+++ b/clang/include/clang/Basic/arm_sve_sme_incl.td
@@ -228,6 

[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread Bhuminjay Soni via cfe-commits

https://github.com/11happy updated 
https://github.com/llvm/llvm-project/pull/77816

>From 1883d987b2f83adaef05fdb47ae25c7b06582a64 Mon Sep 17 00:00:00 2001
From: 11happy 
Date: Fri, 12 Jan 2024 00:02:46 +0530
Subject: [PATCH 01/13] Add readability check to suggest replacement of
 conditional statement with std::min/std::max

Signed-off-by: 11happy 
---
 .../clang-tidy/readability/CMakeLists.txt |  1 +
 .../ConditionaltostdminmaxCheck.cpp   | 86 +++
 .../readability/ConditionaltostdminmaxCheck.h | 30 +++
 .../readability/ReadabilityTidyModule.cpp |  3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../readability/ConditionalToStdMinMax.rst| 29 +++
 .../readability/ConditionalToStdMinMax.cpp| 27 ++
 8 files changed, 183 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/ConditionalToStdMinMax.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/ConditionalToStdMinMax.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 408c822b861c5f..4bc373bb69bb84 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -8,6 +8,7 @@ add_clang_library(clangTidyReadabilityModule
   AvoidReturnWithVoidValueCheck.cpp
   AvoidUnconditionalPreprocessorIfCheck.cpp
   BracesAroundStatementsCheck.cpp
+  ConditionaltostdminmaxCheck.cpp
   ConstReturnTypeCheck.cpp
   ContainerContainsCheck.cpp
   ContainerDataPointerCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
new file mode 100644
index 00..fba8c68f737450
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
@@ -0,0 +1,86 @@
+//===--- ConditionaltostdminmaxCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ConditionaltostdminmaxCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void ConditionaltostdminmaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+ifStmt(
+  has(
+binaryOperator(
+  anyOf(hasOperatorName("<"),hasOperatorName(">")),
+  hasLHS(ignoringImpCasts(declRefExpr().bind("lhsVar1"))),
+  hasRHS(ignoringImpCasts(declRefExpr().bind("rhsVar1")))
+  )
+  )
+,
+hasThen(
+  stmt(
+binaryOperator(
+  hasOperatorName("="),
+  hasLHS(ignoringImpCasts(declRefExpr().bind("lhsVar2"))),
+  hasRHS(ignoringImpCasts(declRefExpr().bind("rhsVar2")))
+  )
+)
+  ) 
+).bind("ifStmt"),this);
+
+
+
+}
+
+void ConditionaltostdminmaxCheck::check(const MatchFinder::MatchResult 
) {
+  const DeclRefExpr *lhsVar1 = Result.Nodes.getNodeAs("lhsVar1");
+  const DeclRefExpr *rhsVar1 = Result.Nodes.getNodeAs("rhsVar1");
+  const DeclRefExpr *lhsVar2 = Result.Nodes.getNodeAs("lhsVar2");
+  const DeclRefExpr *rhsVar2 = Result.Nodes.getNodeAs("rhsVar2"); 
 
+  const IfStmt *ifStmt = Result.Nodes.getNodeAs("ifStmt");
+
+  if (!lhsVar1 || !rhsVar1 || !lhsVar2 || !rhsVar2 || !ifStmt)
+return;
+
+  const BinaryOperator *binaryOp = dyn_cast(ifStmt->getCond());
+  if (!binaryOp)
+  return;
+
+  SourceLocation ifLocation = ifStmt->getIfLoc();
+  SourceLocation thenLocation = ifStmt->getEndLoc();
+
+  if(binaryOp->getOpcode() == BO_LT){
+if(lhsVar1->getDecl() == lhsVar2->getDecl() && rhsVar1->getDecl() == 
rhsVar2->getDecl()){
+  diag(ifStmt->getIfLoc(), "use std::max instead of 
<")getNameInfo().getAsString() + ", " +
+  rhsVar1->getNameInfo().getAsString() + 
")");
+}
+else if(lhsVar1->getDecl() == rhsVar2->getDecl() && rhsVar1->getDecl() == 
lhsVar2->getDecl()){
+  diag(ifStmt->getIfLoc(), "use std::min instead of 
<")getNameInfo().getAsString() + ", " +
+  rhsVar1->getNameInfo().getAsString() + 
")");
+}
+  }
+  else if(binaryOp->getOpcode() == BO_GT){
+if(lhsVar1->getDecl() == 

[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

Following the suggestion from @nikic, I prepared two variants of the same test, 
one hard-written, and one using `update_cc_test_checks.py` (with heavy manual 
editing afterwards). Hand-written:
```
// CHECK-LABEL:  define dso_local void @dr1807::f()
// CHECK:  invoke void @dr1807::S::S(){{.+}}
// CHECK-NEXT: {{.+}} unwind label %lpad
// CHECK-LABEL:  lpad:
// CHECK:  br {{.+}}, label {{.+}}, label %arraydestroy.body
// CHECK-LABEL:  arraydestroy.body:
// CHECK:  [[ARRAYDESTROY_ELEMENT:%.*]] = getelementptr {{.+}}, i64 
-1
// CXX98-NEXT: invoke void 
@dr1807::S::~S(){{.*}}[[ARRAYDESTROY_ELEMENT]]
// SINCE-CXX11-NEXT:   call void @dr1807::S::~S(){{.*}}[[ARRAYDESTROY_ELEMENT]]
```
Script:
```
// CHECK-LABEL:  define dso_local void @dr1807::f()(
// CHECK:  invoke void @dr1807::S::S()(ptr noundef nonnull align 1 
dereferenceable(1) [[ARRAYCTOR_CUR:%.*]])
// CHECK-NEXT: to label [[INVOKE_CONT:%.*]] unwind label 
[[LPAD:%.*]]
// CHECK-LABEL:  lpad:
// CHECK:  br i1 [[ARRAYDESTROY_ISEMPTY:%.*]], label 
[[ARRAYDESTROY_DONE2:%.*]], label [[ARRAYDESTROY_BODY:%.*]]
// CHECK-LABEL:  arraydestroy.body:
// CHECK:  [[ARRAYDESTROY_ELEMENT]] = getelementptr inbounds 
%"struct.dr1807::S", ptr [[ARRAYDESTROY_ELEMENTPAST]], i64 -1
// CXX98-NEXT: invoke void @dr1807::S::~S()(ptr noundef nonnull align 1 
dereferenceable(1) [[ARRAYDESTROY_ELEMENT]])
// CXX98-NEXT: to label [[INVOKE_CONT1]] unwind label 
[[TERMINATE_LPAD:%.*]]
// SINCE-CXX11-NEXT:   call void @dr1807::S::~S()(ptr noundef nonnull align 1 
dereferenceable(1) [[ARRAYDESTROY_ELEMENT5:.*]]) #[[ATTR2:.*]]
```
In my opinion, script captures way too much, diluting the point of the test. 
For example, `i64 -1` is a crucial part of the test, but it's much easier to 
miss it in lengthy script output. (Searching for it might be a good exercise 
for the reader.) I'd also like to note that target audience of DR tests is 
likely to be far less experienced in reading LLVM IR than regular users of the 
script, so it's much less obvious for them to know which parts of the output to 
pay attention to. On the other hand wildcards help hide uninteresting parts of 
the codegen output, highlighting what's important.

This brings me to conclusion that hand-written style of codegen tests presented 
above is a better fit for purposes of C++ defect report codegen tests.

CC @AaronBallman 

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


[clang] [clang][ASTImporter] Fix import of variable template redeclarations. (PR #72841)

2024-01-12 Thread Balázs Kéri via cfe-commits


@@ -6245,17 +6245,21 @@ ExpectedDecl 
ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
   D->getTemplatedDecl()))
 continue;
   if (IsStructuralMatch(D, FoundTemplate)) {
-// The Decl in the "From" context has a definition, but in the
-// "To" context we already have a definition.
+// FIXME Check for ODR error if the two definitions have
+// different initializers?
 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
-if (D->isThisDeclarationADefinition() && FoundDef)
-  // FIXME Check for ODR error if the two definitions have
-  // different initializers?
-  return Importer.MapImported(D, FoundDef);
-if (FoundTemplate->getDeclContext()->isRecord() &&
-D->getDeclContext()->isRecord())
-  return Importer.MapImported(D, FoundTemplate);
-
+if (D->getDeclContext()->isRecord()) {
+  assert(FoundTemplate->getDeclContext()->isRecord() &&
+ "Member variable template imported as non-member, "
+ "inconsistent imported AST?");

balazske wrote:

The existing "To" AST can be somehow invalid or declarations can be in wrong 
scope, because previous wrong AST imports and structural equivalence problems, 
or here a wrong declaration may be found. This assertion looks to check for 
such problems (check `FoundTemplate->getDeclContext()->isRecord()` if 
`D->getDeclContext()->isRecord()`).

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


[llvm] [clang] [PowerPC][X86] Make cpu id builtins target independent and lower for PPC (PR #68919)

2024-01-12 Thread via cfe-commits


@@ -16086,6 +16086,41 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
   switch (BuiltinID) {
   default: return nullptr;
 
+  case Builtin::BI__builtin_cpu_is: {
+const Expr *CPUExpr = E->getArg(0)->IgnoreParenCasts();
+StringRef CPUStr = cast(CPUExpr)->getString();
+unsigned NumCPUID = StringSwitch(CPUStr)
+#define PPC_LNX_CPU(Name, NumericID) .Case(Name, NumericID)
+#include "llvm/TargetParser/PPCTargetParser.def"
+.Default(-1U);
+Value *Op0 = llvm::ConstantInt::get(Int32Ty, PPC_FAWORD_CPUID);
+llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_fixed_addr_ld);
+Value *TheCall = Builder.CreateCall(F, {Op0}, "cpu_is");
+return Builder.CreateICmpEQ(TheCall,
+llvm::ConstantInt::get(Int32Ty, NumCPUID));
+  }
+  case Builtin::BI__builtin_cpu_supports: {
+unsigned FeatureWord;
+unsigned BitMask;
+const Expr *CPUExpr = E->getArg(0)->IgnoreParenCasts();
+StringRef CPUStr = cast(CPUExpr)->getString();
+std::tie(FeatureWord, BitMask) =
+StringSwitch>(CPUStr)
+#define PPC_LNX_FEATURE(Name, Description, EnumName, Bitmask, FA_WORD) 
\
+  .Case(Name, {FA_WORD, Bitmask})
+#include "llvm/TargetParser/PPCTargetParser.def"
+.Default({0, 0});

diggerlin wrote:

 we do not want a default here,  without a default it will hit an assert here 
if fell off the end of the string-switch.
in the class of StringSwitch , there is function as 

```
  [[nodiscard]] operator R() {
assert(Result && "Fell off the end of a string-switch");
return std::move(*Result);
  }
```

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/77637

>From 545ee4900e48b186e1c9fff93dc62a459ee19754 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 20:27:53 +0300
Subject: [PATCH 1/7] [clang] Add test for CWG1807

The test checks that objects in arrays are destructed in reverse order during 
stack unwinding.
---
 clang/test/CXX/drs/dr1807.cpp | 31 +++
 clang/www/cxx_dr_status.html  |  2 +-
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CXX/drs/dr1807.cpp

diff --git a/clang/test/CXX/drs/dr1807.cpp b/clang/test/CXX/drs/dr1807.cpp
new file mode 100644
index 00..f599a36c8b2cbd
--- /dev/null
+++ b/clang/test/CXX/drs/dr1807.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,CXX98
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+
+namespace dr1807 { // dr1807: 3.0
+struct S {
+  S() {}
+  ~S() {}
+};
+
+void f() {
+  try {
+S s[3];
+  } catch (...) {}
+}
+}
+
+// CHECK:  invoke void @dr1807::S::S(){{.+}}
+// CHECK-NEXT: {{.+}} unwind label %lpad
+
+// CHECK-LABEL:  lpad:
+// CHECK:  br {{.+}}, label {{.+}}, label %arraydestroy.body
+
+// CHECK-LABEL:  arraydestroy.body:
+// CHECK:  %arraydestroy.element = getelementptr {{.+}}, i64 -1
+// CXX98-NEXT: invoke void @dr1807::S::~S(){{.*}}%arraydestroy.element
+// SINCE-CXX11-NEXT:   call void @dr1807::S::~S(){{.*}}%arraydestroy.element
diff --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index 2bded63d5cd41c..bea9d0f54c471e 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -10649,7 +10649,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/1807.html;>1807
 CD4
 Order of destruction of array elements after an exception
-Unknown
+Clang 3.0
   
   
 https://cplusplus.github.io/CWG/issues/1808.html;>1808

>From 81b5f521c4e8e77f39ef1b01612a7866c6de8440 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 21:57:30 +0300
Subject: [PATCH 2/7] Leave a comment in dr18xx.cpp

---
 clang/test/CXX/drs/dr18xx.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/test/CXX/drs/dr18xx.cpp b/clang/test/CXX/drs/dr18xx.cpp
index 1d76804907a5c1..e092c83ab4ce42 100644
--- a/clang/test/CXX/drs/dr18xx.cpp
+++ b/clang/test/CXX/drs/dr18xx.cpp
@@ -164,6 +164,8 @@ void A::C::f4() {
 }
 } // namespace dr1804
 
+// dr1807 is in separate file
+
 namespace dr1812 { // dr1812: no
// NB: dup 1710
 #if __cplusplus >= 201103L

>From 59ec23c9cdd4d4557c0b471331683d577add31d6 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 22:06:01 +0300
Subject: [PATCH 3/7] Eliminate the need for readers to guess how the file is
 named

---
 clang/test/CXX/drs/dr18xx.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/CXX/drs/dr18xx.cpp b/clang/test/CXX/drs/dr18xx.cpp
index e092c83ab4ce42..530122ccd1aab1 100644
--- a/clang/test/CXX/drs/dr18xx.cpp
+++ b/clang/test/CXX/drs/dr18xx.cpp
@@ -164,7 +164,7 @@ void A::C::f4() {
 }
 } // namespace dr1804
 
-// dr1807 is in separate file
+// dr1807 is in dr1807.cpp
 
 namespace dr1812 { // dr1812: no
// NB: dup 1710

>From 62f1fa6bb3c691dde2e903711634857de486e71e Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 23:33:41 +0300
Subject: [PATCH 4/7] Simplify C++ part of the test

---
 clang/test/CXX/drs/dr1807.cpp | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/clang/test/CXX/drs/dr1807.cpp b/clang/test/CXX/drs/dr1807.cpp
index f599a36c8b2cbd..e654987b485c76 100644
--- 

[clang] [clang][ASTImporter] Improve structural equivalence of overloadable operators. (PR #72242)

2024-01-12 Thread Balázs Kéri via cfe-commits


@@ -2252,6 +2252,176 @@ TEST_F(StructuralEquivalenceStmtTest, 
UnaryOperatorDifferentOps) {
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+TEST_F(StructuralEquivalenceStmtTest,
+   CXXOperatorCallExprVsUnaryBinaryOperator) {
+  auto t = makeNamedDecls(
+  R"(
+  template 
+  class A;
+  template 
+  void foo(
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A y)>,
+A,
+A> y)>,
+A,
+A,
+A,
+A= y>,
+A y>,
+A,
+A,
+A,
+A,
+A,
+A* y>,
+A y>
+  );
+  )",
+  R"(
+  struct Bar {
+Bar& operator=(Bar&);
+Bar& operator->();
+  };
+
+  Bar& operator+(Bar&, Bar&);
+  Bar& operator+(Bar&);
+  Bar& operator-(Bar&, Bar&);
+  Bar& operator-(Bar&);
+  Bar& operator*(Bar&, Bar&);
+  Bar& operator*(Bar&);
+  Bar& operator/(Bar&, Bar&);
+  Bar& operator%(Bar&, Bar&);
+  Bar& operator^(Bar&, Bar&);
+  Bar& operator&(Bar&, Bar&);
+  Bar& operator&(Bar&);
+  Bar& operator|(Bar&, Bar&);
+  Bar& operator~(Bar&);
+  Bar& operator!(Bar&);
+  Bar& operator<(Bar&, Bar&);
+  Bar& operator>(Bar&, Bar&);
+  Bar& operator+=(Bar&, Bar&);
+  Bar& operator-=(Bar&, Bar&);
+  Bar& operator*=(Bar&, Bar&);
+  Bar& operator/=(Bar&, Bar&);
+  Bar& operator%=(Bar&, Bar&);
+  Bar& operator^=(Bar&, Bar&);
+  Bar& operator&=(Bar&, Bar&);
+  Bar& operator|=(Bar&, Bar&);
+  Bar& operator<<(Bar&, Bar&);
+  Bar& operator>>(Bar&, Bar&);
+  Bar& operator<<=(Bar&, Bar&);
+  Bar& operator>>=(Bar&, Bar&);
+  Bar& operator==(Bar&, Bar&);
+  Bar& operator!=(Bar&, Bar&);
+  Bar& operator<=(Bar&, Bar&);
+  Bar& operator>=(Bar&, Bar&);
+  Bar& operator<=>(Bar&, Bar&);
+  Bar& operator&&(Bar&, Bar&);
+  Bar& operator||(Bar&, Bar&);
+  Bar& operator++(Bar&);
+  Bar& operator--(Bar&);
+  Bar& operator,(Bar&, Bar&);
+  Bar& operator->*(Bar&, Bar&);
+
+  template 
+  class A;
+  template 
+  void foo(
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A,
+A y)>,
+A,
+A> y)>,
+A,
+A,
+A,
+A= y>,
+A y>,
+A,
+A,
+A,
+A,
+A,
+A* y>,
+A y>
+  );
+  )",
+  Lang_CXX20);
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceStmtTest,
+   CXXOperatorCallExprVsUnaryBinaryOperatorNe) {
+  auto t = makeNamedDecls(
+  R"(
+  template 
+  class A;
+  template 
+  void foo(
+A
+  );
+  )",
+  R"(
+  struct Bar;
+
+  Bar& operator+(Bar&, Bar&);

balazske wrote:

Code is now updated to `operator-` (the first code should contain an 
`CXXOperatorCallExpr`, the second a `BinaryOperator` in the template arg 2 of 
`A`).

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


[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-01-12 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 8cf6bcf5a30673dd8a234ae3ef4ab4c1e63786b1 
a8f9dc9edd98416a84d524ca6b233a27882f5085 -- 
clang/test/Driver/cxx23-modules-print-library-module-manifest-path.cpp 
clang/include/clang/Driver/Driver.h clang/lib/Driver/Driver.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index a3cae06fc6..0f9022f23f 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6153,8 +6153,8 @@ std::string Driver::GetStdModuleManifestPath(const 
Compilation ,
 
 // Note when there are multiple flavours of libc++ the module json needs to
 // look at the command-line arguments for the proper json.
-   // These flavours do not exist at the moment, but there are plans to
-   // provide a variant that is built with sanitizer instrumentation 
enabled.
+// These flavours do not exist at the moment, but there are plans to
+// provide a variant that is built with sanitizer instrumentation enabled.
 
 // For example
 //  const SanitizerArgs  = TC.getSanitizerArgs(C.getArgs());

``




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


[clang] [clang][ASTImporter] Improve structural equivalence of overloadable operators. (PR #72242)

2024-01-12 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/72242

From 5300f979c96eb2f88c298872f0519e274c155cfe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Tue, 14 Nov 2023 11:53:20 +0100
Subject: [PATCH 1/3] [clang][ASTImporter] Improve structural equivalence of
 overloadable operators.

Operators that are overloadable may be parsed as `CXXOperatorCallExpr`
or as `UnaryOperator` (or `BinaryOperator`). This depends on the context
and can be different if a similar construct is imported into an existing AST.
The two "forms" of the operator call AST nodes should be detected as
equivalent to allow AST import of these cases.

This fix has probably other consequences because if a structure is imported
that has `CXXOperatorCallExpr` into an AST with an existing similar structure
that has `UnaryOperator` (or binary), the additional data in the
`CXXOperatorCallExpr` node is lost at the import (because the existing node
will be used). I am not sure if this can cause problems.
---
 clang/lib/AST/ASTStructuralEquivalence.cpp|  57 ++
 .../AST/StructuralEquivalenceTest.cpp | 170 ++
 2 files changed, 227 insertions(+)

diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp 
b/clang/lib/AST/ASTStructuralEquivalence.cpp
index 6bb4bf14b873d7..b937ff0579ca02 100644
--- a/clang/lib/AST/ASTStructuralEquivalence.cpp
+++ b/clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -98,6 +98,8 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
  QualType T1, QualType T2);
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
  Decl *D1, Decl *D2);
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ const Stmt *S1, const Stmt *S2);
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
  const TemplateArgument ,
  const TemplateArgument );
@@ -437,12 +439,67 @@ class StmtComparer {
 };
 } // namespace
 
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ const UnaryOperator *E1,
+ const CXXOperatorCallExpr *E2) {
+  return UnaryOperator::getOverloadedOperator(E1->getOpcode()) ==
+ E2->getOperator() &&
+ IsStructurallyEquivalent(Context, E1->getSubExpr(), E2->getArg(0));
+}
+
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ const CXXOperatorCallExpr *E1,
+ const UnaryOperator *E2) {
+  return E1->getOperator() ==
+ UnaryOperator::getOverloadedOperator(E2->getOpcode()) &&
+ IsStructurallyEquivalent(Context, E1->getArg(0), E2->getSubExpr());
+}
+
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ const BinaryOperator *E1,
+ const CXXOperatorCallExpr *E2) {
+  return BinaryOperator::getOverloadedOperator(E1->getOpcode()) ==
+ E2->getOperator() &&
+ IsStructurallyEquivalent(Context, E1->getLHS(), E2->getArg(0)) &&
+ IsStructurallyEquivalent(Context, E1->getRHS(), E2->getArg(1));
+}
+
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ const CXXOperatorCallExpr *E1,
+ const BinaryOperator *E2) {
+  return E1->getOperator() ==
+ BinaryOperator::getOverloadedOperator(E2->getOpcode()) &&
+ IsStructurallyEquivalent(Context, E1->getArg(0), E2->getLHS()) &&
+ IsStructurallyEquivalent(Context, E1->getArg(1), E2->getRHS());
+}
+
 /// Determine structural equivalence of two statements.
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
  const Stmt *S1, const Stmt *S2) {
   if (!S1 || !S2)
 return S1 == S2;
 
+  // Check for statements with similar syntax but different AST.
+  // The unary and binary operators (like '+', '&') can be parsed as
+  // CXXOperatorCall too (and UnaryOperator or BinaryOperator).
+  // This depends on arguments with unresolved type and on the name lookup.
+  // The lookup results can be different in a "From" and "To" AST even if the
+  // compared structure is otherwise equivalent. For this reason we must treat
+  // these operators as equivalent even if they are represented by different 
AST
+  // nodes.
+  if (const auto *E2CXXOperatorCall = dyn_cast(S2)) {
+if (const auto *E1Unary = dyn_cast(S1))
+  return IsStructurallyEquivalent(Context, E1Unary, E2CXXOperatorCall);
+if (const auto *E1Binary = dyn_cast(S1))
+  return IsStructurallyEquivalent(Context, E1Binary, E2CXXOperatorCall);
+  }
+  if (const auto *E1CXXOperatorCall = dyn_cast(S1)) {
+if (const auto *E2Unary = 

[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-01-12 Thread Mark de Wever via cfe-commits

https://github.com/mordante updated 
https://github.com/llvm/llvm-project/pull/76451

>From f3f0db64da4d341f8e4a2054f9f25c87f8eda829 Mon Sep 17 00:00:00 2001
From: Mark de Wever 
Date: Wed, 27 Dec 2023 17:34:10 +0100
Subject: [PATCH 1/4] [clang][modules] Print library module manifest path.

This implements a way for the compiler to find the modules.json
associated with the C++23 Standard library modules.

This is based on a discussion in SG15. At the moment no Standard library
installs this manifest. #75741 adds this feature in libc++.
---
 clang/include/clang/Driver/Driver.h   | 10 +
 clang/include/clang/Driver/Options.td |  3 ++
 clang/lib/Driver/Driver.cpp   | 40 +++
 .../usr/lib/x86_64-linux-gnu/libc++.so|  0
 .../usr/lib/x86_64-linux-gnu/modules.json |  0
 ...dules-print-library-module-manifest-path.c | 15 +++
 ...arwin-print-library-module-manifest-path.c |  9 +
 7 files changed, 77 insertions(+)
 create mode 100644 
clang/test/Driver/Inputs/cxx23_modules/usr/lib/x86_64-linux-gnu/libc++.so
 create mode 100644 
clang/test/Driver/Inputs/cxx23_modules/usr/lib/x86_64-linux-gnu/modules.json
 create mode 100644 
clang/test/Driver/cxx23-modules-print-library-module-manifest-path.c
 create mode 100644 
clang/test/Driver/darwin-print-library-module-manifest-path.c

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 3ee1bcf2a69c9b..2e1e3b128744ff 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -602,6 +602,16 @@ class Driver {
   // FIXME: This should be in CompilationInfo.
   std::string GetProgramPath(StringRef Name, const ToolChain ) const;
 
+  /// GetModuleManifestPath - Lookup the name of the Standard library manifest.
+  ///
+  /// \param C - The compilation.
+  /// \param TC - The tool chain for additional information on
+  /// directories to search.
+  //
+  // FIXME: This should be in CompilationInfo.
+  std::string GetModuleManifestPath(const Compilation ,
+const ToolChain ) const;
+
   /// HandleAutocompletions - Handle --autocomplete by searching and printing
   /// possible flags, descriptions, and its arguments.
   void HandleAutocompletions(StringRef PassedFlags) const;
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2b93ddf033499c..890257e11485b6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5280,6 +5280,9 @@ def print_resource_dir : Flag<["-", "--"], 
"print-resource-dir">,
 def print_search_dirs : Flag<["-", "--"], "print-search-dirs">,
   HelpText<"Print the paths used for finding libraries and programs">,
   Visibility<[ClangOption, CLOption]>;
+def print_library_module_manifest_path : Flag<["-", "--"], 
"print-library-module-manifest-path">,
+  HelpText<"Print the path for the C++ Standard library module manifest">,
+  Visibility<[ClangOption, CLOption]>;
 def print_targets : Flag<["-", "--"], "print-targets">,
   HelpText<"Print the registered targets">,
   Visibility<[ClangOption, CLOption]>;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index ff95c899c5f3d4..8d682f9238c6b8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2164,6 +2164,12 @@ bool Driver::HandleImmediateArgs(const Compilation ) {
 return false;
   }
 
+  if (C.getArgs().hasArg(options::OPT_print_library_module_manifest_path)) {
+llvm::outs() << "module: ="
+ << GetModuleManifestPath(C, C.getDefaultToolChain()) << '\n';
+return false;
+  }
+
   if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
 if (std::optional RuntimePath = TC.getRuntimePath())
   llvm::outs() << *RuntimePath << '\n';
@@ -6135,6 +6141,40 @@ std::string Driver::GetProgramPath(StringRef Name, const 
ToolChain ) const {
   return std::string(Name);
 }
 
+std::string Driver::GetModuleManifestPath(const Compilation ,
+  const ToolChain ) const {
+
+  switch (TC.GetCXXStdlibType(C.getArgs())) {
+  case ToolChain::CST_Libcxx: {
+std::string lib = "libc++.so";
+std::string path = GetFilePath(lib, TC);
+
+// Note when there are multiple flavours of libc++ the module json needs to
+// look at the command-line arguments for the proper json.
+
+// For example
+/*
+const SanitizerArgs  = TC.getSanitizerArgs(C.getArgs());
+if (Sanitize.needsAsanRt())
+  return path.replace(path.size() - lib.size(), lib.size(),
+  "modules-asan.json");
+*/
+
+path = path.replace(path.size() - lib.size(), lib.size(), "modules.json");
+if (TC.getVFS().exists(path))
+  return path;
+
+return "";
+  }
+
+  case ToolChain::CST_Libstdcxx:
+// libstdc++ does not provide Standard library modules yet.
+return "";
+  }
+
+  return "";
+}
+
 std::string 

[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,31 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 
+improving readability and promoting the use of standard library functions.
+Note: this transformation may impact performance in performance-critical code 
due to potential 
+additional stores compared to the original if statement.
+
+Examples:
+
+Before:
+
+.. code-block:: c++
+
+  void foo() {
+  int a, b;

EugeneZelenko wrote:

Function body should be indented.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,31 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 
+improving readability and promoting the use of standard library functions.
+Note: this transformation may impact performance in performance-critical code 
due to potential 
+additional stores compared to the original if statement.
+
+Examples:
+
+Before:
+
+.. code-block:: c++
+
+  void foo() {
+  int a, b;
+  if (a < b)
+a = b;
+  }
+
+
+After:
+
+.. code-block:: c++
+
+  void foo() {
+  int a, b;

EugeneZelenko wrote:

Function body indentation. How about variables initialization?

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,31 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 
+improving readability and promoting the use of standard library functions.
+Note: this transformation may impact performance in performance-critical code 
due to potential 
+additional stores compared to the original if statement.
+
+Examples:
+
+Before:
+
+.. code-block:: c++
+
+  void foo() {
+  int a, b;
+  if (a < b)
+a = b;
+  }
+

EugeneZelenko wrote:

Missing closing bracket.

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


[clang] [Clang] Amend SME attributes with support for ZT0. (PR #77941)

2024-01-12 Thread via cfe-commits

rsandifo-arm wrote:

LGTM from a spec point of view, although it might be worth having some tests 
that have different ZA state from ZT0.  (But maybe not, since the code to 
handle ZA and ZT0 is mostly orthogonal.)

I won't approve because of the growth in `FunctionProtoType` — someone more 
qualified than me should sign off on that.

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


[clang-tools-extra] [clang-tidy] Fix false-positives in misc-static-assert caused by non-constexpr variables (PR #77203)

2024-01-12 Thread Congcong Cai via cfe-commits

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

LGTM

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


[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-01-12 Thread Mark de Wever via cfe-commits


@@ -0,0 +1,9 @@
+// Test that -print-library-module-manifest-path finds the correct file.
+//
+// Note this file is currently not available on Apple platforms

mordante wrote:

I'll remove this test for now. It can be added later when it's known where 
Apple will store this file.

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


[clang-tools-extra] [clang-tid]fix modernize-use-auto incorrect fix hints for pointer (PR #77943)

2024-01-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Congcong Cai (HerrCai0907)


Changes

avoid create incorrect fix hints for pointer to array type and pointer to 
function type Fixes: #77891

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp (+38-14) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index 7af30e688b6a71..af41c4b5071796 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -8,10 +8,12 @@
 
 #include "UseAutoCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Tooling/FixIt.h"
+#include "llvm/ADT/STLExtras.h"
 
 using namespace clang;
 using namespace clang::ast_matchers;
@@ -333,6 +335,26 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, 
ASTContext *Context) {
   << FixItHint::CreateReplacement(Range, "auto");
 }
 
+namespace {
+
+void ignoreTypeLocClasses(
+TypeLoc , llvm::SmallVector const ) {
+  while (llvm::is_contained(LocClasses, Loc.getTypeLocClass()))
+Loc = Loc.getNextTypeLoc();
+}
+
+bool isMutliLevelPointerToTypeLocClasses(
+TypeLoc Loc, llvm::SmallVector const ) {
+  ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified});
+  if (Loc.getTypeLocClass() != TypeLoc::Pointer)
+return false;
+  ignoreTypeLocClasses(Loc,
+   {TypeLoc::Paren, TypeLoc::Qualified, TypeLoc::Pointer});
+  return llvm::is_contained(LocClasses, Loc.getTypeLocClass());
+}
+
+} // namespace
+
 void UseAutoCheck::replaceExpr(
 const DeclStmt *D, ASTContext *Context,
 llvm::function_ref GetType, StringRef Message) {
@@ -384,16 +406,10 @@ void UseAutoCheck::replaceExpr(
   // information is not reliable where CV qualifiers are concerned so we can't
   // do anything about this case for now.
   TypeLoc Loc = FirstDecl->getTypeSourceInfo()->getTypeLoc();
-  if (!RemoveStars) {
-while (Loc.getTypeLocClass() == TypeLoc::Pointer ||
-   Loc.getTypeLocClass() == TypeLoc::Qualified)
-  Loc = Loc.getNextTypeLoc();
-  }
-  while (Loc.getTypeLocClass() == TypeLoc::LValueReference ||
- Loc.getTypeLocClass() == TypeLoc::RValueReference ||
- Loc.getTypeLocClass() == TypeLoc::Qualified) {
-Loc = Loc.getNextTypeLoc();
-  }
+  if (!RemoveStars)
+ignoreTypeLocClasses(Loc, {TypeLoc::Pointer, TypeLoc::Qualified});
+  ignoreTypeLocClasses(Loc, {TypeLoc::LValueReference, 
TypeLoc::RValueReference,
+ TypeLoc::Qualified});
   SourceRange Range(Loc.getSourceRange());
 
   if (MinTypeNameLength != 0 &&
@@ -405,12 +421,20 @@ void UseAutoCheck::replaceExpr(
 
   auto Diag = diag(Range.getBegin(), Message);
 
+  bool ShouldReplenishVariableName = isMutliLevelPointerToTypeLocClasses(
+  FirstDecl->getTypeSourceInfo()->getTypeLoc(),
+  {TypeLoc::FunctionProto, TypeLoc::ConstantArray});
+
   // Space after 'auto' to handle cases where the '*' in the pointer type is
   // next to the identifier. This avoids changing 'int *p' into 'autop'.
-  // FIXME: This doesn't work for function pointers because the variable name
-  // is inside the type.
-  Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto")
-   << StarRemovals;
+  llvm::StringRef Auto = ShouldReplenishVariableName
+ ? (RemoveStars ? "auto " : "auto *")
+ : (RemoveStars ? "auto " : "auto");
+  std::string ReplenishedVariableName =
+  ShouldReplenishVariableName ? FirstDecl->getQualifiedNameAsString() : "";
+  std::string Replacement =
+  (Auto + llvm::StringRef{ReplenishedVariableName}).str();
+  Diag << FixItHint::CreateReplacement(Range, Replacement) << StarRemovals;
 }
 
 void UseAutoCheck::check(const MatchFinder::MatchResult ) {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b4d87e0ed2a67a..9bf34177ebff2c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -405,6 +405,10 @@ Changes in existing checks
   false-positives when constructing the container with ``count`` copies of
   elements with value ``value``.
 
+- Improved :doc:`modernize-use-auto
+  ` to avoid create incorrect fix hints
+  for pointer to array type and pointer to function type.
+
 - Improved :doc:`modernize-use-emplace
   ` to not replace aggregates that
   ``emplace`` cannot construct with aggregate initialization.

``




https://github.com/llvm/llvm-project/pull/77943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-01-12 Thread Mark de Wever via cfe-commits


@@ -6135,6 +6141,42 @@ std::string Driver::GetProgramPath(StringRef Name, const 
ToolChain ) const {
   return std::string(Name);
 }
 
+std::string Driver::GetStdModuleManifestPath(const Compilation ,
+ const ToolChain ) const {
+
+  std::string error = "";
+
+  switch (TC.GetCXXStdlibType(C.getArgs())) {
+  case ToolChain::CST_Libcxx: {
+std::string lib = "libc++.so";
+std::string path = GetFilePath(lib, TC);
+
+// Note when there are multiple flavours of libc++ the module json needs to
+// look at the command-line arguments for the proper json.

mordante wrote:

We don't have multiple flavours yet, but I've updated the comment to give a bit 
more information.

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


[clang-tools-extra] [clang-tid]fix modernize-use-auto incorrect fix hints for pointer (PR #77943)

2024-01-12 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/77943

avoid create incorrect fix hints for pointer to array type and pointer to 
function type Fixes: #77891

>From 537d283288f555c2bb7cff90aee89fe9b18f08b8 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 13 Jan 2024 00:31:33 +0800
Subject: [PATCH] [clang-tid]fix modernize-use-auto incorrect fix hints for
 pointer

avoid create incorrect fix hints for pointer to array type and pointer to 
function type
Fixes: #77891
---
 .../clang-tidy/modernize/UseAutoCheck.cpp | 52 ++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 ++
 2 files changed, 42 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index 7af30e688b6a71..af41c4b5071796 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -8,10 +8,12 @@
 
 #include "UseAutoCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Tooling/FixIt.h"
+#include "llvm/ADT/STLExtras.h"
 
 using namespace clang;
 using namespace clang::ast_matchers;
@@ -333,6 +335,26 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, 
ASTContext *Context) {
   << FixItHint::CreateReplacement(Range, "auto");
 }
 
+namespace {
+
+void ignoreTypeLocClasses(
+TypeLoc , llvm::SmallVector const ) {
+  while (llvm::is_contained(LocClasses, Loc.getTypeLocClass()))
+Loc = Loc.getNextTypeLoc();
+}
+
+bool isMutliLevelPointerToTypeLocClasses(
+TypeLoc Loc, llvm::SmallVector const ) {
+  ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified});
+  if (Loc.getTypeLocClass() != TypeLoc::Pointer)
+return false;
+  ignoreTypeLocClasses(Loc,
+   {TypeLoc::Paren, TypeLoc::Qualified, TypeLoc::Pointer});
+  return llvm::is_contained(LocClasses, Loc.getTypeLocClass());
+}
+
+} // namespace
+
 void UseAutoCheck::replaceExpr(
 const DeclStmt *D, ASTContext *Context,
 llvm::function_ref GetType, StringRef Message) {
@@ -384,16 +406,10 @@ void UseAutoCheck::replaceExpr(
   // information is not reliable where CV qualifiers are concerned so we can't
   // do anything about this case for now.
   TypeLoc Loc = FirstDecl->getTypeSourceInfo()->getTypeLoc();
-  if (!RemoveStars) {
-while (Loc.getTypeLocClass() == TypeLoc::Pointer ||
-   Loc.getTypeLocClass() == TypeLoc::Qualified)
-  Loc = Loc.getNextTypeLoc();
-  }
-  while (Loc.getTypeLocClass() == TypeLoc::LValueReference ||
- Loc.getTypeLocClass() == TypeLoc::RValueReference ||
- Loc.getTypeLocClass() == TypeLoc::Qualified) {
-Loc = Loc.getNextTypeLoc();
-  }
+  if (!RemoveStars)
+ignoreTypeLocClasses(Loc, {TypeLoc::Pointer, TypeLoc::Qualified});
+  ignoreTypeLocClasses(Loc, {TypeLoc::LValueReference, 
TypeLoc::RValueReference,
+ TypeLoc::Qualified});
   SourceRange Range(Loc.getSourceRange());
 
   if (MinTypeNameLength != 0 &&
@@ -405,12 +421,20 @@ void UseAutoCheck::replaceExpr(
 
   auto Diag = diag(Range.getBegin(), Message);
 
+  bool ShouldReplenishVariableName = isMutliLevelPointerToTypeLocClasses(
+  FirstDecl->getTypeSourceInfo()->getTypeLoc(),
+  {TypeLoc::FunctionProto, TypeLoc::ConstantArray});
+
   // Space after 'auto' to handle cases where the '*' in the pointer type is
   // next to the identifier. This avoids changing 'int *p' into 'autop'.
-  // FIXME: This doesn't work for function pointers because the variable name
-  // is inside the type.
-  Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto")
-   << StarRemovals;
+  llvm::StringRef Auto = ShouldReplenishVariableName
+ ? (RemoveStars ? "auto " : "auto *")
+ : (RemoveStars ? "auto " : "auto");
+  std::string ReplenishedVariableName =
+  ShouldReplenishVariableName ? FirstDecl->getQualifiedNameAsString() : "";
+  std::string Replacement =
+  (Auto + llvm::StringRef{ReplenishedVariableName}).str();
+  Diag << FixItHint::CreateReplacement(Range, Replacement) << StarRemovals;
 }
 
 void UseAutoCheck::check(const MatchFinder::MatchResult ) {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b4d87e0ed2a67a..9bf34177ebff2c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -405,6 +405,10 @@ Changes in existing checks
   false-positives when constructing the container with ``count`` copies of
   elements with value ``value``.
 
+- Improved :doc:`modernize-use-auto
+  ` to avoid create incorrect fix hints
+  for pointer to array type and pointer to function type.
+
 - Improved :doc:`modernize-use-emplace
   ` to not 

[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Evgenii Kudriashov via cfe-commits

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Evgenii Kudriashov via cfe-commits

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Evgenii Kudriashov via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and should not use traditional AVX512 options anymore.
+
+The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
+from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
+enable all instructions within AVX10 version N at a maximum vector length of
+256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
+length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
+
+Current binaries built with AVX512 features can run on Intel AVX10/512 capable
+processor without re-compile, but cannot run on AVX10/256 capable processor.
+Users need to re-compile their code with ``-mavx10.N``, and maybe update some
+code that calling to 512-bit X86 specific intrinsics and passing or returning
+512-bit vector types in function call, if they want to run on AVX10/256 capable
+processor. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
+AVX10/512 capable processor.
+
+Users can add a ``-mno-evex512`` in the command line with AVX512 options if
+they want to run the binary on both legacy AVX512 and new AVX10/256 capable
+processors. The option has the same constraints as ``-mavx10.N``, i.e.,
+cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit 
vector
+types in function call.
+
+Users should avoid using AVX512 features in function target attributes when
+developing code for AVX10. If they have to do so, they need to add an explicit
+``evex512`` or ``no-evex512`` together with AVX512 features for 512-bit or
+non-512-bit functions respectively to avoid unexpected code generation. Both
+command line option and target attribute of EVEX512 feature can only be used
+with AVX512. They don't affect vector size of AVX10.
+
+User should not mix the use AVX10 and AVX512 options together at any time,
+because the option combinations are conflicting sometimes. For example, a
+combination of ``-mavx512f -mavx10.1-256`` doesn't show a clear intention to
+compiler, since instructions in AVX512F and AVX10.1/256 intersect but do not
+overlap. In this case, compiler will emit warning for it, but the behavior
+is determined. It will generate the same code as option ``-mavx10.1-512``.
+A similar case is ``-mavx512f -mavx10.2-256``, which equals to
+``-mavx10.1-512 -mavx10.2-256``, because ``avx10.2-256`` implies 
``avx10.1-256``
+and ``-mavx512f -mavx10.1-256`` equals to ``-mavx10.1-512``.
+
+There are some new macros introduced with AVX10 support. ``-mavx10.1-256`` will
+enable ``__AVX10_1__`` and ``__EVEX256__``, while ``-mavx10.1-512`` enables
+``__AVX10_1__``, ``__EVEX256__``, ``__EVEX512__``  and ``__AVX10_1_512__``.
+Besides, both ``-mavx10.1-256`` and ``-mavx10.1-512`` will enable all AVX512
+feature specific macros. A AVX512 feature will enable both ``__EVEX256__``,
+``__EVEX512__`` and its own macro. So ``__EVEX512__`` can be used to guard code
+that can run on both legacy AVX512 and AVX10/512 capable processors but cannot
+run on AVX10/256, while a AVX512 macro like ``__AVX512F__`` cannot tell the
+difference among the three options. Users need to check additional macros
+``__AVX10_1__`` and ``__EVEX512__`` if they want to make distinction.

e-kud wrote:

I don't know whether it matters to mention or not, but if a user want to 
compile code with old (before avx10 has been introduced) and new (after the 
introduction) compilers, then the user has to use something like this.

```if !defined(__AVX10_1__) && defined(__AVX512F__) || defined(__AVX512F__) && 
defined(__EVEX512__)```

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Evgenii Kudriashov via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.

e-kud wrote:

Processor**s**?

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


[clang] [llvm] [CMake][PGO] Build Sema.cpp to generate profdata for PGO builds (PR #77347)

2024-01-12 Thread Chris B via cfe-commits


@@ -26,9 +30,23 @@ if(LLVM_BUILD_INSTRUMENTED)
 message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
   else()
 add_custom_target(generate-profdata
-  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR}
+  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} 
${CMAKE_BINARY_DIR}/profiles/
   COMMENT "Merging profdata"
   DEPENDS generate-profraw)
+if (CLANG_PGO_TRAINING_DATA_SOURCE_DIR)
+  llvm_ExternalProject_Add(generate-profraw-external 
${CLANG_PGO_TRAINING_DATA_SOURCE_DIR}
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS 
generate-profraw)
+  add_dependencies(generate-profdata generate-profraw-external)
+else()
+  # Default to compiling a file from clang. This also builds all the
+  # dependencies needed to build this file, like TableGen.
+  set(generate_profraw_clang_sema 
tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/Sema.cpp.o)
+  llvm_ExternalProject_Add(generate-profraw-clang 
${CMAKE_CURRENT_SOURCE_DIR}/../../../llvm
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS generate-profraw
+  EXTRA_TARGETS generate_profraw_clang_sema

llvm-beanz wrote:

This is going to be really fragile. The paths of object file outputs are an 
implementation detail of CMake that has changed in the past and could change in 
the future, also I think only the makefile and ninja generator actually export 
those as buildable targets.

Beyond that I also have a philosophical problem with the approach of using 
living clang sources as training data. I think this can result in unexplainable 
or difficult to diagnose differences in the efficacy of PGO because as you 
change the compiler you're also innately changing the training data. A 
potential better solution would be to have a preprocessed Sema.cpp from a 
recent LLVM release that we check in as a stable copy. This would be similar to 
how the GCC compile-time benchmark works.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread Bhuminjay Soni via cfe-commits

https://github.com/11happy updated 
https://github.com/llvm/llvm-project/pull/77816

>From 1883d987b2f83adaef05fdb47ae25c7b06582a64 Mon Sep 17 00:00:00 2001
From: 11happy 
Date: Fri, 12 Jan 2024 00:02:46 +0530
Subject: [PATCH 01/12] Add readability check to suggest replacement of
 conditional statement with std::min/std::max

Signed-off-by: 11happy 
---
 .../clang-tidy/readability/CMakeLists.txt |  1 +
 .../ConditionaltostdminmaxCheck.cpp   | 86 +++
 .../readability/ConditionaltostdminmaxCheck.h | 30 +++
 .../readability/ReadabilityTidyModule.cpp |  3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../readability/ConditionalToStdMinMax.rst| 29 +++
 .../readability/ConditionalToStdMinMax.cpp| 27 ++
 8 files changed, 183 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/ConditionalToStdMinMax.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/ConditionalToStdMinMax.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 408c822b861c5f..4bc373bb69bb84 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -8,6 +8,7 @@ add_clang_library(clangTidyReadabilityModule
   AvoidReturnWithVoidValueCheck.cpp
   AvoidUnconditionalPreprocessorIfCheck.cpp
   BracesAroundStatementsCheck.cpp
+  ConditionaltostdminmaxCheck.cpp
   ConstReturnTypeCheck.cpp
   ContainerContainsCheck.cpp
   ContainerDataPointerCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
new file mode 100644
index 00..fba8c68f737450
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/ConditionaltostdminmaxCheck.cpp
@@ -0,0 +1,86 @@
+//===--- ConditionaltostdminmaxCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ConditionaltostdminmaxCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void ConditionaltostdminmaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+ifStmt(
+  has(
+binaryOperator(
+  anyOf(hasOperatorName("<"),hasOperatorName(">")),
+  hasLHS(ignoringImpCasts(declRefExpr().bind("lhsVar1"))),
+  hasRHS(ignoringImpCasts(declRefExpr().bind("rhsVar1")))
+  )
+  )
+,
+hasThen(
+  stmt(
+binaryOperator(
+  hasOperatorName("="),
+  hasLHS(ignoringImpCasts(declRefExpr().bind("lhsVar2"))),
+  hasRHS(ignoringImpCasts(declRefExpr().bind("rhsVar2")))
+  )
+)
+  ) 
+).bind("ifStmt"),this);
+
+
+
+}
+
+void ConditionaltostdminmaxCheck::check(const MatchFinder::MatchResult 
) {
+  const DeclRefExpr *lhsVar1 = Result.Nodes.getNodeAs("lhsVar1");
+  const DeclRefExpr *rhsVar1 = Result.Nodes.getNodeAs("rhsVar1");
+  const DeclRefExpr *lhsVar2 = Result.Nodes.getNodeAs("lhsVar2");
+  const DeclRefExpr *rhsVar2 = Result.Nodes.getNodeAs("rhsVar2"); 
 
+  const IfStmt *ifStmt = Result.Nodes.getNodeAs("ifStmt");
+
+  if (!lhsVar1 || !rhsVar1 || !lhsVar2 || !rhsVar2 || !ifStmt)
+return;
+
+  const BinaryOperator *binaryOp = dyn_cast(ifStmt->getCond());
+  if (!binaryOp)
+  return;
+
+  SourceLocation ifLocation = ifStmt->getIfLoc();
+  SourceLocation thenLocation = ifStmt->getEndLoc();
+
+  if(binaryOp->getOpcode() == BO_LT){
+if(lhsVar1->getDecl() == lhsVar2->getDecl() && rhsVar1->getDecl() == 
rhsVar2->getDecl()){
+  diag(ifStmt->getIfLoc(), "use std::max instead of 
<")getNameInfo().getAsString() + ", " +
+  rhsVar1->getNameInfo().getAsString() + 
")");
+}
+else if(lhsVar1->getDecl() == rhsVar2->getDecl() && rhsVar1->getDecl() == 
lhsVar2->getDecl()){
+  diag(ifStmt->getIfLoc(), "use std::min instead of 
<")getNameInfo().getAsString() + ", " +
+  rhsVar1->getNameInfo().getAsString() + 
")");
+}
+  }
+  else if(binaryOp->getOpcode() == BO_GT){
+if(lhsVar1->getDecl() == 

[clang] [Clang] Amend SME attributes with support for ZT0. (PR #77941)

2024-01-12 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 9803de0e8e3abbbc94a4265d5847db435897a384 
6b8d1c8cc772a14a820ab1fdcd6d368b0117d170 -- 
clang/test/CodeGen/aarch64-sme2-intrinsics/aarch64-sme2-attrs.cpp 
clang/include/clang/AST/Type.h clang/include/clang/Basic/AttributeCommonInfo.h 
clang/include/clang/Basic/TokenKinds.h clang/include/clang/Sema/Sema.h 
clang/lib/AST/TypePrinter.cpp clang/lib/CodeGen/CGCall.cpp 
clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Parse/ParseDecl.cpp 
clang/lib/Parse/ParseDeclCXX.cpp clang/lib/Parse/ParseTentative.cpp 
clang/lib/Sema/SemaChecking.cpp clang/lib/Sema/SemaDecl.cpp 
clang/lib/Sema/SemaDeclAttr.cpp clang/lib/Sema/SemaDeclCXX.cpp 
clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaOverload.cpp 
clang/lib/Sema/SemaType.cpp clang/test/AST/ast-dump-sme-attributes.cpp 
clang/test/CodeGen/aarch64-sme-intrinsics/aarch64-sme-attrs.cpp 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_add-i32.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_add-i64.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_ld1.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_ld1_vnum.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_ldr.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_mopa-za32.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_mopa-za64.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_mops-za32.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_mops-za64.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_read.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_st1.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_st1_vnum.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_state_funs.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_str.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_write.c 
clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_zero.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_add.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_bmop.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_fp_dots.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_int_dots.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti2_lane_zt.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti2_lane_zt_x2.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti2_lane_zt_x4.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_lane_zt.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_lane_zt_x2.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_lane_zt_x4.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mla.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mlal.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mlall.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mls.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mlsl.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_mop.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_read.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_sub.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_vdot.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_write.c 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_zero_zt.c 
clang/test/Modules/aarch64-sme-keywords.cppm 
clang/test/Parser/c2x-attribute-keywords.c 
clang/test/Parser/cxx0x-keyword-attributes.cpp 
clang/test/Sema/aarch64-incompat-sm-builtin-calls.c 
clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp 
clang/test/Sema/aarch64-sme-func-attrs.c 
clang/test/Sema/aarch64-sme-intrinsics/acle_sme_imm.cpp 
clang/test/Sema/aarch64-sme-intrinsics/acle_sme_target.c 
clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_imm.cpp 
clang/utils/TableGen/ClangAttrEmitter.cpp clang/utils/TableGen/SveEmitter.cpp 
clang/utils/TableGen/TableGen.cpp clang/utils/TableGen/TableGenBackends.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 64d4cde1c9..089704618c 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -7542,9 +7542,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
   CallerHasZT0State = true;
 else if (const auto *FPT =
  CallerFD->getType()->getAs())
-  CallerHasZT0State = FunctionType::getArmZT0State(
- FPT->getExtProtoInfo().AArch64SMEAttributes) 
!=
- FunctionType::ARM_None;
+  CallerHasZT0State =
+  FunctionType::getArmZT0State(
+  FPT->getExtProtoInfo().AArch64SMEAttributes) !=
+  FunctionType::ARM_None;
   }
 
   if (!CallerHasZT0State)

``





[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Erich Keane via cfe-commits


@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,CXX98
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+
+namespace dr1807 { // dr1807: 3.0
+struct S {
+  S() {}
+  ~S() {}
+};
+
+void f() {
+  S s[3];
+}
+}
+
+// CHECK-LABEL:  define dso_local void @dr1807::f()
+// CHECK:  invoke void @dr1807::S::S(){{.+}}
+// CHECK-NEXT: {{.+}} unwind label %lpad
+// CHECK-LABEL:  lpad:
+// CHECK:  br {{.+}}, label {{.+}}, label %arraydestroy.body
+// CHECK-LABEL:  arraydestroy.body: 
+// CHECK:  [[ARRAYDESTROY_ELEMENT:%.*]] = getelementptr {{.+}}, 
i64 -1
+// CXX98-NEXT: invoke void 
@dr1807::S::~S(){{.*}}[[ARRAYDESTROY_ELEMENT]]
+// SINCE-CXX11-NEXT:   call void @dr1807::S::~S(){{.*}}[[ARRAYDESTROY_ELEMENT]]

erichkeane wrote:

```suggestion
// SINCE-CXX11-NEXT:   call void 
@dr1807::S::~S()({{.*}}[[ARRAYDESTROY_ELEMENT]])
```

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Erich Keane via cfe-commits

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

1 nit for readability sake, else is good enough.

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Erich Keane via cfe-commits


@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,CXX98
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+
+namespace dr1807 { // dr1807: 3.0
+struct S {
+  S() {}
+  ~S() {}
+};
+
+void f() {
+  S s[3];
+}
+}
+
+// CHECK-LABEL:  define dso_local void @dr1807::f()
+// CHECK:  invoke void @dr1807::S::S(){{.+}}
+// CHECK-NEXT: {{.+}} unwind label %lpad
+// CHECK-LABEL:  lpad:
+// CHECK:  br {{.+}}, label {{.+}}, label %arraydestroy.body
+// CHECK-LABEL:  arraydestroy.body: 
+// CHECK:  [[ARRAYDESTROY_ELEMENT:%.*]] = getelementptr {{.+}}, 
i64 -1
+// CXX98-NEXT: invoke void 
@dr1807::S::~S(){{.*}}[[ARRAYDESTROY_ELEMENT]]

erichkeane wrote:

```suggestion
// CXX98-NEXT: invoke void 
@dr1807::S::~S()({{.*}}[[ARRAYDESTROY_ELEMENT]])
```

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Erich Keane via cfe-commits

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


[clang] [clang] Add test for CWG1807 (PR #77637)

2024-01-12 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/77637

>From 545ee4900e48b186e1c9fff93dc62a459ee19754 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 20:27:53 +0300
Subject: [PATCH 1/6] [clang] Add test for CWG1807

The test checks that objects in arrays are destructed in reverse order during 
stack unwinding.
---
 clang/test/CXX/drs/dr1807.cpp | 31 +++
 clang/www/cxx_dr_status.html  |  2 +-
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CXX/drs/dr1807.cpp

diff --git a/clang/test/CXX/drs/dr1807.cpp b/clang/test/CXX/drs/dr1807.cpp
new file mode 100644
index 00..f599a36c8b2cbd
--- /dev/null
+++ b/clang/test/CXX/drs/dr1807.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,CXX98
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - 
-fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s 
--check-prefixes CHECK,SINCE-CXX11
+
+namespace dr1807 { // dr1807: 3.0
+struct S {
+  S() {}
+  ~S() {}
+};
+
+void f() {
+  try {
+S s[3];
+  } catch (...) {}
+}
+}
+
+// CHECK:  invoke void @dr1807::S::S(){{.+}}
+// CHECK-NEXT: {{.+}} unwind label %lpad
+
+// CHECK-LABEL:  lpad:
+// CHECK:  br {{.+}}, label {{.+}}, label %arraydestroy.body
+
+// CHECK-LABEL:  arraydestroy.body:
+// CHECK:  %arraydestroy.element = getelementptr {{.+}}, i64 -1
+// CXX98-NEXT: invoke void @dr1807::S::~S(){{.*}}%arraydestroy.element
+// SINCE-CXX11-NEXT:   call void @dr1807::S::~S(){{.*}}%arraydestroy.element
diff --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index 2bded63d5cd41c..bea9d0f54c471e 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -10649,7 +10649,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/1807.html;>1807
 CD4
 Order of destruction of array elements after an exception
-Unknown
+Clang 3.0
   
   
 https://cplusplus.github.io/CWG/issues/1808.html;>1808

>From 81b5f521c4e8e77f39ef1b01612a7866c6de8440 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 21:57:30 +0300
Subject: [PATCH 2/6] Leave a comment in dr18xx.cpp

---
 clang/test/CXX/drs/dr18xx.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/test/CXX/drs/dr18xx.cpp b/clang/test/CXX/drs/dr18xx.cpp
index 1d76804907a5c1..e092c83ab4ce42 100644
--- a/clang/test/CXX/drs/dr18xx.cpp
+++ b/clang/test/CXX/drs/dr18xx.cpp
@@ -164,6 +164,8 @@ void A::C::f4() {
 }
 } // namespace dr1804
 
+// dr1807 is in separate file
+
 namespace dr1812 { // dr1812: no
// NB: dup 1710
 #if __cplusplus >= 201103L

>From 59ec23c9cdd4d4557c0b471331683d577add31d6 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 22:06:01 +0300
Subject: [PATCH 3/6] Eliminate the need for readers to guess how the file is
 named

---
 clang/test/CXX/drs/dr18xx.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/CXX/drs/dr18xx.cpp b/clang/test/CXX/drs/dr18xx.cpp
index e092c83ab4ce42..530122ccd1aab1 100644
--- a/clang/test/CXX/drs/dr18xx.cpp
+++ b/clang/test/CXX/drs/dr18xx.cpp
@@ -164,7 +164,7 @@ void A::C::f4() {
 }
 } // namespace dr1804
 
-// dr1807 is in separate file
+// dr1807 is in dr1807.cpp
 
 namespace dr1812 { // dr1812: no
// NB: dup 1710

>From 62f1fa6bb3c691dde2e903711634857de486e71e Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 10 Jan 2024 23:33:41 +0300
Subject: [PATCH 4/6] Simplify C++ part of the test

---
 clang/test/CXX/drs/dr1807.cpp | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/clang/test/CXX/drs/dr1807.cpp b/clang/test/CXX/drs/dr1807.cpp
index f599a36c8b2cbd..e654987b485c76 100644
--- 

[clang] 6f55c13 - [clang[test] Require x86 target for new tests

2024-01-12 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2024-01-12T16:08:52Z
New Revision: 6f55c134d4aaa9eab9ef53886c2532d6da72ca47

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

LOG: [clang[test] Require x86 target for new tests

Fixes d199ab469949b104bc4fbb888251ee184fd53de1.

Added: 


Modified: 
clang/test/CodeGen/debug-names-compound-type-units.ll
clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll

Removed: 




diff  --git a/clang/test/CodeGen/debug-names-compound-type-units.ll 
b/clang/test/CodeGen/debug-names-compound-type-units.ll
index 0d85de286772a3..62cecfdeaf7f94 100644
--- a/clang/test/CodeGen/debug-names-compound-type-units.ll
+++ b/clang/test/CodeGen/debug-names-compound-type-units.ll
@@ -1,4 +1,5 @@
 ; REQUIRES: asserts
+; REQUIRES: x86-registered-target
 
 ;; Tests that we use correct accelerator table when processing nested TUs.
 ;; Assert is not triggered.

diff  --git a/clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll 
b/clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll
index 53aec43a050f8b..8719473820053e 100644
--- a/clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll
+++ b/clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll
@@ -1,4 +1,5 @@
 ; REQUIRES: asserts
+; REQUIRES: x86-registered-target
 
 ;; Tests that accelerator table switches correctly from TU to CU when a top 
level TU is re-used.
 ;; Assert is not triggered.



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


[clang] [clang][analyzer] Add function 'fprintf' to StreamChecker. (PR #77613)

2024-01-12 Thread Balázs Kéri via cfe-commits

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


[clang] 8550e88 - [clang][analyzer] Add function 'fprintf' to StreamChecker. (#77613)

2024-01-12 Thread via cfe-commits

Author: Balázs Kéri
Date: 2024-01-12T17:00:14+01:00
New Revision: 8550e8845c4fe1aea3bd3d69bcc33d33040b1f13

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

LOG: [clang][analyzer] Add function 'fprintf' to StreamChecker. (#77613)

[clang][analyzer] Add function 'fprintf' to StreamChecker.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
clang/test/Analysis/stream-error.c
clang/test/Analysis/stream.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 742426a628e065..95c7503e49e0d3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -263,6 +263,9 @@ class StreamChecker : public Checker(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  const StreamState *OldSS = State->get(StreamSym);
+  if (!OldSS)
+return;
+
+  assertStreamStateOpened(OldSS);
+
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
+  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+  SValBuilder  = C.getSValBuilder();
+  auto  = C.getASTContext();
+  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
+SVB.getConditionType())
+  .getAs();
+  if (!Cond)
+return;
+  ProgramStateRef StateNotFailed, StateFailed;
+  std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
+
+  StateNotFailed =
+  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  C.addTransition(StateNotFailed);
+
+  // Add transition for the failed state. The resulting value of the file
+  // position indicator for the stream is indeterminate.
+  StateFailed = StateFailed->set(
+  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  C.addTransition(StateFailed);
+}
+
 void StreamChecker::evalUngetc(const FnDescription *Desc, const CallEvent 
,
CheckerContext ) const {
   ProgramStateRef State = C.getState();

diff  --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 2d03c0bbe7c474..0f7fdddc0dd4cd 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -191,6 +191,23 @@ void error_fputs(void) {
   fputs("ABC", F); // expected-warning {{Stream might be already closed}}
 }
 
+void error_fprintf(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fprintf(F, "aaa");
+  if (Ret >= 0) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+fprintf(F, "bbb"); // no-warning
+  } else {
+clang_analyzer_eval(ferror(F)); // expected-warning {{TRUE}}
+clang_analyzer_eval(feof(F));   // expected-warning {{FALSE}}
+fprintf(F, "bbb");  // expected-warning {{might be 
'indeterminate'}}
+  }
+  fclose(F);
+  fprintf(F, "ccc"); // expected-warning {{Stream might be already closed}}
+}
+
 void error_ungetc() {
   FILE *F = tmpfile();
   if (!F)

diff  --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c
index d8026247697a50..e8f06922bdb2f3 100644
--- a/clang/test/Analysis/stream.c
+++ b/clang/test/Analysis/stream.c
@@ -39,6 +39,12 @@ void check_fputs(void) {
   fclose(fp);
 }
 
+void check_fprintf(void) {
+  FILE *fp = tmpfile();
+  fprintf(fp, "ABC"); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
 void check_ungetc(void) {
   FILE *fp = tmpfile();
   ungetc('A', fp); // expected-warning {{Stream pointer might be NULL}}
@@ -271,9 +277,8 @@ void check_escape4(void) {
 return;
   fwrite("1", 1, 1, F); // may fail
 
-  // no escape at (non-StreamChecker-handled) system call
-  // FIXME: all such calls should be handled by the checker
-  fprintf(F, "0");
+  // no escape at a non-StreamChecker-handled system call
+  setbuf(F, "0");
 
   fwrite("1", 1, 1, F); // expected-warning {{might be 'indeterminate'}}
   fclose(F);



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


[clang] [coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/77066

>From 3e0d0ab6c4fc6cba68285816a95e423bc18e8e55 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 5 Jan 2024 10:11:20 +0100
Subject: [PATCH 1/7] [coroutines] Detect lifetime issues with coroutine lambda
 captures

---
 clang/lib/Sema/SemaInit.cpp   | 20 +--
 clang/test/SemaCXX/coro-lifetimebound.cpp | 64 +--
 2 files changed, 76 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 60c0e3e74204ec..c100bf11454786 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
@@ -33,6 +34,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath , Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it not lifetimebound.
+if (Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;
+if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
+  VisitLifetimeBoundArg(Callee, ObjectArg);
+  }
+
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
diff --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index 3fc7ca70a14a12..319134450e4b6f 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -64,6 +64,10 @@ Co bar_coro(const int , int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
+// 
=
+// Lambdas
+// 
=
+namespace lambdas {
 void lambdas() {
   auto unsafe_lambda = [] [[clang::coro_wrapper]] (int b) {
 return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
@@ -84,15 +88,47 @@ void lambdas() {
 co_return x + co_await foo_coro(b);
   };
 }
+
+Co lambda_captures() {
+  int a = 1;
+  // Temporary lambda object dies.
+  auto lamb = [a](int x, const int& y) -> Co { // expected-warning 
{{temporary whose address is used as value of local variable 'lamb'}}
+co_return x + y + a;
+  }(1, a);
+  // Object dies but it has no capture.
+  auto no_capture = []() -> Co { co_return 1; }();
+  auto bad_no_capture = [](const int& a) -> Co { co_return a; }(1); // 
expected-warning {{temporary}}
+  // Temporary lambda object with lifetime extension under co_await.
+  int res = co_await [a](int x, const int& y) -> Co {
+co_return x + y + a;
+  }(1, a);
+  co_return 1;
+}
+} // namespace lambdas
+
 // 
=
-// Safe usage when parameters are value
+// Member coroutines
 // 
=
-namespace by_value {
-Co value_coro(int b) { co_return co_await foo_coro(b); }
-[[clang::coro_wrapper]] Co wrapper1(int b) { return value_coro(b); }
-[[clang::coro_wrapper]] Co wrapper2(const int& b) { return value_coro(b); 
}
+namespace member_coroutines{
+struct S {
+  Co member(const int& a) { co_return a; }  
+};
+
+Co use() {
+  S s;
+  int a = 1;
+  auto test1 = s.member(1);  // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto test2 = s.member(a);
+  auto test3 = S{}.member(a);  // expected-warning {{temporary whose address 
is used as value of local variable}}
+  co_return 1;
 }
 
+[[clang::coro_wrapper]] Co wrapper(const int& a) {
+  S s;
+  return s.member(a); // expected-warning {{address of stack memory}}
+}
+} // member_coroutines
+
 // 
=
 // Lifetime bound but not a Coroutine Return Type: No 

[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,35 @@
+// RUN: %check_clang_tidy %s readability-use-std-min-max %t
+
+void foo() {
+  int value1,value2,value3;
+  short value4;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (value2 > value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max
+  if (value2 > value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // No suggestion needed here
+  if (value1 == value2)
+value1 = value2;
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if(value1https://github.com/llvm/llvm-project/pull/77816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,33 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 
+improving readability and promoting the use of standard library functions.
+Note: While this transformation improves code clarity, it may not be
+suitable for performance-critical code. Using ``std::min`` or ``std::max`` can
+introduce additional stores, potentially impacting performance compared to
+the original if statement that only assigns when the value needs to change.
+
+Examples:
+
+Before:
+
+.. code-block:: c++
+
+  void foo(){

EugeneZelenko wrote:

Please Clang-format both snippets.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,33 @@
+.. title:: clang-tidy - readability-use-std-min-max
+
+readability-use-std-min-max
+===
+
+Replaces certain conditional statements with equivalent ``std::min`` or 
``std::max`` expressions, 

EugeneZelenko wrote:

Please follow 80-characters limit.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-12 Thread via cfe-commits


@@ -0,0 +1,97 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void UseStdMinMaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  ifStmt(
+  has(binaryOperator(
+  anyOf(hasOperatorName("<"), hasOperatorName(">"),
+hasOperatorName("<="), hasOperatorName(">=")),
+  hasLHS(expr().bind("lhsVar1")), hasRHS(expr().bind("rhsVar1",
+  hasThen(stmt(binaryOperator(hasOperatorName("="),
+  hasLHS(expr().bind("lhsVar2")),
+  hasRHS(expr().bind("rhsVar2"))
+  .bind("ifStmt"),
+  this);
+}
+
+void UseStdMinMaxCheck::check(const MatchFinder::MatchResult ) {
+  const auto *lhsVar1 = Result.Nodes.getNodeAs("lhsVar1");
+  const auto *rhsVar1 = Result.Nodes.getNodeAs("rhsVar1");
+  const auto *lhsVar2 = Result.Nodes.getNodeAs("lhsVar2");
+  const auto *rhsVar2 = Result.Nodes.getNodeAs("rhsVar2");
+  const auto *ifStmt = Result.Nodes.getNodeAs("ifStmt");
+  auto  = *Result.Context;
+
+  if (!lhsVar1 || !rhsVar1 || !lhsVar2 || !rhsVar2 || !ifStmt)
+return;
+
+  const BinaryOperator *binaryOp = dyn_cast(ifStmt->getCond());

EugeneZelenko wrote:

`const auto *`

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


[clang] [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in StdLibraryFunctionsChecker (PR #77902)

2024-01-12 Thread Balázs Kéri via cfe-commits


@@ -2859,13 +2859,19 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 "fseeko",
 Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsZeroOrMinusOne, ErrnoIrrelevant)
-.ArgConstraint(NotNull(ArgNo(0;
+.Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}})));
 
 // off_t ftello(FILE *stream);
 addToFunctionSummaryMap(
 "ftello", Signature(ArgTypes{FilePtrTy}, RetType{Off_tTy}),
-Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, Range(0, LongMax))},
+  ErrnoUnchanged, GenericSuccessMsg)

balazske wrote:

```suggestion
  ErrnoMustNotBeChecked, GenericSuccessMsg)
```
`ftello` may change `errno` if successful, contrary to `ftell.`

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


[clang] [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in StdLibraryFunctionsChecker (PR #77902)

2024-01-12 Thread Balázs Kéri via cfe-commits


@@ -2859,13 +2859,19 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 "fseeko",
 Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsZeroOrMinusOne, ErrnoIrrelevant)
-.ArgConstraint(NotNull(ArgNo(0;
+.Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}})));

balazske wrote:

Please move the code of function `fseeko` to after `fseek`, and `ftello` after 
`ftell`.

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


[clang-tools-extra] [clang-tidy] Fix false-positives in misc-static-assert caused by non-constexpr variables (PR #77203)

2024-01-12 Thread Justin Cady via cfe-commits

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

Context: I have limited experience writing AST matchers, but I saw [the request 
for 
reviewers](https://discourse.llvm.org/t/clang-tidy-18-reviewers-wanted/76108). 
I'm basing this review on that limited experience and the tests put in place 
with this diff.

On those grounds, these changes LGTM.

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


[clang] [llvm] [clang-tools-extra] [compiler-rt] [flang] [libcxx] [Clang][Sema] Fix qualifier restriction of overriden methods (PR #71696)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -289,3 +289,29 @@ namespace PR8168 {
 static void foo() {} // expected-error{{'static' member function 'foo' 
overrides a virtual function}}
   };
 }
+
+namespace T13 {

AaronBallman wrote:

I'd like to see additional test cases involving type aliases with and without 
qualifiers. e.g.,
```
namespace T13 {
  using cip = const int *;
  using ip = int *;

  class A {
  public:
virtual const int *foo();
virtual const int *bar();
virtual const int *baz();
virtual const int *quux();
  };

  class B: public A {
  public:
cip foo() override; // Okay
const int *bar() override; // Okay
int *baz() override; // Diagnosed
ip quux() override; // Diagnosed
  };
}
```
and similar for the class-based tests.

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


[libcxx] [clang-tools-extra] [compiler-rt] [llvm] [flang] [clang] [Clang][Sema] Fix qualifier restriction of overriden methods (PR #71696)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -799,6 +799,11 @@ Bug Fixes to C++ Support
   completes (except deduction guides). Fixes:
   (`#59827 `_)
 
+- Clang now reports error when overriden method's non-class return type drops
+  qualifiers, or qualifiers of class return type are not subset of super 
method's.
+  Fixes:

AaronBallman wrote:

```suggestion
- Clang now reports error when an overriden method's non-class return type drops
  qualifiers, or qualifiers of the class return type are not a subset of the 
overridden method's.
  Fixes:
```

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


[clang] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-01-12 Thread Sam Tebbs via cfe-commits

https://github.com/SamTebbs33 updated 
https://github.com/llvm/llvm-project/pull/77936

>From bbc6c11cd3def5acbb2ba2f2ddc45df2c399f9d6 Mon Sep 17 00:00:00 2001
From: Samuel Tebbs 
Date: Wed, 10 Jan 2024 14:57:04 +
Subject: [PATCH 1/2] [Clang][SME] Detect always_inline used with mismatched
 streaming attributes

This patch adds an error that is emitted when a streaming function is
marked as always_inline and is called from a non-streaming function.
---
 .../clang/Basic/DiagnosticFrontendKinds.td|  2 ++
 clang/include/clang/Sema/Sema.h   |  9 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 clang/lib/CodeGen/Targets/AArch64.cpp | 20 ++
 clang/lib/Sema/SemaChecking.cpp   | 27 +++
 ...-sme-func-attrs-inline-locally-streaming.c | 12 +
 .../aarch64-sme-func-attrs-inline-streaming.c | 12 +
 7 files changed, 66 insertions(+), 17 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c
 create mode 100644 clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 568000106a84dc..dbd92b600a936e 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -279,6 +279,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def err_function_alwaysinline_attribute_mismatch : Error<
+  "always_inline function %1 and its caller %0 have mismatched %2 attributes">;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4c464a1ae4c67f..0fed60103c9a2c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13803,8 +13803,17 @@ class Sema final {
 FormatArgumentPassingKind ArgPassingKind;
   };
 
+enum ArmStreamingType {
+  ArmNonStreaming,
+  ArmStreaming,
+  ArmStreamingCompatible,
+  ArmStreamingOrSVE2p1
+};
+
+
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
+  static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
 
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 52216d93a302bb..03a6f2f1d7a9d2 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -151,4 +151,5 @@ add_clang_library(clangCodeGen
   clangFrontend
   clangLex
   clangSerialization
+  clangSema
   )
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 7102d190fe008b..ea3d5a97605f1c 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -8,6 +8,8 @@
 
 #include "ABIInfoImpl.h"
 #include "TargetInfo.h"
+#include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Sema/Sema.h"
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -153,6 +155,11 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 }
 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
   }
+
+  void checkFunctionCallABI(CodeGenModule , SourceLocation CallLoc,
+const FunctionDecl *Caller,
+const FunctionDecl *Callee,
+const CallArgList ) const override;
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
@@ -812,6 +819,19 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList ) const {
+if (!Callee->hasAttr())
+  return;
+
+auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
+auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+
+if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+}
+
 std::unique_ptr
 CodeGen::createAArch64TargetCodeGenInfo(CodeGenModule ,
 AArch64ABIKind Kind) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 74f8f626fb1637..160637dde448e4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ 

[clang] [coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-12 Thread Utkarsh Saxena via cfe-commits


@@ -297,6 +297,26 @@ struct ReadySuspendResumeResult {
   bool IsInvalid;
 };
 
+// Adds [[clang::coro_wrapper]] and [[clang::coro_disable_lifetimebound]]
+// attributes to `get_return_object`.
+static void handleGetReturnObject(Sema , MemberExpr *ME) {
+  if (!ME || !ME->getMemberDecl() || !ME->getMemberDecl()->getAsFunction())
+return;
+  auto *MD = ME->getMemberDecl()->getAsFunction();
+  auto *RetType = MD->getReturnType()->getAsRecordDecl();
+  if (!RetType || !RetType->hasAttr())
+return;
+  // `get_return_object` should be allowed to return coro_return_type.
+  if (!MD->hasAttr())
+MD->addAttr(
+CoroWrapperAttr::CreateImplicit(S.getASTContext(), MD->getLocation()));
+  // Object arg of `__promise.get_return_object()` is not lifetimebound.
+  if (RetType->hasAttr() &&
+  !MD->hasAttr())
+MD->addAttr(CoroDisableLifetimeBoundAttr::CreateImplicit(
+S.getASTContext(), MD->getLocation()));
+}
+

usx95 wrote:

Moved the check to `makeReturnObject`.

> Then we should be able to get rid of hard-coding the get_return_object name 
> in Sema::CheckCoroutineWrapper too?

`CheckCoroutineWrapper` is called in `ActOnFinishFunctionBody`. At this point, 
we are in the `promise::get_return_object` definition. It is possible that we 
have not seen any coroutine associated with this promise until now. So the 
coroutine statements would not have been generated.

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


[clang] [coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/77066

>From 3e0d0ab6c4fc6cba68285816a95e423bc18e8e55 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 5 Jan 2024 10:11:20 +0100
Subject: [PATCH 1/6] [coroutines] Detect lifetime issues with coroutine lambda
 captures

---
 clang/lib/Sema/SemaInit.cpp   | 20 +--
 clang/test/SemaCXX/coro-lifetimebound.cpp | 64 +--
 2 files changed, 76 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 60c0e3e74204ec..c100bf11454786 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
@@ -33,6 +34,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath , Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it not lifetimebound.
+if (Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;
+if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
+  VisitLifetimeBoundArg(Callee, ObjectArg);
+  }
+
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
diff --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index 3fc7ca70a14a12..319134450e4b6f 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -64,6 +64,10 @@ Co bar_coro(const int , int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
+// 
=
+// Lambdas
+// 
=
+namespace lambdas {
 void lambdas() {
   auto unsafe_lambda = [] [[clang::coro_wrapper]] (int b) {
 return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
@@ -84,15 +88,47 @@ void lambdas() {
 co_return x + co_await foo_coro(b);
   };
 }
+
+Co lambda_captures() {
+  int a = 1;
+  // Temporary lambda object dies.
+  auto lamb = [a](int x, const int& y) -> Co { // expected-warning 
{{temporary whose address is used as value of local variable 'lamb'}}
+co_return x + y + a;
+  }(1, a);
+  // Object dies but it has no capture.
+  auto no_capture = []() -> Co { co_return 1; }();
+  auto bad_no_capture = [](const int& a) -> Co { co_return a; }(1); // 
expected-warning {{temporary}}
+  // Temporary lambda object with lifetime extension under co_await.
+  int res = co_await [a](int x, const int& y) -> Co {
+co_return x + y + a;
+  }(1, a);
+  co_return 1;
+}
+} // namespace lambdas
+
 // 
=
-// Safe usage when parameters are value
+// Member coroutines
 // 
=
-namespace by_value {
-Co value_coro(int b) { co_return co_await foo_coro(b); }
-[[clang::coro_wrapper]] Co wrapper1(int b) { return value_coro(b); }
-[[clang::coro_wrapper]] Co wrapper2(const int& b) { return value_coro(b); 
}
+namespace member_coroutines{
+struct S {
+  Co member(const int& a) { co_return a; }  
+};
+
+Co use() {
+  S s;
+  int a = 1;
+  auto test1 = s.member(1);  // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto test2 = s.member(a);
+  auto test3 = S{}.member(a);  // expected-warning {{temporary whose address 
is used as value of local variable}}
+  co_return 1;
 }
 
+[[clang::coro_wrapper]] Co wrapper(const int& a) {
+  S s;
+  return s.member(a); // expected-warning {{address of stack memory}}
+}
+} // member_coroutines
+
 // 
=
 // Lifetime bound but not a Coroutine Return Type: No 

[clang] [llvm] [LLVM][DWARF] Fix accelerator table switching between CU and TU (PR #77511)

2024-01-12 Thread Alexander Yermolovich via cfe-commits

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


[clang] d199ab4 - [LLVM][DWARF] Fix accelerator table switching between CU and TU (#77511)

2024-01-12 Thread via cfe-commits

Author: Alexander Yermolovich
Date: 2024-01-12T07:01:17-08:00
New Revision: d199ab469949b104bc4fbb888251ee184fd53de1

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

LOG: [LLVM][DWARF] Fix accelerator table switching between CU and TU (#77511)

Bug 1 is triggered when a TU is already created, and we process the same
DICompositeType at a top level. We would switch to TU accelerator table,
but
would not switch back on early exit. As the result we would add CU
entries to the TU
accelerator table. When we try to write out TUs and normalize entries,
the
offsets for DIEs that are part of a CU would not have been computed, and
it
would assert on getOffset().

Bug 2 is triggered when processing nested TUs. When we exit from
addDwarfTypeUnitType we switched back to CU accelerator table. If we
were processing nested TUs, the rest of the entries from TUs would be
added to CU accelerator table. When we write out TUs, all the DIE
pointers will become invalid. Eventually it will assert during
normalization step after CU is processed.

Added: 
clang/test/CodeGen/debug-names-compound-type-units.ll
clang/test/CodeGen/thinlto-debug-names-tu-reuse.ll

Modified: 
llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp

Removed: 




diff  --git a/clang/test/CodeGen/debug-names-compound-type-units.ll 
b/clang/test/CodeGen/debug-names-compound-type-units.ll
new file mode 100644
index 00..0d85de286772a3
--- /dev/null
+++ b/clang/test/CodeGen/debug-names-compound-type-units.ll
@@ -0,0 +1,73 @@
+; REQUIRES: asserts
+
+;; Tests that we use correct accelerator table when processing nested TUs.
+;; Assert is not triggered.
+;; File1
+;; struct Foo {
+;;   char f;
+;; };
+;; struct Foo2 {
+;;   char f;
+;;   Foo f1;
+;; };
+;; void fooFunc() {
+;; Foo2 global2;
+;; }
+;; clang++ .cpp -O0 -g2 -fdebug-types-section -gpubnames -S -emit-llvm 
-o .ll
+
+; RUN: llc -O0 -dwarf-version=5 -generate-type-units -filetype=obj < %s -o %t.o
+; RUN: llvm-readelf --sections %t.o | FileCheck --check-prefix=OBJ %s
+
+; OBJ: debug_names
+
+; ModuleID = 'main.cpp'
+source_filename = "main.cpp"
+target datalayout = 
"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+%struct.Foo2 = type { i8, %struct.Foo }
+%struct.Foo = type { i8 }
+
+; Function Attrs: mustprogress noinline nounwind optnone uwtable
+define dso_local void @_Z7fooFuncv() #0 !dbg !10 {
+entry:
+  %global2 = alloca %struct.Foo2, align 1
+  call void @llvm.dbg.declare(metadata ptr %global2, metadata !14, metadata 
!DIExpression()), !dbg !23
+  ret void, !dbg !24
+}
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn 
memory(none)
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
+
+attributes #0 = { mustprogress noinline nounwind optnone uwtable 
"frame-pointer"="all" "min-legal-vector-width"="0" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-cpu"="x86-64" 
"target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
+attributes #1 = { nocallback nofree nosync nounwind speculatable willreturn 
memory(none) }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3, !4, !5, !6, !7, !8}
+!llvm.ident = !{!9}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, 
producer: "clang version 18.0.0git", isOptimized: false, runtimeVersion: 0, 
emissionKind: FullDebug, splitDebugInlining: false)
+!1 = !DIFile(filename: "main.cpp", directory: "/smallMultipleTUs", 
checksumkind: CSK_MD5, checksum: "70bff4d50322126f3d8ca4178afad376")
+!2 = !{i32 7, !"Dwarf Version", i32 5}
+!3 = !{i32 2, !"Debug Info Version", i32 3}
+!4 = !{i32 1, !"wchar_size", i32 4}
+!5 = !{i32 8, !"PIC Level", i32 2}
+!6 = !{i32 7, !"PIE Level", i32 2}
+!7 = !{i32 7, !"uwtable", i32 2}
+!8 = !{i32 7, !"frame-pointer", i32 2}
+!9 = !{!"clang version 18.0.0git"}
+!10 = distinct !DISubprogram(name: "fooFunc", linkageName: "_Z7fooFuncv", 
scope: !1, file: !1, line: 9, type: !11, scopeLine: 9, flags: DIFlagPrototyped, 
spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !13)
+!11 = !DISubroutineType(types: !12)
+!12 = !{null}
+!13 = !{}
+!14 = !DILocalVariable(name: "global2", scope: !10, file: !1, line: 10, type: 
!15)
+!15 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Foo2", 
file: !1, line: 4, size: 16, flags: DIFlagTypePassByValue, elements: !16, 
identifier: "_ZTS4Foo2")
+!16 = !{!17, !19}
+!17 = !DIDerivedType(tag: DW_TAG_member, name: "f", scope: !15, file: !1, 
line: 5, baseType: !18, size: 8)
+!18 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!19 = !DIDerivedType(tag: DW_TAG_member, name: "f1", scope: !15, file: !1, 
line: 6, baseType: !20, size: 8, offset: 8)
+!20 = distinct 

[clang] [clang][Interp] Diagnose reads from non-const global variables (PR #71919)

2024-01-12 Thread Aaron Ballman via cfe-commits

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


[clang] [clang][Interp] Diagnose reads from non-const global variables (PR #71919)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -1005,12 +1008,23 @@ bool SetThisField(InterpState , CodePtr OpPC, 
uint32_t I) {
 template ::T>
 bool GetGlobal(InterpState , CodePtr OpPC, uint32_t I) {
   const Block *B = S.P.getGlobal(I);
+
+  if (!CheckConstant(S, OpPC, B->getDescriptor()))
+return false;
   if (B->isExtern())
 return false;
   S.Stk.push(B->deref());
   return true;
 }
 
+/// Same as GetGlobal, but without the checks.
+template ::T>
+bool GetGlobalUnchecked(InterpState , CodePtr OpPC, uint32_t I) {
+  auto *B = S.P.getGlobal(I);
+  S.Stk.push(B->deref());
+  return true;
+}
+

AaronBallman wrote:

Eh probably not worth it then.

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


[clang] [clang][Interp] Diagnose reads from non-const global variables (PR #71919)

2024-01-12 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-01-12 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 124efcaa973306ce42633cea07ed3cf55d63afde 
bbc6c11cd3def5acbb2ba2f2ddc45df2c399f9d6 -- 
clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c 
clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c 
clang/include/clang/Sema/Sema.h clang/lib/CodeGen/Targets/AArch64.cpp 
clang/lib/Sema/SemaChecking.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 0fed60103c..2ff1fcb01c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13803,13 +13803,12 @@ public:
 FormatArgumentPassingKind ArgPassingKind;
   };
 
-enum ArmStreamingType {
-  ArmNonStreaming,
-  ArmStreaming,
-  ArmStreamingCompatible,
-  ArmStreamingOrSVE2p1
-};
-
+  enum ArmStreamingType {
+ArmNonStreaming,
+ArmStreaming,
+ArmStreamingCompatible,
+ArmStreamingOrSVE2p1
+  };
 
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index ea3d5a9760..43555f577f 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -822,14 +822,18 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
 void AArch64TargetCodeGenInfo::checkFunctionCallABI(
 CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
 const FunctionDecl *Callee, const CallArgList ) const {
-if (!Callee->hasAttr())
-  return;
+  if (!Callee->hasAttr())
+return;
 
-auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
-auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+  auto CalleeIsStreaming =
+  Sema::getArmStreamingFnType(Callee) == Sema::ArmStreaming;
+  auto CallerIsStreaming =
+  Sema::getArmStreamingFnType(Caller) == Sema::ArmStreaming;
 
-if (CalleeIsStreaming && !CallerIsStreaming)
-CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+  if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc,
+  diag::err_function_alwaysinline_attribute_mismatch)
+<< Caller->getDeclName() << Callee->getDeclName() << "streaming";
 }
 
 std::unique_ptr

``




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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,844 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent
+out-of-bounds (OOB) memory accesses, which remain a major source of security
+vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs
+by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can
+use to attach bounds to pointers. For example, programmers can add the
+``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer
+has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every
+pointer dereference, ensuring that the program does not access memory outside
+the specified bounds. The compiler requires programmers to provide enough 
bounds
+information so that the accesses can be checked at either run time or compile
+time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the
+programmer’s annotation burden by reconciling bounds annotations at ABI
+boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that
+carry bounds information on local variables without the need for annotations. 
We
+designed this model so that it preserves ABI compatibility with C while
+minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of
+production C code and proven to work in a consumer operating system setting. 
The
+extension was designed to enable incremental adoption — a key requirement in
+real-world settings where modifying an entire project and its dependencies all
+at once is often not possible. It also addresses multiple of other practical
+challenges that have made existing approaches to safer C dialects difficult to
+adopt, offering these properties that make it widely adoptable in practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety
+  benefits.
+* It is a conforming extension to C.
+* Consequently, source code that adopts the extension can continue to be
+  compiled by toolchains that do not support the extension (CAVEAT: this still
+  requires inclusion of a header file micro-defining bounds annotations to
+  empty).
+* It has a relatively low adoption cost.
+
+This document discusses the key designs of ``-fbounds-safety``. The document is
+subject to be actively updated with a more detailed specification. The
+implementation plan can be found in Implementation plans for -fbounds-safety.
+
+.. Cross reference doesn't currently work

AaronBallman wrote:

No, you should be able to land both at the same time with the correct 
references I believe.

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2024-01-12 Thread Aaron Ballman via cfe-commits

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

Thank you for the updates; the changes LGTM!

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2024-01-12 Thread Aaron Ballman via cfe-commits

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


[clang] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-01-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-aarch64

Author: Sam Tebbs (SamTebbs33)


Changes

This patch adds an error that is emitted when a streaming function is marked as 
always_inline and is called from a non-streaming function.

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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+2) 
- (modified) clang/include/clang/Sema/Sema.h (+9) 
- (modified) clang/lib/CodeGen/CMakeLists.txt (+1) 
- (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+20) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+10-17) 
- (added) clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c 
(+12) 
- (added) clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c (+12) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 568000106a84dc..dbd92b600a936e 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -279,6 +279,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def err_function_alwaysinline_attribute_mismatch : Error<
+  "always_inline function %1 and its caller %0 have mismatched %2 attributes">;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4c464a1ae4c67f..0fed60103c9a2c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13803,8 +13803,17 @@ class Sema final {
 FormatArgumentPassingKind ArgPassingKind;
   };
 
+enum ArmStreamingType {
+  ArmNonStreaming,
+  ArmStreaming,
+  ArmStreamingCompatible,
+  ArmStreamingOrSVE2p1
+};
+
+
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
+  static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
 
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 52216d93a302bb..03a6f2f1d7a9d2 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -151,4 +151,5 @@ add_clang_library(clangCodeGen
   clangFrontend
   clangLex
   clangSerialization
+  clangSema
   )
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 7102d190fe008b..ea3d5a97605f1c 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -8,6 +8,8 @@
 
 #include "ABIInfoImpl.h"
 #include "TargetInfo.h"
+#include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Sema/Sema.h"
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -153,6 +155,11 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 }
 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
   }
+
+  void checkFunctionCallABI(CodeGenModule , SourceLocation CallLoc,
+const FunctionDecl *Caller,
+const FunctionDecl *Callee,
+const CallArgList ) const override;
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
@@ -812,6 +819,19 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList ) const {
+if (!Callee->hasAttr())
+  return;
+
+auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
+auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+
+if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+}
+
 std::unique_ptr
 CodeGen::createAArch64TargetCodeGenInfo(CodeGenModule ,
 AArch64ABIKind Kind) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 74f8f626fb1637..160637dde448e4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2998,13 +2998,6 @@ static QualType getNeonEltType(NeonTypeFlags Flags, 
ASTContext ,
   llvm_unreachable("Invalid NeonTypeFlag!");
 }
 
-enum ArmStreamingType {
-  ArmNonStreaming,
-  ArmStreaming,
-  ArmStreamingCompatible,
-  ArmStreamingOrSVE2p1
-};
-
 bool 

[clang] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-01-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sam Tebbs (SamTebbs33)


Changes

This patch adds an error that is emitted when a streaming function is marked as 
always_inline and is called from a non-streaming function.

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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+2) 
- (modified) clang/include/clang/Sema/Sema.h (+9) 
- (modified) clang/lib/CodeGen/CMakeLists.txt (+1) 
- (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+20) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+10-17) 
- (added) clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c 
(+12) 
- (added) clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c (+12) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 568000106a84dc..dbd92b600a936e 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -279,6 +279,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def err_function_alwaysinline_attribute_mismatch : Error<
+  "always_inline function %1 and its caller %0 have mismatched %2 attributes">;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4c464a1ae4c67f..0fed60103c9a2c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13803,8 +13803,17 @@ class Sema final {
 FormatArgumentPassingKind ArgPassingKind;
   };
 
+enum ArmStreamingType {
+  ArmNonStreaming,
+  ArmStreaming,
+  ArmStreamingCompatible,
+  ArmStreamingOrSVE2p1
+};
+
+
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
+  static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
 
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 52216d93a302bb..03a6f2f1d7a9d2 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -151,4 +151,5 @@ add_clang_library(clangCodeGen
   clangFrontend
   clangLex
   clangSerialization
+  clangSema
   )
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 7102d190fe008b..ea3d5a97605f1c 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -8,6 +8,8 @@
 
 #include "ABIInfoImpl.h"
 #include "TargetInfo.h"
+#include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Sema/Sema.h"
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -153,6 +155,11 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 }
 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
   }
+
+  void checkFunctionCallABI(CodeGenModule , SourceLocation CallLoc,
+const FunctionDecl *Caller,
+const FunctionDecl *Callee,
+const CallArgList ) const override;
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
@@ -812,6 +819,19 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList ) const {
+if (!Callee->hasAttr())
+  return;
+
+auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
+auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+
+if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+}
+
 std::unique_ptr
 CodeGen::createAArch64TargetCodeGenInfo(CodeGenModule ,
 AArch64ABIKind Kind) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 74f8f626fb1637..160637dde448e4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2998,13 +2998,6 @@ static QualType getNeonEltType(NeonTypeFlags Flags, 
ASTContext ,
   llvm_unreachable("Invalid NeonTypeFlag!");
 }
 
-enum ArmStreamingType {
-  ArmNonStreaming,
-  ArmStreaming,
-  ArmStreamingCompatible,
-  ArmStreamingOrSVE2p1
-};
-
 bool Sema::ParseSVEImmChecks(
 

[clang] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-01-12 Thread Sam Tebbs via cfe-commits

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


[clang] [Clang][SME] Detect always_inline used with mismatched streaming attibutes (PR #77936)

2024-01-12 Thread Sam Tebbs via cfe-commits

https://github.com/SamTebbs33 created 
https://github.com/llvm/llvm-project/pull/77936

This patch adds an error that is emitted when a streaming function is marked as 
always_inline and is called from a non-streaming function.

>From bbc6c11cd3def5acbb2ba2f2ddc45df2c399f9d6 Mon Sep 17 00:00:00 2001
From: Samuel Tebbs 
Date: Wed, 10 Jan 2024 14:57:04 +
Subject: [PATCH] [Clang][SME] Detect always_inline used with mismatched
 streaming attributes

This patch adds an error that is emitted when a streaming function is
marked as always_inline and is called from a non-streaming function.
---
 .../clang/Basic/DiagnosticFrontendKinds.td|  2 ++
 clang/include/clang/Sema/Sema.h   |  9 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 clang/lib/CodeGen/Targets/AArch64.cpp | 20 ++
 clang/lib/Sema/SemaChecking.cpp   | 27 +++
 ...-sme-func-attrs-inline-locally-streaming.c | 12 +
 .../aarch64-sme-func-attrs-inline-streaming.c | 12 +
 7 files changed, 66 insertions(+), 17 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c
 create mode 100644 clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 568000106a84dc..dbd92b600a936e 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -279,6 +279,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def err_function_alwaysinline_attribute_mismatch : Error<
+  "always_inline function %1 and its caller %0 have mismatched %2 attributes">;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4c464a1ae4c67f..0fed60103c9a2c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13803,8 +13803,17 @@ class Sema final {
 FormatArgumentPassingKind ArgPassingKind;
   };
 
+enum ArmStreamingType {
+  ArmNonStreaming,
+  ArmStreaming,
+  ArmStreamingCompatible,
+  ArmStreamingOrSVE2p1
+};
+
+
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
+  static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
 
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 52216d93a302bb..03a6f2f1d7a9d2 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -151,4 +151,5 @@ add_clang_library(clangCodeGen
   clangFrontend
   clangLex
   clangSerialization
+  clangSema
   )
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 7102d190fe008b..ea3d5a97605f1c 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -8,6 +8,8 @@
 
 #include "ABIInfoImpl.h"
 #include "TargetInfo.h"
+#include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Sema/Sema.h"
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -153,6 +155,11 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 }
 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
   }
+
+  void checkFunctionCallABI(CodeGenModule , SourceLocation CallLoc,
+const FunctionDecl *Caller,
+const FunctionDecl *Callee,
+const CallArgList ) const override;
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
@@ -812,6 +819,19 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList ) const {
+if (!Callee->hasAttr())
+  return;
+
+auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
+auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+
+if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+}
+
 std::unique_ptr
 CodeGen::createAArch64TargetCodeGenInfo(CodeGenModule ,
 AArch64ABIKind Kind) {
diff --git 

[clang] [llvm] [X86] Use vXi1 for `k` constraint in inline asm (PR #77733)

2024-01-12 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

> Should we add test coverage for the gpr <-> mask transfers?

Is the concern about existing BC files using gpr? It's covered by existing test 
case, e.g., function `@a` in pr41678.ll
We don't remove the iN type support in X86ISelLowering.cpp, but add extra vXi1 
support.

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


[clang] [llvm] [lld] [libcxx] [openmp] [mlir] [libc++] Deprecate the _LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS macro (PR #77692)

2024-01-12 Thread Louis Dionne via cfe-commits

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


[clang] [flang] [lld] [llvm] [AMDGPU] Introduce GFX9/10.1/10.3/11 Generic Targets (PR #76955)

2024-01-12 Thread Pierre van Houtryve via cfe-commits


@@ -520,6 +520,106 @@ Every processor supports every OS ABI (see 
:ref:`amdgpu-os`) with the following
 
  === ===  = = 
=== === ==
 
+Generic processors also exist. They group multiple processors into one,
+allowing to build code once and run it on multiple targets at the cost
+of less features being available.
+
+Generic processors are only available on Code Object V6 and up.
+
+  .. table:: AMDGPU Generic Processors
+ :name: amdgpu-generic-processor-table
+
+  == = 
=
+ Processor TargetSupported Target
+   TripleProcessorsFeatures
+   ArchitectureRestrictions
+
+
+
+
+
+
+
+
+  == = 
=
+ ``gfx9-generic`` ``amdgcn`` - ``gfx900``  - ``v_mad_mix`` 
instructions
+ - ``gfx902``are not available 
on
+ - ``gfx904````gfx900``, 
``gfx902``,
+ - ``gfx906````gfx909``, 
``gfx90c``
+ - ``gfx909``  - ``v_fma_mix`` 
instructions
+ - ``gfx90c``are not available 
on ``gfx904``
+   - sramecc is not 
available on
+ ``gfx906``
+   - The following 
instructions
+ are not available 
on ``gfx906``:
+
+ - ``v_fmac_f32``
+ - ``v_xnor_b32``
+ - 
``v_dot4_i32_i8``
+ - 
``v_dot8_i32_i4``
+ - 
``v_dot2_i32_i16``
+ - 
``v_dot2_u32_u16``
+ - 
``v_dot4_u32_u8``
+ - 
``v_dot8_u32_u4``
+ - 
``v_dot2_f32_f16``
+
+
+ ``gfx10.1-generic``  ``amdgcn`` - ``gfx1010`` - The following 
instructions are
+ - ``gfx1011``   not available on 
``gfx1011``
+ - ``gfx1012``   and ``gfx1012``
+ - ``gfx1013``
+ - 
``v_dot4_i32_i8``

Pierre-vh wrote:

gfx1010 and gfx1012 are indeed not identical, but gfx1011 and gfx1012 are:
```
def FeatureISAVersion10_1_0 : FeatureSet<
  !listconcat(FeatureISAVersion10_1_Common.Features,
[])>;

def FeatureISAVersion10_1_2 : FeatureSet<
  !listconcat(FeatureISAVersion10_1_Common.Features,
[FeatureDot1Insts,
 FeatureDot2Insts,
 FeatureDot5Insts,
 FeatureDot6Insts,
 FeatureDot7Insts,
 FeatureDot10Insts])>;
```



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


[clang] [flang] [lld] [llvm] [AMDGPU] Introduce GFX9/10.1/10.3/11 Generic Targets (PR #76955)

2024-01-12 Thread Pierre van Houtryve via cfe-commits


@@ -520,6 +520,106 @@ Every processor supports every OS ABI (see 
:ref:`amdgpu-os`) with the following
 
  === ===  = = 
=== === ==
 
+Generic processors also exist. They group multiple processors into one,
+allowing to build code once and run it on multiple targets at the cost
+of less features being available.
+
+Generic processors are only available on Code Object V6 and up.
+
+  .. table:: AMDGPU Generic Processors
+ :name: amdgpu-generic-processor-table
+
+  == = 
=
+ Processor TargetSupported Target
+   TripleProcessorsFeatures
+   ArchitectureRestrictions
+
+
+
+
+
+
+
+
+  == = 
=
+ ``gfx9-generic`` ``amdgcn`` - ``gfx900``  - ``v_mad_mix`` 
instructions
+ - ``gfx902``are not available 
on
+ - ``gfx904````gfx900``, 
``gfx902``,
+ - ``gfx906````gfx909``, 
``gfx90c``
+ - ``gfx909``  - ``v_fma_mix`` 
instructions
+ - ``gfx90c``are not available 
on ``gfx904``
+   - sramecc is not 
available on
+ ``gfx906``
+   - The following 
instructions
+ are not available 
on ``gfx906``:
+
+ - ``v_fmac_f32``
+ - ``v_xnor_b32``
+ - 
``v_dot4_i32_i8``
+ - 
``v_dot8_i32_i4``
+ - 
``v_dot2_i32_i16``
+ - 
``v_dot2_u32_u16``
+ - 
``v_dot4_u32_u8``
+ - 
``v_dot8_u32_u4``
+ - 
``v_dot2_f32_f16``
+
+
+ ``gfx10.1-generic``  ``amdgcn`` - ``gfx1010`` - The following 
instructions are
+ - ``gfx1011``   not available on 
``gfx1011``
+ - ``gfx1012``   and ``gfx1012``
+ - ``gfx1013``
+ - 
``v_dot4_i32_i8``
+ - 
``v_dot8_i32_i4``
+ - 
``v_dot2_i32_i16``
+ - 
``v_dot2_u32_u16``
+ - 
``v_dot2c_f32_f16``
+ - 
``v_dot4c_i32_i8``
+ - 
``v_dot4_u32_u8``
+ - 
``v_dot8_u32_u4``
+ - 
``v_dot2_f32_f16``
+
+   - BVH Ray Tracing 
instructions
+ are not available 
on
+ ``gfx1013``
+
+
+ ``gfx10.3-generic``  ``amdgcn`` - ``gfx1030`` No restrictions.
+ - ``gfx1031``
+ - ``gfx1032``
+ - ``gfx1033``
+ - ``gfx1034``
+ - ``gfx1035``
+ - ``gfx1036``

Pierre-vh wrote:

It's not a target in LLVM so no

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


[llvm] [clang] [X86] Use vXi1 for `k` constraint in inline asm (PR #77733)

2024-01-12 Thread Simon Pilgrim via cfe-commits

https://github.com/RKSimon commented:

Should we add test coverage for the gpr <-> mask transfers?

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Phoebe Wang via cfe-commits

https://github.com/phoebewang updated 
https://github.com/llvm/llvm-project/pull/77925

>From cc0f2b24299bdfc9216ee87ab1aba08707f95503 Mon Sep 17 00:00:00 2001
From: Phoebe Wang 
Date: Fri, 12 Jan 2024 21:29:50 +0800
Subject: [PATCH 1/2] [AVX10][Doc] Add documentation about AVX10 options and
 their attentions

---
 clang/docs/UsersManual.rst | 54 ++
 1 file changed, 54 insertions(+)

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 7c30570437e8b0..cbefa2cf0e9497 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and do not use traditional AVX512 options anymore.
+
+The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
+from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
+enable all instructions within AVX10 version N at a maximum vector length of
+256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
+length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
+
+Current binaries built with AVX512 features can run on Intel AVX10/512 capable
+processor without re-compile, but cannot run on AVX10/256 capable processor.
+Users need to re-compile their code with ``-mavx10.N``, and maybe update some
+code that calling to 512-bit X86 specific intrinsics and passing or returning
+512-bit vector types in function call, if they want to run on AVX10/256 capable
+processor. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
+AVX10/512 capable processor.
+
+Users can add a ``-mno-evex512`` in the command line with AVX512 options if
+they want run the binary on both legacy AVX512 processor and new AVX10/256
+capable processor. The option has the same constraints as ``-mavx10.N``, i.e.,
+cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit 
vector
+types in function call.
+
+Users should avoid to use AVX512 features in function target attributes when
+develop code for AVX10. If they have to do so, they need to add an explicit
+``evex512`` or ``no-evex512`` together with AVX512 features for 512-bit or
+non-512-bit functions respectively to avoid unexpected code generation. Both
+command line option and target attribute of EVEX512 feature can only be used
+with AVX512. They don't affect vector size of AVX10.
+
+User should not mix use AVX10 and AVX512 options together in any time, because
+the option combinations are conflicting sometimes. For example, a combination
+of ``-mavx512f -mavx10.1-256`` doesn't show a clear intention to compiler, 
since
+instructions in AVX512F and AVX10.1/256 intersect but do not overlap. In this
+case, compiler will emit warning for it, but the behavior is determined. It
+will generate the same code as option ``-mavx10.1-512``. A similar case is
+``-mavx512f -mavx10.2-256``, which equals to ``-mavx10.1-512 -mavx10.2-256``,
+because ``avx10.2-256`` implies ``avx10.1-256`` and ``-mavx512f -mavx10.1-256``
+equals to ``-mavx10.1-512``.
+
+There are some new macros introduced with AVX10 support. ``-mavx10.1-256`` will
+enable ``__AVX10_1__`` and ``__EVEX256__``, while ``-mavx10.1-512`` enables
+``__AVX10_1__``, ``__EVEX256__``, ``__EVEX512__``  and ``__AVX10_1_512__``.
+Besides, both ``-mavx10.1-256`` and ``-mavx10.1-512`` will enable all AVX512
+feature specific macros. A AVX512 feature will enable both ``__EVEX256__``,
+``__EVEX512__`` and its own macro. So ``__EVEX512__`` can be used to guard code
+that can run on both legacy AVX512 and AVX10/512 capable processor but cannot
+run on AVX10/256, while a AVX512 macro like ``__AVX512F__`` cannot tell the
+difference among the three options. Users need to check additional macros
+``__AVX10_1__`` and ``__EVEX512__`` if they want to make distinction.
+
 ARM
 ^^^
 

>From 485095d9befbb21cad1d980e4bca7fa58ee28e67 Mon Sep 17 00:00:00 2001
From: Phoebe Wang 
Date: Fri, 12 Jan 2024 22:40:04 +0800
Subject: [PATCH 2/2] Address review comments

---
 clang/docs/UsersManual.rst | 30 +++---
 1 file changed, 15 insertions(+), 15 deletions(-)

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index cbefa2cf0e9497..02aad64c4dd08b 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3967,7 +3967,7 @@ implicitly included in later levels.
 a major new vector ISA incorporating the modern vectorization aspects of
 Intel AVX-512. This ISA will be supported on 

[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

@owenca, @HazardyKnusperkeks could you please take another look and approve if 
this looks good to you?
I believe all comments should be addressed at this point.

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


[clang] 7700ea1 - [OpenACC] Implement the 'rest' of the simple 'var-list' clauses

2024-01-12 Thread via cfe-commits

Author: erichkeane
Date: 2024-01-12T06:14:48-08:00
New Revision: 7700ea103187ba6e547deb501ca4a1402e8a23fd

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

LOG: [OpenACC] Implement the 'rest' of the simple 'var-list' clauses

A large number of clauses are simple, required parens with a var-list.
This patch adds them all, as adding them is quite trivial.

Added: 


Modified: 
clang/include/clang/Basic/OpenACCKinds.h
clang/lib/Parse/ParseOpenACC.cpp
clang/test/ParserOpenACC/parse-clauses.c

Removed: 




diff  --git a/clang/include/clang/Basic/OpenACCKinds.h 
b/clang/include/clang/Basic/OpenACCKinds.h
index cb775ba0d92873..e860893b933ca3 100644
--- a/clang/include/clang/Basic/OpenACCKinds.h
+++ b/clang/include/clang/Basic/OpenACCKinds.h
@@ -103,6 +103,37 @@ enum class OpenACCClauseKind {
   Copy,
   /// 'use_device' clause, allowed on 'host_data' construct.
   UseDevice,
+  /// 'attach' clause, allowed on Compute and Combined constructs, plus 'data'
+  /// and 'enter data'.
+  Attach,
+  /// 'delete' clause, allowed on the 'exit data' construct.
+  Delete,
+  /// 'detach' clause, allowed on the 'exit data' construct.
+  Detach,
+  /// 'device' clause, allowed on the 'update' construct.
+  Device,
+  /// 'deviceptr' clause, allowed on Compute and Combined Constructs, plus
+  /// 'data' and 'declare'.
+  DevicePtr,
+  /// 'device_resident' clause, allowed on the 'declare' construct.
+  DeviceResident,
+  /// 'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop',
+  /// and 'serial loop' constructs.
+  FirstPrivate,
+  /// 'host' clause, allowed on 'update' construct.
+  Host,
+  /// 'link' clause, allowed on 'declare' construct.
+  Link,
+  /// 'no_create' clause, allowed on allowed on Compute and Combined 
constructs,
+  /// plus 'data'.
+  NoCreate,
+  /// 'present' clause, allowed on Compute and Combined constructs, plus 'data'
+  /// and 'declare'.
+  Present,
+  /// 'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel
+  /// loop', and 'serial loop' constructs.
+  Private,
+
   /// Represents an invalid clause, for the purposes of parsing.
   Invalid,
 };

diff  --git a/clang/lib/Parse/ParseOpenACC.cpp 
b/clang/lib/Parse/ParseOpenACC.cpp
index c94f48d3ec04f0..83378a094492b2 100644
--- a/clang/lib/Parse/ParseOpenACC.cpp
+++ b/clang/lib/Parse/ParseOpenACC.cpp
@@ -87,16 +87,29 @@ OpenACCClauseKind getOpenACCClauseKind(Token Tok) {
   if (!Tok.is(tok::identifier))
 return OpenACCClauseKind::Invalid;
 
+  // TODO: ERICH: add new clauses here.
   return llvm::StringSwitch(
  Tok.getIdentifierInfo()->getName())
+.Case("attach",OpenACCClauseKind::Attach)
   .Case("auto", OpenACCClauseKind::Auto)
   .Case("copy", OpenACCClauseKind::Copy)
   .Case("default", OpenACCClauseKind::Default)
+  .Case("delete", OpenACCClauseKind::Delete)
+  .Case("detach", OpenACCClauseKind::Detach)
+  .Case("device", OpenACCClauseKind::Device)
+  .Case("device_resident", OpenACCClauseKind::DeviceResident)
+  .Case("deviceptr", OpenACCClauseKind::DevicePtr)
   .Case("finalize", OpenACCClauseKind::Finalize)
+  .Case("firstprivate", OpenACCClauseKind::FirstPrivate)
+  .Case("host", OpenACCClauseKind::Host)
   .Case("if", OpenACCClauseKind::If)
   .Case("if_present", OpenACCClauseKind::IfPresent)
   .Case("independent", OpenACCClauseKind::Independent)
+  .Case("link", OpenACCClauseKind::Link)
+  .Case("no_create", OpenACCClauseKind::NoCreate)
   .Case("nohost", OpenACCClauseKind::NoHost)
+  .Case("present", OpenACCClauseKind::Present)
+  .Case("private", OpenACCClauseKind::Private)
   .Case("self", OpenACCClauseKind::Self)
   .Case("seq", OpenACCClauseKind::Seq)
   .Case("use_device", OpenACCClauseKind::UseDevice)
@@ -331,14 +344,55 @@ OpenACCDirectiveKind ParseOpenACCDirectiveKind(Parser ) 
{
   return DirKind;
 }
 
+enum ClauseParensKind {
+  None,
+  Optional,
+  Required
+};
+
+ClauseParensKind getClauseParensKind(OpenACCClauseKind Kind) {
+  switch (Kind) {
+  case OpenACCClauseKind::Self:
+return ClauseParensKind::Optional;
+
+  case OpenACCClauseKind::Default:
+  case OpenACCClauseKind::If:
+  case OpenACCClauseKind::Copy:
+  case OpenACCClauseKind::UseDevice:
+  case OpenACCClauseKind::NoCreate:
+  case OpenACCClauseKind::Present:
+  case OpenACCClauseKind::DevicePtr:
+  case OpenACCClauseKind::Attach:
+  case OpenACCClauseKind::Detach:
+  case OpenACCClauseKind::Private:
+  case OpenACCClauseKind::FirstPrivate:
+  case OpenACCClauseKind::Delete:
+  case OpenACCClauseKind::DeviceResident:
+  case OpenACCClauseKind::Device:
+  case OpenACCClauseKind::Link:
+  case OpenACCClauseKind::Host:
+return ClauseParensKind::Required;
+
+  case 

[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-12 Thread Ilya Biryukov via cfe-commits


@@ -1698,8 +1698,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   /*BasedOnStyle=*/"google",
   },
   };
-  GoogleStyle.AttributeMacros.push_back("GUARDED_BY");

ilya-biryukov wrote:

I think we should postpone the inclusion of those names into `AtrributeMacros`  
and land the patch as is.

It seems that there is agreement among everyone that having this formatting 
without explicit `AtrributeMacros` is desirable, so landing as is is a 
no-brainer.

Whether we should add common macro names into `AttributeMacros` is more 
contentious, so I think we may need more data to back up our decision to go 
either way. I have some examples where not having those names in the config 
leads to undesirable formatting, but I would share them in a follow-up 
conversation.

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


[clang] [Clang][Sema] improve sema check of clang::musttail attribute (PR #77727)

2024-01-12 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

Just needs a release note, else LGTM.

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


[clang] [llvm] [Clang] Make sdot builtins available to SME (PR #77792)

2024-01-12 Thread Kerry McLaughlin via cfe-commits

https://github.com/kmclaughlin-arm approved this pull request.

LGTM!

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


[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-12 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov updated 
https://github.com/llvm/llvm-project/pull/76804

>From d8598a382fb1496a96d6ff8317c06cf73606ad84 Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Wed, 3 Jan 2024 11:07:17 +0100
Subject: [PATCH 1/4] [Format] Fix isStartOfName to recognize attributes

This addresses a problem with formatting attributes in a different way
as before. For some context:
- 199fc973ced20016b04ba540cf63a1d4914fa513 changed `isStartOfName` to
  fix problems inside macro directives (judging by the added tests), but
  this behavior changed formatting of attribute macros in an undesirable
  way.
- efeb546865c233dfa7706ee0316c676de9f69897 changed Google format style
  to fix some widely used attributes.

Instead of changing the format style, this commit specializes behavior
introduced in 199fc973ced20016b04ba540cf63a1d4914fa513 to macro
directives. This seems to work well in both cases.

Also update the test with two `GUARDED_BY` directives. While the
formatting after efeb546865c233dfa7706ee0316c676de9f69897 seems better,
this case is rare enough to not warrant the extra complexity. We are
reverting it back to the state it had before
efeb546865c233dfa7706ee0316c676de9f69897.
---
 clang/lib/Format/Format.cpp | 2 --
 clang/lib/Format/TokenAnnotator.cpp | 3 ++-
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index f798d555bf9929..38974f578fe1d2 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1698,8 +1698,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   /*BasedOnStyle=*/"google",
   },
   };
-  GoogleStyle.AttributeMacros.push_back("GUARDED_BY");
-  GoogleStyle.AttributeMacros.push_back("ABSL_GUARDED_BY");
 
   GoogleStyle.SpacesBeforeTrailingComments = 2;
   GoogleStyle.Standard = FormatStyle::LS_Auto;
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ac3aa3c5e3a22..94fe5b21cfc6e6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2209,7 +2209,8 @@ class AnnotatingParser {
 (!NextNonComment && !Line.InMacroBody) ||
 (NextNonComment &&
  (NextNonComment->isPointerOrReference() ||
-  NextNonComment->isOneOf(tok::identifier, tok::string_literal {
+  (Line.InPragmaDirective &&
+   NextNonComment->isOneOf(tok::identifier, tok::string_literal) {
   return false;
 }
 

>From 6ba6f35e97af2299bbd5364fd535f31962a7eb4c Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Wed, 3 Jan 2024 11:22:26 +0100
Subject: [PATCH 2/4] Update tests

---
 clang/unittests/Format/FormatTest.cpp | 7 ++-
 1 file changed, 2 insertions(+), 5 deletions(-)

diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 881993ede17c3d..fbbeddc29cfb5f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8498,9 +8498,6 @@ TEST_F(FormatTest, 
BreaksFunctionDeclarationsWithTrailingTokens) {
"__attribute__((unused));");
 
   Style = getGoogleStyle();
-  ASSERT_THAT(Style.AttributeMacros,
-  testing::AllOf(testing::Contains("GUARDED_BY"),
- testing::Contains("ABSL_GUARDED_BY")));
 
   verifyFormat(
   "bool 
a\n"
@@ -10093,11 +10090,11 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
getGoogleStyleWithColumns(40));
   verifyFormat("Tttt ppp\n"
"ABSL_GUARDED_BY(mutex1)\n"
-   "ABSL_GUARDED_BY(mutex2);",
+   "ABSL_GUARDED_BY(mutex2);",
getGoogleStyleWithColumns(40));
   verifyFormat("Tt f(int a, int b)\n"
"ABSL_GUARDED_BY(mutex1)\n"
-   "ABSL_GUARDED_BY(mutex2);",
+   "ABSL_GUARDED_BY(mutex2);",
getGoogleStyleWithColumns(40));
   // * typedefs
   verifyGoogleFormat("typedef ATTR(X) char x;");

>From be3b337199fdc71718872e56aed19d89fa4447a1 Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Fri, 12 Jan 2024 15:28:56 +0100
Subject: [PATCH 3/4] Update clang/lib/Format/TokenAnnotator.cpp

Co-authored-by: Owen Pan 
---
 clang/lib/Format/TokenAnnotator.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 94fe5b21cfc6e6..7d030db45243a9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2209,8 +2209,8 @@ class AnnotatingParser {
 (!NextNonComment && !Line.InMacroBody) ||
 (NextNonComment &&
  (NextNonComment->isPointerOrReference() ||
-  (Line.InPragmaDirective &&
-   NextNonComment->isOneOf(tok::identifier, tok::string_literal) {
+  

[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-12 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov updated 
https://github.com/llvm/llvm-project/pull/76804

>From d8598a382fb1496a96d6ff8317c06cf73606ad84 Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Wed, 3 Jan 2024 11:07:17 +0100
Subject: [PATCH 1/3] [Format] Fix isStartOfName to recognize attributes

This addresses a problem with formatting attributes in a different way
as before. For some context:
- 199fc973ced20016b04ba540cf63a1d4914fa513 changed `isStartOfName` to
  fix problems inside macro directives (judging by the added tests), but
  this behavior changed formatting of attribute macros in an undesirable
  way.
- efeb546865c233dfa7706ee0316c676de9f69897 changed Google format style
  to fix some widely used attributes.

Instead of changing the format style, this commit specializes behavior
introduced in 199fc973ced20016b04ba540cf63a1d4914fa513 to macro
directives. This seems to work well in both cases.

Also update the test with two `GUARDED_BY` directives. While the
formatting after efeb546865c233dfa7706ee0316c676de9f69897 seems better,
this case is rare enough to not warrant the extra complexity. We are
reverting it back to the state it had before
efeb546865c233dfa7706ee0316c676de9f69897.
---
 clang/lib/Format/Format.cpp | 2 --
 clang/lib/Format/TokenAnnotator.cpp | 3 ++-
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index f798d555bf9929..38974f578fe1d2 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1698,8 +1698,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   /*BasedOnStyle=*/"google",
   },
   };
-  GoogleStyle.AttributeMacros.push_back("GUARDED_BY");
-  GoogleStyle.AttributeMacros.push_back("ABSL_GUARDED_BY");
 
   GoogleStyle.SpacesBeforeTrailingComments = 2;
   GoogleStyle.Standard = FormatStyle::LS_Auto;
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ac3aa3c5e3a22..94fe5b21cfc6e6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2209,7 +2209,8 @@ class AnnotatingParser {
 (!NextNonComment && !Line.InMacroBody) ||
 (NextNonComment &&
  (NextNonComment->isPointerOrReference() ||
-  NextNonComment->isOneOf(tok::identifier, tok::string_literal {
+  (Line.InPragmaDirective &&
+   NextNonComment->isOneOf(tok::identifier, tok::string_literal) {
   return false;
 }
 

>From 6ba6f35e97af2299bbd5364fd535f31962a7eb4c Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Wed, 3 Jan 2024 11:22:26 +0100
Subject: [PATCH 2/3] Update tests

---
 clang/unittests/Format/FormatTest.cpp | 7 ++-
 1 file changed, 2 insertions(+), 5 deletions(-)

diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 881993ede17c3d..fbbeddc29cfb5f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8498,9 +8498,6 @@ TEST_F(FormatTest, 
BreaksFunctionDeclarationsWithTrailingTokens) {
"__attribute__((unused));");
 
   Style = getGoogleStyle();
-  ASSERT_THAT(Style.AttributeMacros,
-  testing::AllOf(testing::Contains("GUARDED_BY"),
- testing::Contains("ABSL_GUARDED_BY")));
 
   verifyFormat(
   "bool 
a\n"
@@ -10093,11 +10090,11 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
getGoogleStyleWithColumns(40));
   verifyFormat("Tttt ppp\n"
"ABSL_GUARDED_BY(mutex1)\n"
-   "ABSL_GUARDED_BY(mutex2);",
+   "ABSL_GUARDED_BY(mutex2);",
getGoogleStyleWithColumns(40));
   verifyFormat("Tt f(int a, int b)\n"
"ABSL_GUARDED_BY(mutex1)\n"
-   "ABSL_GUARDED_BY(mutex2);",
+   "ABSL_GUARDED_BY(mutex2);",
getGoogleStyleWithColumns(40));
   // * typedefs
   verifyGoogleFormat("typedef ATTR(X) char x;");

>From be3b337199fdc71718872e56aed19d89fa4447a1 Mon Sep 17 00:00:00 2001
From: Ilya Biryukov 
Date: Fri, 12 Jan 2024 15:28:56 +0100
Subject: [PATCH 3/3] Update clang/lib/Format/TokenAnnotator.cpp

Co-authored-by: Owen Pan 
---
 clang/lib/Format/TokenAnnotator.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 94fe5b21cfc6e6..7d030db45243a9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2209,8 +2209,8 @@ class AnnotatingParser {
 (!NextNonComment && !Line.InMacroBody) ||
 (NextNonComment &&
  (NextNonComment->isPointerOrReference() ||
-  (Line.InPragmaDirective &&
-   NextNonComment->isOneOf(tok::identifier, tok::string_literal) {
+  

[flang] [clang] [flang][Driver] Support -pthread in the frontend (PR #77360)

2024-01-12 Thread Kareem Ergawy via cfe-commits

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


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


[flang] [clang] [flang][Driver] Support -pthread in the frontend (PR #77360)

2024-01-12 Thread Leandro Lupori via cfe-commits

luporl wrote:

> Could someone test this on AArch64 and/or Windows just to make sure that it 
> passes there?

Works fine on AArch64.


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


[clang] [clang][Interp] Implement IntegralAP::{div, rem} (PR #72614)

2024-01-12 Thread Aaron Ballman via cfe-commits


@@ -44,6 +44,24 @@ static_assert(MulA * MulB == 50, ""); // ref-error {{not an 
integral constant ex
 static_assert(MulA * 5 == 25, "");
 static_assert(-1 * MulB == -7, "");
 
+
+constexpr _BitInt(4) DivA = 2;
+constexpr _BitInt(2) DivB = 1;
+static_assert(DivA / DivB == 2, "");
+
+constexpr _BitInt(4) DivC = DivA / 0; // ref-error {{must be initialized by a 
constant expression}} \

AaronBallman wrote:

Ah, thank you!

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


[clang] [clang][Interp] Implement IntegralAP::{div, rem} (PR #72614)

2024-01-12 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [clang][Interp] Implement IntegralAP::{div, rem} (PR #72614)

2024-01-12 Thread Aaron Ballman via cfe-commits

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and do not use traditional AVX512 options anymore.
+
+The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
+from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
+enable all instructions within AVX10 version N at a maximum vector length of
+256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
+length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
+
+Current binaries built with AVX512 features can run on Intel AVX10/512 capable
+processor without re-compile, but cannot run on AVX10/256 capable processor.
+Users need to re-compile their code with ``-mavx10.N``, and maybe update some
+code that calling to 512-bit X86 specific intrinsics and passing or returning
+512-bit vector types in function call, if they want to run on AVX10/256 capable
+processor. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
+AVX10/512 capable processor.
+
+Users can add a ``-mno-evex512`` in the command line with AVX512 options if
+they want run the binary on both legacy AVX512 processor and new AVX10/256

RKSimon wrote:

"they want to run"
processor -> processors

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and do not use traditional AVX512 options anymore.
+
+The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
+from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
+enable all instructions within AVX10 version N at a maximum vector length of
+256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
+length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
+
+Current binaries built with AVX512 features can run on Intel AVX10/512 capable
+processor without re-compile, but cannot run on AVX10/256 capable processor.
+Users need to re-compile their code with ``-mavx10.N``, and maybe update some
+code that calling to 512-bit X86 specific intrinsics and passing or returning
+512-bit vector types in function call, if they want to run on AVX10/256 capable
+processor. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
+AVX10/512 capable processor.
+
+Users can add a ``-mno-evex512`` in the command line with AVX512 options if
+they want run the binary on both legacy AVX512 processor and new AVX10/256
+capable processor. The option has the same constraints as ``-mavx10.N``, i.e.,
+cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit 
vector
+types in function call.
+
+Users should avoid to use AVX512 features in function target attributes when
+develop code for AVX10. If they have to do so, they need to add an explicit

RKSimon wrote:

"Users should avoid using AVX512 features in function target attributes when 
developing code for AVX10."

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and do not use traditional AVX512 options anymore.
+
+The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
+from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
+enable all instructions within AVX10 version N at a maximum vector length of
+256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
+length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
+
+Current binaries built with AVX512 features can run on Intel AVX10/512 capable
+processor without re-compile, but cannot run on AVX10/256 capable processor.
+Users need to re-compile their code with ``-mavx10.N``, and maybe update some
+code that calling to 512-bit X86 specific intrinsics and passing or returning
+512-bit vector types in function call, if they want to run on AVX10/256 capable
+processor. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
+AVX10/512 capable processor.
+
+Users can add a ``-mno-evex512`` in the command line with AVX512 options if
+they want run the binary on both legacy AVX512 processor and new AVX10/256
+capable processor. The option has the same constraints as ``-mavx10.N``, i.e.,
+cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit 
vector
+types in function call.
+
+Users should avoid to use AVX512 features in function target attributes when
+develop code for AVX10. If they have to do so, they need to add an explicit
+``evex512`` or ``no-evex512`` together with AVX512 features for 512-bit or
+non-512-bit functions respectively to avoid unexpected code generation. Both
+command line option and target attribute of EVEX512 feature can only be used
+with AVX512. They don't affect vector size of AVX10.
+
+User should not mix use AVX10 and AVX512 options together in any time, because

RKSimon wrote:

"Users should not mix the use AVX10 and AVX512 options together at any time,"

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits


@@ -3963,6 +3963,60 @@ implicitly included in later levels.
 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, 
LZCNT, MOVBE, XSAVE
 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
 
+`Intel AVX10 ISA `_ is
+a major new vector ISA incorporating the modern vectorization aspects of
+Intel AVX-512. This ISA will be supported on all future Intel processor.
+Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
+on these processors and do not use traditional AVX512 options anymore.

RKSimon wrote:

"and should not use"

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits

https://github.com/RKSimon commented:

A few minors

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


[clang] [AVX10][Doc] Add documentation about AVX10 options and their attentions (PR #77925)

2024-01-12 Thread Simon Pilgrim via cfe-commits

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

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


[clang] 460ff58 - [clang] Reapply Handle templated operators with reversed arguments (#72213)

2024-01-12 Thread via cfe-commits

Author: Utkarsh Saxena
Date: 2024-01-12T15:03:01+01:00
New Revision: 460ff58f62456a1f3ccf61ec9cf9d10781bd41bb

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

LOG: [clang] Reapply Handle templated operators with reversed arguments (#72213)

Re-applies https://github.com/llvm/llvm-project/pull/69595 with extra
[diff](https://github.com/llvm/llvm-project/pull/72213/commits/79181efd0d7aef1b8396d44cdf40c0dfa4054984)
### New changes

Further relax ambiguities with a warning for member operators of a
template class (primary templates of such ops do not match). Eg:
```cpp
template 
struct S {
template 
bool operator==(const OtherT ); 
};
struct A : S {};
struct B : S {};
bool x = A{} == B{}; // accepted with a warning.
```

This is important for making llvm build using previous clang versions in
C++20 mode (eg: this makes the commit
e558be51bab051d1471d92e967f8a2aecc13567a keep working with a warning
instead of an error).

### Description from https://github.com/llvm/llvm-project/pull/69595

https://github.com/llvm/llvm-project/pull/68999 correctly computed
conversion sequence for reversed args to a template operator. This was a
breaking change as code, previously accepted in C++17, starts to break
in C++20.

Example:
```cpp
struct P {};
template bool operator==(const P&, const S &);

struct A : public P {};
struct B : public P {};
bool check(A a, B b) { return a == b; }  // This is now ambiguous in C++20.
```

In order to minimise widespread breakages, as a clang extension, we had
previously accepted such ambiguities with a warning
(`-Wambiguous-reversed-operator`) for non-template operators. Due to the
same reasons, we extend this relaxation for template operators.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaOverload.cpp
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 10e426a30d98f9..3cbce1be159437 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,29 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17.
+  Clang did not properly diagnose such casese in C++20 before this change. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+// This equality is now ambiguous in C++20.
+bool ambiguous(A a, B b) { return a == b; }
+
+template bool operator!=(const P&, const S&);
+// Ok. Found a matching operator!=.
+bool fine(A a, B b) { return a == b; }
+
+  To reduce such widespread breakages, as an extension, Clang accepts this code
+  with an existing warning ``-Wambiguous-reversed-operator`` warning.
+  Fixes `GH `_.
+
 - The CMake variable ``GCC_INSTALL_PREFIX`` (which sets the default
   ``--gcc-toolchain=``) is deprecated and will be removed. Specify
   ``--gcc-install-dir=`` or ``--gcc-triple=`` in a `configuration file

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 64bc3851980272..23b9bc0fe2d6e2 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7723,9 +7723,19 @@ bool Sema::CheckNonDependentConversions(
++I) {
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
-  unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
- : (ThisConversions + I);
+  unsigned ConvIdx;
+  if (PO == OverloadCandidateParamOrder::Reversed) {
+ConvIdx = Args.size() - 1 - I;
+assert(Args.size() + ThisConversions == 2 &&
+   "number of args (including 'this') must be exactly 2 for "
+   "reversed order");
+// For members, there would be only one arg 'Args[0]' whose ConvIdx
+// would also be 0. 'this' got ConvIdx = 1 previously.
+assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
+  } else {
+// For members, 'this' got ConvIdx = 0 previously.
+ConvIdx = ThisConversions + I;
+  }
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
 SuppressUserConversions,
@@ -10121,11 +10131,23 @@ getImplicitObjectParamType(ASTContext , const 
FunctionDecl *F) {
   return 

[clang] 4556813 - [Sema] Use lexical DC for friend functions when getting constraint instantiation args (#77552)

2024-01-12 Thread via cfe-commits

Author: antangelo
Date: 2024-01-12T09:02:01-05:00
New Revision: 45568135cbb31bb3b345a8355134970742248120

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

LOG: [Sema] Use lexical DC for friend functions when getting constraint 
instantiation args (#77552)

Fixes a crash where the template argument depth computed in the semantic
context for a friend FunctionDecl with a constrained parameter is
compared against arguments in the lexical context for the purpose of
checking if the constraint depends on enclosing template parameters.

Since getTemplateInstantiationArgs in this case follows the semantic DC
for friend FunctionDecls, the resulting depth is incorrect and trips an
assertion.

Fixes #75426

Added: 
clang/test/SemaTemplate/GH75426.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplateInstantiate.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4aba054e252af2..10e426a30d98f9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -723,6 +723,10 @@ Bug Fixes in This Version
 - Clang now emits correct source location for code-coverage regions in `if 
constexpr`
   and `if consteval` branches.
   Fixes (`#54419 `_)
+- Fix assertion failure when declaring a template friend function with
+  a constrained parameter in a template class that declares a class method
+  or lambda at 
diff erent depth.
+  Fixes (`#75426 `_)
 - Fix an issue where clang cannot find conversion function with template
   parameter when instantiation of template class.
   Fixes (`#77583 `_)

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 7f20413c104e97..fc80515b45e35b 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -223,6 +223,9 @@ Response HandleFunction(const FunctionDecl *Function,
   (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
 return Response::ChangeDecl(Function->getLexicalDeclContext());
   }
+
+  if (ForConstraintInstantiation && Function->getFriendObjectKind())
+return Response::ChangeDecl(Function->getLexicalDeclContext());
   return Response::UseNextDecl(Function);
 }
 

diff  --git a/clang/test/SemaTemplate/GH75426.cpp 
b/clang/test/SemaTemplate/GH75426.cpp
new file mode 100644
index 00..faf70699f9c5f0
--- /dev/null
+++ b/clang/test/SemaTemplate/GH75426.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+template concept C = true;
+
+struct A {
+template void f();
+};
+
+auto L = []{};
+
+template
+class Friends {
+template friend void A::f();
+template friend void decltype(L)::operator()();
+};



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


[compiler-rt] [libc] [clang] [clang-tools-extra] [libunwind] [llvm] [libcxx] [lldb] [lld] [libcxxabi] [flang] [Sema] Use lexical DC for friend functions when getting constraint instantiation args (PR

2024-01-12 Thread via cfe-commits

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/72213

>From b0183f23ffad814080e82c725ee4cb7902aea23f Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 12 Jan 2024 13:38:15 +
Subject: [PATCH 1/4] rebase

---
 clang/docs/ReleaseNotes.rst   | 21 +++
 clang/lib/Sema/SemaOverload.cpp   | 28 ++---
 .../over.match.oper/p3-2a.cpp | 61 +++
 3 files changed, 100 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4aba054e252af2..8453b72b8b5d12 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,27 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+// This equality is now ambiguous in C++20.
+bool ambiguous(A a, B b) { return a == b; }
+
+template bool operator!=(const P&, const S&);
+// Ok. Found a matching operator!=.
+bool fine(A a, B b) { return a == b; }
+
+  To reduce such widespread breakages, as an extension, Clang accepts this code
+  with an existing warning ``-Wambiguous-reversed-operator`` warning.
+  Fixes `GH `_.
 - The CMake variable ``GCC_INSTALL_PREFIX`` (which sets the default
   ``--gcc-toolchain=``) is deprecated and will be removed. Specify
   ``--gcc-install-dir=`` or ``--gcc-triple=`` in a `configuration file
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 64bc3851980272..a440a3b7b6a9e0 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7724,7 +7724,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)
  : (ThisConversions + I);
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
@@ -10121,11 +10121,19 @@ getImplicitObjectParamType(ASTContext , const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext , const FunctionDecl *F1,
-   const FunctionDecl *F2) {
+// As a Clang extension, allow ambiguity among F1 and F2 if they represent
+// represent the same entity.
+static bool allowAmbiguity(ASTContext , const FunctionDecl *F1,
+   const FunctionDecl *F2) {
   if (declaresSameEntity(F1, F2))
 return true;
-
+  if (F1->isTemplateInstantiation() && F2->isTemplateInstantiation() &&
+  declaresSameEntity(F1->getPrimaryTemplate(), F2->getPrimaryTemplate())) {
+return true;
+  }
+  // TODO: It is not clear whether comparing parameters is necessary (i.e.
+  // different functions with same params). Consider removing this (as no test
+  // fail w/o it).
   auto NextParam = [&](const FunctionDecl *F, unsigned , bool First) {
 if (First) {
   if (std::optional T = getImplicitObjectParamType(Context, F))
@@ -10329,14 +10337,14 @@ bool clang::isBetterOverloadCandidate(
 case ImplicitConversionSequence::Worse:
   if (Cand1.Function && Cand2.Function &&
   Cand1.isReversed() != Cand2.isReversed() &&
-  haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function)) {
+  allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
 // Work around large-scale breakage caused by considering reversed
 // forms of operator== in C++20:
 //
-// When comparing a function against a reversed function with the same
-// parameter types, if we have a better conversion for one argument and
-// a worse conversion for the other, the implicit conversion sequences
-// are treated as being equally good.
+// When comparing a function against a reversed function, if we have a
+// better conversion for one argument and a worse conversion for the
+// other, the implicit conversion sequences are treated as being 
equally
+// good.
 //
 // This prevents a comparison function from being considered ambiguous
 // with a reversed form that is written in the same way.
@@ -14526,7 +14534,7 @@ ExprResult Sema::CreateOverloadedBinOp(SourceLocation 
OpLoc,
   llvm::SmallVector AmbiguousWith;
   for (OverloadCandidate  : CandidateSet) {
 if (Cand.Viable && 

[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits


@@ -10088,9 +10088,13 @@ static bool allowAmbiguity(ASTContext , const 
FunctionDecl *F1,
const FunctionDecl *F2) {
   if (declaresSameEntity(F1, F2))
 return true;
-  if (F1->isTemplateInstantiation() && F2->isTemplateInstantiation() &&
-  declaresSameEntity(F1->getPrimaryTemplate(), F2->getPrimaryTemplate())) {
-return true;
+  if (F1->isTemplateInstantiation() && F2->isTemplateInstantiation()) {
+auto PT1 = F1->getPrimaryTemplate();
+auto PT2 = F2->getPrimaryTemplate();
+if (declaresSameEntity(PT1, PT2) ||

usx95 wrote:

Added test

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/72213

>From b0183f23ffad814080e82c725ee4cb7902aea23f Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 12 Jan 2024 13:38:15 +
Subject: [PATCH 1/2] rebase

---
 clang/docs/ReleaseNotes.rst   | 21 +++
 clang/lib/Sema/SemaOverload.cpp   | 28 ++---
 .../over.match.oper/p3-2a.cpp | 61 +++
 3 files changed, 100 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4aba054e252af2..8453b72b8b5d12 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,27 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+// This equality is now ambiguous in C++20.
+bool ambiguous(A a, B b) { return a == b; }
+
+template bool operator!=(const P&, const S&);
+// Ok. Found a matching operator!=.
+bool fine(A a, B b) { return a == b; }
+
+  To reduce such widespread breakages, as an extension, Clang accepts this code
+  with an existing warning ``-Wambiguous-reversed-operator`` warning.
+  Fixes `GH `_.
 - The CMake variable ``GCC_INSTALL_PREFIX`` (which sets the default
   ``--gcc-toolchain=``) is deprecated and will be removed. Specify
   ``--gcc-install-dir=`` or ``--gcc-triple=`` in a `configuration file
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 64bc3851980272..a440a3b7b6a9e0 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7724,7 +7724,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)
  : (ThisConversions + I);
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
@@ -10121,11 +10121,19 @@ getImplicitObjectParamType(ASTContext , const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext , const FunctionDecl *F1,
-   const FunctionDecl *F2) {
+// As a Clang extension, allow ambiguity among F1 and F2 if they represent
+// represent the same entity.
+static bool allowAmbiguity(ASTContext , const FunctionDecl *F1,
+   const FunctionDecl *F2) {
   if (declaresSameEntity(F1, F2))
 return true;
-
+  if (F1->isTemplateInstantiation() && F2->isTemplateInstantiation() &&
+  declaresSameEntity(F1->getPrimaryTemplate(), F2->getPrimaryTemplate())) {
+return true;
+  }
+  // TODO: It is not clear whether comparing parameters is necessary (i.e.
+  // different functions with same params). Consider removing this (as no test
+  // fail w/o it).
   auto NextParam = [&](const FunctionDecl *F, unsigned , bool First) {
 if (First) {
   if (std::optional T = getImplicitObjectParamType(Context, F))
@@ -10329,14 +10337,14 @@ bool clang::isBetterOverloadCandidate(
 case ImplicitConversionSequence::Worse:
   if (Cand1.Function && Cand2.Function &&
   Cand1.isReversed() != Cand2.isReversed() &&
-  haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function)) {
+  allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
 // Work around large-scale breakage caused by considering reversed
 // forms of operator== in C++20:
 //
-// When comparing a function against a reversed function with the same
-// parameter types, if we have a better conversion for one argument and
-// a worse conversion for the other, the implicit conversion sequences
-// are treated as being equally good.
+// When comparing a function against a reversed function, if we have a
+// better conversion for one argument and a worse conversion for the
+// other, the implicit conversion sequences are treated as being 
equally
+// good.
 //
 // This prevents a comparison function from being considered ambiguous
 // with a reversed form that is written in the same way.
@@ -14526,7 +14534,7 @@ ExprResult Sema::CreateOverloadedBinOp(SourceLocation 
OpLoc,
   llvm::SmallVector AmbiguousWith;
   for (OverloadCandidate  : CandidateSet) {
 if (Cand.Viable && 

[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

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


[clang] [clang] Reapply Handle templated operators with reversed arguments (PR #72213)

2024-01-12 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/72213

>From b0183f23ffad814080e82c725ee4cb7902aea23f Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 12 Jan 2024 13:38:15 +
Subject: [PATCH] rebase

---
 clang/docs/ReleaseNotes.rst   | 21 +++
 clang/lib/Sema/SemaOverload.cpp   | 28 ++---
 .../over.match.oper/p3-2a.cpp | 61 +++
 3 files changed, 100 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4aba054e252af2..8453b72b8b5d12 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,27 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+// This equality is now ambiguous in C++20.
+bool ambiguous(A a, B b) { return a == b; }
+
+template bool operator!=(const P&, const S&);
+// Ok. Found a matching operator!=.
+bool fine(A a, B b) { return a == b; }
+
+  To reduce such widespread breakages, as an extension, Clang accepts this code
+  with an existing warning ``-Wambiguous-reversed-operator`` warning.
+  Fixes `GH `_.
 - The CMake variable ``GCC_INSTALL_PREFIX`` (which sets the default
   ``--gcc-toolchain=``) is deprecated and will be removed. Specify
   ``--gcc-install-dir=`` or ``--gcc-triple=`` in a `configuration file
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 64bc3851980272..a440a3b7b6a9e0 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7724,7 +7724,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)
  : (ThisConversions + I);
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
@@ -10121,11 +10121,19 @@ getImplicitObjectParamType(ASTContext , const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext , const FunctionDecl *F1,
-   const FunctionDecl *F2) {
+// As a Clang extension, allow ambiguity among F1 and F2 if they represent
+// represent the same entity.
+static bool allowAmbiguity(ASTContext , const FunctionDecl *F1,
+   const FunctionDecl *F2) {
   if (declaresSameEntity(F1, F2))
 return true;
-
+  if (F1->isTemplateInstantiation() && F2->isTemplateInstantiation() &&
+  declaresSameEntity(F1->getPrimaryTemplate(), F2->getPrimaryTemplate())) {
+return true;
+  }
+  // TODO: It is not clear whether comparing parameters is necessary (i.e.
+  // different functions with same params). Consider removing this (as no test
+  // fail w/o it).
   auto NextParam = [&](const FunctionDecl *F, unsigned , bool First) {
 if (First) {
   if (std::optional T = getImplicitObjectParamType(Context, F))
@@ -10329,14 +10337,14 @@ bool clang::isBetterOverloadCandidate(
 case ImplicitConversionSequence::Worse:
   if (Cand1.Function && Cand2.Function &&
   Cand1.isReversed() != Cand2.isReversed() &&
-  haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function)) {
+  allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
 // Work around large-scale breakage caused by considering reversed
 // forms of operator== in C++20:
 //
-// When comparing a function against a reversed function with the same
-// parameter types, if we have a better conversion for one argument and
-// a worse conversion for the other, the implicit conversion sequences
-// are treated as being equally good.
+// When comparing a function against a reversed function, if we have a
+// better conversion for one argument and a worse conversion for the
+// other, the implicit conversion sequences are treated as being 
equally
+// good.
 //
 // This prevents a comparison function from being considered ambiguous
 // with a reversed form that is written in the same way.
@@ -14526,7 +14534,7 @@ ExprResult Sema::CreateOverloadedBinOp(SourceLocation 
OpLoc,
   llvm::SmallVector AmbiguousWith;
   for (OverloadCandidate  : CandidateSet) {
 if (Cand.Viable && 

<    1   2   3   4   5   >