[clang] [llvm] [PowerPC] frontend get target feature from backend with cpu name (PR #137670)

2025-06-03 Thread zhijian lin via cfe-commits

https://github.com/diggerlin updated 
https://github.com/llvm/llvm-project/pull/137670

>From 97f10e6a0fb4c158359e79e24650f8fdf4d23ef2 Mon Sep 17 00:00:00 2001
From: zhijian 
Date: Fri, 25 Apr 2025 13:09:47 +
Subject: [PATCH 1/8] implement getting target features from backend for clang
 frontend

---
 clang/lib/Basic/Targets/PPC.cpp   | 150 +-
 .../cxx11-thread-local-reference.cpp  |   2 +-
 .../Driver/aix-shared-lib-tls-model-opt.c |   7 +-
 .../Driver/aix-small-local-exec-dynamic-tls.c |  15 +-
 clang/test/Driver/ppc-crbits.cpp  |   4 -
 clang/test/Driver/ppc-isa-features.cpp|  22 +--
 llvm/include/llvm/MC/MCSubtargetInfo.h|  32 +++-
 .../llvm/TargetParser/PPCTargetParser.h   |   5 +
 llvm/lib/MC/MCSubtargetInfo.cpp   |  32 +++-
 llvm/lib/Target/PowerPC/PPC.td|   4 +-
 llvm/lib/TargetParser/CMakeLists.txt  |   8 +
 llvm/lib/TargetParser/PPCTargetParser.cpp |  26 +++
 llvm/utils/TableGen/SubtargetEmitter.cpp  |  52 --
 13 files changed, 159 insertions(+), 200 deletions(-)

diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index 425ad68bb9098..2a1024be1d537 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/MacroBuilder.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "llvm/TargetParser/PPCTargetParser.h"
+#include 
 
 using namespace clang;
 using namespace clang::targets;
@@ -516,130 +517,15 @@ static bool ppcUserFeaturesCheck(DiagnosticsEngine 
&Diags,
 bool PPCTargetInfo::initFeatureMap(
 llvm::StringMap &Features, DiagnosticsEngine &Diags, StringRef CPU,
 const std::vector &FeaturesVec) const {
-  Features["altivec"] = llvm::StringSwitch(CPU)
-.Case("7400", true)
-.Case("g4", true)
-.Case("7450", true)
-.Case("g4+", true)
-.Case("970", true)
-.Case("g5", true)
-.Case("pwr6", true)
-.Case("pwr7", true)
-.Case("pwr8", true)
-.Case("pwr9", true)
-.Case("ppc64", true)
-.Case("ppc64le", true)
-.Default(false);
-
-  Features["power9-vector"] = (CPU == "pwr9");
-  Features["crypto"] = llvm::StringSwitch(CPU)
-   .Case("ppc64le", true)
-   .Case("pwr9", true)
-   .Case("pwr8", true)
-   .Default(false);
-  Features["power8-vector"] = llvm::StringSwitch(CPU)
-  .Case("ppc64le", true)
-  .Case("pwr9", true)
-  .Case("pwr8", true)
-  .Default(false);
-  Features["bpermd"] = llvm::StringSwitch(CPU)
-   .Case("ppc64le", true)
-   .Case("pwr9", true)
-   .Case("pwr8", true)
-   .Case("pwr7", true)
-   .Default(false);
-  Features["extdiv"] = llvm::StringSwitch(CPU)
-   .Case("ppc64le", true)
-   .Case("pwr9", true)
-   .Case("pwr8", true)
-   .Case("pwr7", true)
-   .Default(false);
-  Features["direct-move"] = llvm::StringSwitch(CPU)
-.Case("ppc64le", true)
-.Case("pwr9", true)
-.Case("pwr8", true)
-.Default(false);
-  Features["crbits"] = llvm::StringSwitch(CPU)
-.Case("ppc64le", true)
-.Case("pwr9", true)
-.Case("pwr8", true)
-.Default(false);
-  Features["vsx"] = llvm::StringSwitch(CPU)
-.Case("ppc64le", true)
-.Case("pwr9", true)
-.Case("pwr8", true)
-.Case("pwr7", true)
-.Default(false);
-  Features["htm"] = llvm::StringSwitch(CPU)
-.Case("ppc64le", true)
-.Case("pwr9", true)
-.Case("pwr8", true)
-.Default(false);
-
-  // ROP Protect is off by default.
-  Features["rop-protect"] = false;
-  // Privileged instructions are off by default.
-  Features["privileged"] = false;
 
-  if (getTriple().isOSAIX()) {
-// The code generated by the -maix-small-local-[exec|dynamic]-tls option is
-// turned off by default.
-Features["aix-small-local-exec-tls"] = false;
-Features["aix-small-local-dyna

[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams updated 
https://github.com/llvm/llvm-project/pull/134647

>From 5c7ac16d5099b192f25f17ec58dbe89cb43a7bca Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Thu, 3 Apr 2025 19:46:01 +0100
Subject: [PATCH 1/4] [KeyInstr][Clang] For range stmt atoms

This patch is part of a stack that teaches Clang to generate Key Instructions
metadata for C and C++.

The Key Instructions project is introduced, including a "quick summary" section
at the top which adds context for this PR, here:
https://discourse.llvm.org/t/rfc-improving-is-stmt-placement-for-better-interactive-debugging/82668

The feature is only functional in LLVM if LLVM is built with CMake flag
LLVM_EXPERIMENTAL_KEY_INSTRUCTIONs. Eventually that flag will be removed.

The Clang-side work is demoed here:
https://github.com/llvm/llvm-project/pull/130943
---
 clang/lib/CodeGen/CGStmt.cpp  | 13 +++-
 .../DebugInfo/KeyInstructions/for-range.cpp   | 72 +++
 2 files changed, 84 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/DebugInfo/KeyInstructions/for-range.cpp

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 205a57cbab31a..9f9442b70f3b4 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,7 +1483,14 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  // Key Instructions: Emit the condition and branch as separate atoms to
+  // match existing loop stepping behaviour. FIXME: We could have the branch as
+  // the backup location for the condition, which would probably be a better
+  // experience.
+  if (auto *I = dyn_cast(BoolCondVal))
+addInstToNewSourceAtom(I, nullptr);
+  addInstToNewSourceAtom(I, nullptr);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1532,6 +1539,10 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
+
+  // We want the for closing brace to be step-able on to match existing
+  // behaviour. 
+  addInstToNewSourceAtom(ForBody->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
diff --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
new file mode 100644
index 0..be71d9fbfb581
--- /dev/null
+++ b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
@@ -0,0 +1,72 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang -gkey-instructions %s -gmlt -S -emit-llvm -o - \
+// RUN: | FileCheck %s --implicit-check-not atomGroup --implicit-check-not 
atomRank
+
+// Perennial quesiton: should the inc be its own source atom or not
+// (currently it is).
+
+// FIXME: See do.c and while.c regarding cmp and cond br groups.
+
+// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
+// marked as Key. Unclear whether that's desirable. Keep for now as that's
+// least risky.
+
+// Check the conditional branch (and the condition) in FOR_COND and
+// unconditional branch in FOR_BODY are Key Instructions.
+
+struct Range {
+int *begin();
+int *end();
+} r;
+
+// CHECK-LABEL: define dso_local void @_Z1av(
+// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
+// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
+// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
+// CHECK:   [[FOR_COND]]:
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
+// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[[FOR_END:.*]], !dbg [[DBG21:![0-9]+]]
+// CHECK:   [[FOR_BODY]]:
+// CHECK-

[clang] Introduce intra-procedural lifetime analysis in Clang (PR #142313)

2025-06-03 Thread Utkarsh Saxena via cfe-commits

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

>From 942648ef075407d2c7a8e19414d604e254d53064 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Mon, 2 Jun 2025 17:53:14 +
Subject: [PATCH] Introduce Intra-procedural lifetime analysis in Clang

---
 .../clang/Analysis/Analyses/LifetimeSafety.h  |  13 +
 clang/lib/Analysis/CMakeLists.txt |   1 +
 clang/lib/Analysis/LifetimeSafety.cpp | 721 ++
 clang/lib/Sema/AnalysisBasedWarnings.cpp  |   8 +
 .../test/Sema/lifetime-safety-testcase-gen.py |  79 ++
 .../Sema/warn-lifetime-safety-dataflow.cpp| 362 +
 6 files changed, 1184 insertions(+)
 create mode 100644 clang/include/clang/Analysis/Analyses/LifetimeSafety.h
 create mode 100644 clang/lib/Analysis/LifetimeSafety.cpp
 create mode 100644 clang/test/Sema/lifetime-safety-testcase-gen.py
 create mode 100644 clang/test/Sema/warn-lifetime-safety-dataflow.cpp

diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety.h 
b/clang/include/clang/Analysis/Analyses/LifetimeSafety.h
new file mode 100644
index 0..daf24fff72b9b
--- /dev/null
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety.h
@@ -0,0 +1,13 @@
+#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIME_SAFETY_H
+#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIME_SAFETY_H
+#include "clang/AST/DeclBase.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Analysis/CFG.h"
+namespace clang {
+
+void runLifetimeAnalysis(const DeclContext &DC, const CFG &Cfg,
+ AnalysisDeclContext &AC);
+
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIME_SAFETY_H
diff --git a/clang/lib/Analysis/CMakeLists.txt 
b/clang/lib/Analysis/CMakeLists.txt
index 8cd3990db4c3e..0523d92480cb3 100644
--- a/clang/lib/Analysis/CMakeLists.txt
+++ b/clang/lib/Analysis/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangAnalysis
   FixitUtil.cpp
   IntervalPartition.cpp
   IssueHash.cpp
+  LifetimeSafety.cpp
   LiveVariables.cpp
   MacroExpansionContext.cpp
   ObjCNoReturn.cpp
diff --git a/clang/lib/Analysis/LifetimeSafety.cpp 
b/clang/lib/Analysis/LifetimeSafety.cpp
new file mode 100644
index 0..9405ac453df3b
--- /dev/null
+++ b/clang/lib/Analysis/LifetimeSafety.cpp
@@ -0,0 +1,721 @@
+#include "clang/Analysis/Analyses/LifetimeSafety.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/StmtVisitor.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
+#include "llvm/ADT/ImmutableMap.h"
+#include "llvm/ADT/ImmutableSet.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Debug.h"
+#include 
+
+namespace clang {
+namespace {
+
+struct Point {
+  const clang::CFGBlock *Block;
+  /// Index into Block->Elements().
+  unsigned ElementIndex;
+
+  Point(const clang::CFGBlock *B = nullptr, unsigned Idx = 0)
+  : Block(B), ElementIndex(Idx) {}
+
+  bool operator==(const Point &Other) const {
+return Block == Other.Block && ElementIndex == Other.ElementIndex;
+  }
+};
+
+/// Represents the storage location being borrowed, e.g., a specific stack
+/// variable.
+/// TODO: Handle member accesseslike `s.y`.
+struct Path {
+  const clang::ValueDecl *D;
+
+  enum class Kind : uint8_t {
+StackVariable,
+Heap,// TODO: Handle.
+Field,   // TODO: Handle.
+ArrayElement,// TODO: Handle.
+TemporaryObject, // TODO: Handle.
+StaticOrGlobal,  // TODO: Handle.
+  };
+
+  Kind PathKind;
+
+  Path(const clang::ValueDecl *D, Kind K) : D(D), PathKind(K) {}
+};
+
+using LoanID = uint32_t;
+using OriginID = uint32_t;
+
+/// Information about a single borrow, or "Loan". A loan is created when a
+/// reference or pointer is taken.
+struct LoanInfo {
+  /// TODO: Represent opaque loans.
+  /// TODO: Represent nullptr: loans to no path. Accessing it UB! Currently it
+  /// is represented as empty LoanSet
+  LoanID ID;
+  Path SourcePath;
+  SourceLocation IssueLoc;
+
+  LoanInfo(LoanID id, Path path, SourceLocation loc)
+  : ID(id), SourcePath(path), IssueLoc(loc) {}
+};
+
+enum class OriginKind : uint8_t { Variable, ExpressionResult };
+
+/// An Origin is a symbolic identifier that represents the set of possible
+/// loans a pointer-like object could hold at any given time.
+/// TODO: Also represent Origins of complex types (fields, dependent internal
+/// types).
+struct OriginInfo {
+  OriginID ID;
+  OriginKind Kind;
+  union {
+const clang::ValueDecl *Decl;
+const clang::Expr *Expression;
+  };
+  OriginInfo(OriginID id, OriginKind kind, const clang::ValueDecl *D)
+  : ID(id), Kind(kind), Decl(D) {}
+  OriginInfo(OriginID id, OriginKind kind, const clang::Expr *E)
+  : ID(id), Kind(kind), Expression(E) {}
+};
+
+class LoanManager {
+public:
+  LoanManager() = default;
+
+  LoanInfo &addLo

[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Stephen Tozer via cfe-commits

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

LGTM with some nits.

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Stephen Tozer via cfe-commits


@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu  -gkey-instructions %s 
-debug-info-kind=line-tables-only -emit-llvm -o - \
+// RUN: | FileCheck %s
+
+// Perennial question: should the inc be its own source atom or not
+// (currently it is).
+
+// FIXME: See do.c and while.c regarding cmp and cond br groups.
+
+// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
+// marked as Key. Unclear whether that's desirable. Keep for now as that's
+// least risky (at worst it introduces an unecessary step while debugging,

SLTozer wrote:

```suggestion
// least risky (at worst it introduces an unnecessary step while debugging,
```

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Stephen Tozer via cfe-commits


@@ -1509,6 +1516,10 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 EmitStmt(S.getBody());
   }
 
+  // The last block in the loop's body (which unconditionally branches to 
theAdd commentMore actions
+  // `inc` block if there is one).

SLTozer wrote:

```suggestion
  // The last block in the loop's body (which unconditionally branches to the
  // `inc` block if there is one).
```

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Stephen Tozer via cfe-commits

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


[libclc] [llvm] [libclc] Support LLVM_ENABLE_RUNTIMES when building (PR #141574)

2025-06-03 Thread Fraser Cormack via cfe-commits


@@ -72,7 +72,7 @@ else()
   # Note that we check this later (for both build types) but we can provide a
   # more useful error message when built in-tree. We assume that LLVM tools are
   # always available so don't warn here.
-  if( NOT clang IN_LIST LLVM_ENABLE_PROJECTS )
+  if( NOT LLVM_RUNTIMES_BUILD AND NOT clang IN_LIST LLVM_ENABLE_PROJECTS )

frasercrmck wrote:

Thanks. Yes I suppose in the absence of a higher-level warning like you 
describe, we could probably use `USE_TOOLCHAIN` to accomplish the same thing in 
a runtimes build.

With any luck this is all temporary, and a runtimes build will allow us to just 
take the cmake c compiler.

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams updated 
https://github.com/llvm/llvm-project/pull/134647

>From 5c7ac16d5099b192f25f17ec58dbe89cb43a7bca Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Thu, 3 Apr 2025 19:46:01 +0100
Subject: [PATCH 1/5] [KeyInstr][Clang] For range stmt atoms

This patch is part of a stack that teaches Clang to generate Key Instructions
metadata for C and C++.

The Key Instructions project is introduced, including a "quick summary" section
at the top which adds context for this PR, here:
https://discourse.llvm.org/t/rfc-improving-is-stmt-placement-for-better-interactive-debugging/82668

The feature is only functional in LLVM if LLVM is built with CMake flag
LLVM_EXPERIMENTAL_KEY_INSTRUCTIONs. Eventually that flag will be removed.

The Clang-side work is demoed here:
https://github.com/llvm/llvm-project/pull/130943
---
 clang/lib/CodeGen/CGStmt.cpp  | 13 +++-
 .../DebugInfo/KeyInstructions/for-range.cpp   | 72 +++
 2 files changed, 84 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/DebugInfo/KeyInstructions/for-range.cpp

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 205a57cbab31a..9f9442b70f3b4 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,7 +1483,14 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  // Key Instructions: Emit the condition and branch as separate atoms to
+  // match existing loop stepping behaviour. FIXME: We could have the branch as
+  // the backup location for the condition, which would probably be a better
+  // experience.
+  if (auto *I = dyn_cast(BoolCondVal))
+addInstToNewSourceAtom(I, nullptr);
+  addInstToNewSourceAtom(I, nullptr);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1532,6 +1539,10 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
+
+  // We want the for closing brace to be step-able on to match existing
+  // behaviour. 
+  addInstToNewSourceAtom(ForBody->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
diff --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
new file mode 100644
index 0..be71d9fbfb581
--- /dev/null
+++ b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
@@ -0,0 +1,72 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang -gkey-instructions %s -gmlt -S -emit-llvm -o - \
+// RUN: | FileCheck %s --implicit-check-not atomGroup --implicit-check-not 
atomRank
+
+// Perennial quesiton: should the inc be its own source atom or not
+// (currently it is).
+
+// FIXME: See do.c and while.c regarding cmp and cond br groups.
+
+// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
+// marked as Key. Unclear whether that's desirable. Keep for now as that's
+// least risky.
+
+// Check the conditional branch (and the condition) in FOR_COND and
+// unconditional branch in FOR_BODY are Key Instructions.
+
+struct Range {
+int *begin();
+int *end();
+} r;
+
+// CHECK-LABEL: define dso_local void @_Z1av(
+// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
+// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
+// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
+// CHECK:   [[FOR_COND]]:
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
+// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[[FOR_END:.*]], !dbg [[DBG21:![0-9]+]]
+// CHECK:   [[FOR_BODY]]:
+// CHECK-

[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams updated 
https://github.com/llvm/llvm-project/pull/134647

>From 5c7ac16d5099b192f25f17ec58dbe89cb43a7bca Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Thu, 3 Apr 2025 19:46:01 +0100
Subject: [PATCH 1/6] [KeyInstr][Clang] For range stmt atoms

This patch is part of a stack that teaches Clang to generate Key Instructions
metadata for C and C++.

The Key Instructions project is introduced, including a "quick summary" section
at the top which adds context for this PR, here:
https://discourse.llvm.org/t/rfc-improving-is-stmt-placement-for-better-interactive-debugging/82668

The feature is only functional in LLVM if LLVM is built with CMake flag
LLVM_EXPERIMENTAL_KEY_INSTRUCTIONs. Eventually that flag will be removed.

The Clang-side work is demoed here:
https://github.com/llvm/llvm-project/pull/130943
---
 clang/lib/CodeGen/CGStmt.cpp  | 13 +++-
 .../DebugInfo/KeyInstructions/for-range.cpp   | 72 +++
 2 files changed, 84 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/DebugInfo/KeyInstructions/for-range.cpp

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 205a57cbab31a..9f9442b70f3b4 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,7 +1483,14 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
+  // Key Instructions: Emit the condition and branch as separate atoms to
+  // match existing loop stepping behaviour. FIXME: We could have the branch as
+  // the backup location for the condition, which would probably be a better
+  // experience.
+  if (auto *I = dyn_cast(BoolCondVal))
+addInstToNewSourceAtom(I, nullptr);
+  addInstToNewSourceAtom(I, nullptr);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1532,6 +1539,10 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
+
+  // We want the for closing brace to be step-able on to match existing
+  // behaviour. 
+  addInstToNewSourceAtom(ForBody->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
diff --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
new file mode 100644
index 0..be71d9fbfb581
--- /dev/null
+++ b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
@@ -0,0 +1,72 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang -gkey-instructions %s -gmlt -S -emit-llvm -o - \
+// RUN: | FileCheck %s --implicit-check-not atomGroup --implicit-check-not 
atomRank
+
+// Perennial quesiton: should the inc be its own source atom or not
+// (currently it is).
+
+// FIXME: See do.c and while.c regarding cmp and cond br groups.
+
+// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
+// marked as Key. Unclear whether that's desirable. Keep for now as that's
+// least risky.
+
+// Check the conditional branch (and the condition) in FOR_COND and
+// unconditional branch in FOR_BODY are Key Instructions.
+
+struct Range {
+int *begin();
+int *end();
+} r;
+
+// CHECK-LABEL: define dso_local void @_Z1av(
+// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
+// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
+// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
+// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
+// CHECK:   [[FOR_COND]]:
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
+// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
+// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[[FOR_END:.*]], !dbg [[DBG21:![0-9]+]]
+// CHECK:   [[FOR_BODY]]:
+// CHECK-

[clang] [clang][AST] Reduce some AST node size. (PR #142585)

2025-06-03 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/142585

>From 4b1cdc30ddb476d7e30519e5fe5ab6c298b59809 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Sat, 10 May 2025 07:44:51 +0200
Subject: [PATCH 1/4] [AST] Restructure the CXXForRanageStmt class to reduce
 the size, 96 -> 88

---
 clang/include/clang/AST/Expr.h| 9 +++--
 clang/include/clang/AST/Stmt.h| 4 +++-
 clang/include/clang/AST/StmtCXX.h | 2 +-
 clang/lib/AST/Expr.cpp| 7 ---
 4 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index a83320a7ddec2..5125d1a8349c1 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -2890,9 +2890,6 @@ class MatrixSubscriptExpr : public Expr {
 class CallExpr : public Expr {
   enum { FN = 0, PREARGS_START = 1 };
 
-  /// The number of arguments in the call expression.
-  unsigned NumArgs;
-
   /// The location of the right parentheses. This has a different meaning for
   /// the derived classes of CallExpr.
   SourceLocation RParenLoc;
@@ -3056,7 +3053,7 @@ class CallExpr : public Expr {
   }
 
   /// getNumArgs - Return the number of actual arguments to this call.
-  unsigned getNumArgs() const { return NumArgs; }
+  unsigned getNumArgs() const { return CallExprBits.NumArgs; }
 
   /// Retrieve the call arguments.
   Expr **getArgs() {
@@ -3104,13 +3101,13 @@ class CallExpr : public Expr {
   void shrinkNumArgs(unsigned NewNumArgs) {
 assert((NewNumArgs <= getNumArgs()) &&
"shrinkNumArgs cannot increase the number of arguments!");
-NumArgs = NewNumArgs;
+CallExprBits.NumArgs = NewNumArgs;
   }
 
   /// Bluntly set a new number of arguments without doing any checks 
whatsoever.
   /// Only used during construction of a CallExpr in a few places in Sema.
   /// FIXME: Find a way to remove it.
-  void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
+  void setNumArgsUnsafe(unsigned NewNumArgs) { CallExprBits.NumArgs = 
NewNumArgs; }
 
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index 336eb6d3df7e1..bea85271fbe92 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -572,8 +572,10 @@ class alignas(void *) Stmt {
 /// trailing objects belonging to CallExpr. Intentionally byte sized
 /// for faster access.
 unsigned OffsetToTrailingObjects : 8;
+
+unsigned NumArgs:20;
   };
-  enum { NumCallExprBits = 32 };
+  enum { NumCallExprBits = 52 };
 
   class MemberExprBitfields {
 friend class ASTStmtReader;
diff --git a/clang/include/clang/AST/StmtCXX.h 
b/clang/include/clang/AST/StmtCXX.h
index 8b4ef24ed376a..a15a445fbea40 100644
--- a/clang/include/clang/AST/StmtCXX.h
+++ b/clang/include/clang/AST/StmtCXX.h
@@ -133,11 +133,11 @@ class CXXTryStmt final : public Stmt,
 /// analysis of the constituent components. The original syntactic components
 /// can be extracted using getLoopVariable and getRangeInit.
 class CXXForRangeStmt : public Stmt {
-  SourceLocation ForLoc;
   enum { INIT, RANGE, BEGINSTMT, ENDSTMT, COND, INC, LOOPVAR, BODY, END };
   // SubExprs[RANGE] is an expression or declstmt.
   // SubExprs[COND] and SubExprs[INC] are expressions.
   Stmt *SubExprs[END];
+  SourceLocation ForLoc;
   SourceLocation CoawaitLoc;
   SourceLocation ColonLoc;
   SourceLocation RParenLoc;
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 59c0e47c7c195..2a659ef67144a 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -1460,7 +1460,7 @@ CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef PreArgs,
SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
unsigned MinNumArgs, ADLCallKind UsesADL)
 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
-  NumArgs = std::max(Args.size(), MinNumArgs);
+  CallExprBits.NumArgs = std::max(Args.size(), MinNumArgs);
   unsigned NumPreArgs = PreArgs.size();
   CallExprBits.NumPreArgs = NumPreArgs;
   assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
@@ -1477,7 +1477,7 @@ CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef PreArgs,
 setPreArg(I, PreArgs[I]);
   for (unsigned I = 0; I != Args.size(); ++I)
 setArg(I, Args[I]);
-  for (unsigned I = Args.size(); I != NumArgs; ++I)
+  for (unsigned I = Args.size(); I != CallExprBits.NumArgs; ++I)
 setArg(I, nullptr);
 
   this->computeDependence();
@@ -1490,7 +1490,8 @@ CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef PreArgs,
 
 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
bool HasFPFeatures, EmptyShell Empty)
-: Expr(SC, Empty), NumArgs(NumArgs) {
+: Expr(SC, Empty) {
+  CallExprBits.NumArgs = NumArgs;
   CallExprBits.NumPreArgs = NumPreArgs;
   assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
 


[clang] e29eb66 - [Clang] Slightly tweak the code to try to fix a potential codegen issue in #142592

2025-06-03 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2025-06-03T16:18:17+02:00
New Revision: e29eb6637d6b8ee54f746a9c914304f83309c4ee

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

LOG: [Clang] Slightly tweak the code to try to fix a potential codegen issue in 
#142592

Added: 


Modified: 
clang/include/clang/Lex/Preprocessor.h
clang/lib/Lex/PPExpressions.cpp
clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index cab398ad4a865..78be2bd64d61c 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -132,7 +132,7 @@ enum class EmbedResult {
 struct CXXStandardLibraryVersionInfo {
   enum Library { Unknown, LibStdCXX };
   Library Lib;
-  unsigned Version;
+  std::uint64_t Version;
 };
 
 /// Engages in a tight little dance with the lexer to efficiently
@@ -2717,8 +2717,8 @@ class Preprocessor {
   std::optional CXXStandardLibraryVersion;
 
 public:
-  std::optional getStdLibCxxVersion();
-  bool NeedsStdLibCxxWorkaroundBefore(unsigned FixedVersion);
+  std::optional getStdLibCxxVersion();
+  bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion);
 
 private:
   
//======//

diff  --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp
index 7b1dbb29b3b24..d18e56e7d478a 100644
--- a/clang/lib/Lex/PPExpressions.cpp
+++ b/clang/lib/Lex/PPExpressions.cpp
@@ -984,14 +984,9 @@ static std::optional
 getCXXStandardLibraryVersion(Preprocessor &PP, StringRef MacroName,
  CXXStandardLibraryVersionInfo::Library Lib) {
   MacroInfo *Macro = PP.getMacroInfo(PP.getIdentifierInfo(MacroName));
-  if (!Macro)
+  if (!Macro || Macro->getNumTokens() != 1 || !Macro->isObjectLike())
 return std::nullopt;
 
-  if (Macro->getNumTokens() != 1 || !Macro->isObjectLike()) {
-Macro->dump();
-return std::nullopt;
-  }
-
   const Token &RevisionDateTok = Macro->getReplacementToken(0);
 
   bool Invalid = false;
@@ -999,19 +994,16 @@ getCXXStandardLibraryVersion(Preprocessor &PP, StringRef 
MacroName,
   llvm::StringRef RevisionDate =
   PP.getSpelling(RevisionDateTok, Buffer, &Invalid);
   if (!Invalid) {
-llvm::errs() << RevisionDate << "\n";
-unsigned Value;
+std::uint64_t Value;
 // We don't use NumericParser to avoid diagnostics
-if (!RevisionDate.consumeInteger(10, Value)) {
-  llvm::errs() << "Value:" << Value << "\n";
+if (!RevisionDate.consumeInteger(10, Value))
   return CXXStandardLibraryVersionInfo{Lib, Value};
-}
   }
   return CXXStandardLibraryVersionInfo{CXXStandardLibraryVersionInfo::Unknown,
0};
 }
 
-std::optional Preprocessor::getStdLibCxxVersion() {
+std::optional Preprocessor::getStdLibCxxVersion() {
   if (!CXXStandardLibraryVersion)
 CXXStandardLibraryVersion = getCXXStandardLibraryVersion(
 *this, "__GLIBCXX__", CXXStandardLibraryVersionInfo::LibStdCXX);
@@ -1024,10 +1016,10 @@ std::optional 
Preprocessor::getStdLibCxxVersion() {
   return std::nullopt;
 }
 
-bool Preprocessor::NeedsStdLibCxxWorkaroundBefore(unsigned FixedVersion) {
+bool Preprocessor::NeedsStdLibCxxWorkaroundBefore(uint64_t FixedVersion) {
   assert(FixedVersion >= 2000'00'00 && FixedVersion <= 2100'00'00 &&
  "invalid value for __GLIBCXX__");
-  std::optional Ver = getStdLibCxxVersion();
+  std::optional Ver = getStdLibCxxVersion();
   if (!Ver)
 return false;
   return *Ver < FixedVersion;

diff  --git a/clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp 
b/clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
index 6b0adea930abf..6b8ca4f740914 100644
--- a/clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
+++ b/clang/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
@@ -7,15 +7,15 @@
 // The same problem afflicts a bunch of other class templates. Those
 // affected are array, pair, priority_queue, stack, and queue.
 
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-exceptions -Wextra -D__GLIBCXX__=2010L -DCLASS=array
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-exceptions -Wextra -D__GLIBCXX__=2010L -DCLASS=array -DPR28423
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-exceptions -Wextra -D__GLIBCXX__=2010L -DCLASS=pair
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-exceptions -Wextra -D__GLIBCXX__=2010L -DCLASS=priority_queue
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-exceptions -Wextra -D__GLIBCXX__=2010L -DCLASS=stack
-// RUN: %clang_cc1 -fsyntax-only %s -std=c++11 -verify -fexceptions 
-fcxx-e

[clang] d9df710 - [clang][Sema] Fix and reapply 'Declare builtins used in #pragma intrinsic #138205' (#142019)

2025-06-03 Thread via cfe-commits

Author: Nick Sarnie
Date: 2025-06-03T14:25:20Z
New Revision: d9df71045441e02d33cd01fad203862c7efd637e

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

LOG:  [clang][Sema] Fix and reapply 'Declare builtins used in #pragma intrinsic 
#138205' (#142019)

I had to revert https://github.com/llvm/llvm-project/pull/138205 in
https://github.com/llvm/llvm-project/pull/141994 because it broke the
Chrome build.

The problem came down to the following:

```c++
unsigned __int64 _umul128(unsigned __int64, unsigned __int64,
  unsigned __int64 *);

namespace {}
#pragma intrinsic(_umul128)

 void foo() {
   unsigned __int64 carry;
   unsigned __int64 low = _umul128(0, 0, &carry);
 }
```

When processing the `#pragma intrinsic` line, we do a name lookup to see
if the builtin was previously declared. In this case the lookup fails
because the current namespace of the parser and sema is the above
namespace scope. The processing of the pragma happens as part of the
namespace close parsing. This is usually fine because most pragmas don't
care about scopes. However, that's not true for this and other MS
pragmas.

To fix this, we change the `#pragma intrinsic` processing to be the same
as other MS pragmas such as "optimize". Those are processed like a
declaration, and because of that we have the correct current scope, so
the lookup succeeds.

I added a test case that locks down the Chrome fix, as well as manually
tested the Chrome build and confirmed it passed.

Added: 
clang/test/Sema/Inputs/builtin-system-header.h
clang/test/Sema/builtin-pragma-intrinsic-namespace.cpp
clang/test/Sema/builtin-pragma-intrinsic.c

Modified: 
clang/include/clang/Parse/Parser.h
clang/lib/Parse/ParsePragma.cpp

Removed: 




diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index c4bef4729fd36..98db8201390be 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -7074,6 +7074,10 @@ class Parser : public CodeCompletionHandler {
   bool HandlePragmaMSOptimize(StringRef PragmaName,
   SourceLocation PragmaLocation);
 
+  // #pragma intrinsic("foo")
+  bool HandlePragmaMSIntrinsic(StringRef PragmaName,
+   SourceLocation PragmaLocation);
+
   /// Handle the annotation token produced for
   /// #pragma align...
   void HandlePragmaAlign();

diff  --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index 77b61af768993..6341e565b5042 100644
--- a/clang/lib/Parse/ParsePragma.cpp
+++ b/clang/lib/Parse/ParsePragma.cpp
@@ -300,12 +300,6 @@ struct PragmaMSRuntimeChecksHandler : public 
EmptyPragmaHandler {
   PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
 };
 
-struct PragmaMSIntrinsicHandler : public PragmaHandler {
-  PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
-  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
-Token &FirstToken) override;
-};
-
 // "\#pragma fenv_access (on)".
 struct PragmaMSFenvAccessHandler : public PragmaHandler {
   PragmaMSFenvAccessHandler() : PragmaHandler("fenv_access") {}
@@ -517,7 +511,7 @@ void Parser::initializePragmaHandlers() {
 PP.AddPragmaHandler(MSOptimize.get());
 MSRuntimeChecks = std::make_unique();
 PP.AddPragmaHandler(MSRuntimeChecks.get());
-MSIntrinsic = std::make_unique();
+MSIntrinsic = std::make_unique("intrinsic");
 PP.AddPragmaHandler(MSIntrinsic.get());
 MSFenvAccess = std::make_unique();
 PP.AddPragmaHandler(MSFenvAccess.get());
@@ -1046,7 +1040,8 @@ void Parser::HandlePragmaMSPragma() {
   .Case("strict_gs_check", 
&Parser::HandlePragmaMSStrictGuardStackCheck)
   .Case("function", &Parser::HandlePragmaMSFunction)
   .Case("alloc_text", &Parser::HandlePragmaMSAllocText)
-  .Case("optimize", &Parser::HandlePragmaMSOptimize);
+  .Case("optimize", &Parser::HandlePragmaMSOptimize)
+  .Case("intrinsic", &Parser::HandlePragmaMSIntrinsic);
 
   if (!(this->*Handler)(PragmaName, PragmaLocation)) {
 // Pragma handling failed, and has been diagnosed.  Slurp up the tokens
@@ -3762,56 +3757,6 @@ void PragmaUnrollHintHandler::HandlePragma(Preprocessor 
&PP,
   /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
 }
 
-/// Handle the Microsoft \#pragma intrinsic extension.
-///
-/// The syntax is:
-/// \code
-///  #pragma intrinsic(memset)
-///  #pragma intrinsic(strlen, memcpy)
-/// \endcode
-///
-/// Pragma intrisic tells the compiler to use a builtin version of the
-/// function. Clang does it anyway, so the pragma doesn't really do anything.
-/// Anyway, we emit a warning if the function specified in \#pragma intrinsic
-/// 

[clang] [clang][Sema] Fix and reapply 'Declare builtins used in #pragma intrinsic #138205' (PR #142019)

2025-06-03 Thread Nick Sarnie via cfe-commits

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


[clang] 2e70da3 - [clang][bytecode] Partially address string literal uniqueness (#142555)

2025-06-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-06-03T16:26:31+02:00
New Revision: 2e70da3fba14f9ff0b29f65fed174f075d94d9a4

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

LOG: [clang][bytecode] Partially address string literal uniqueness (#142555)

This still leaves the case of the

constexpr auto b3 = name1() == name1();

test from cxx20.cpp broken.

Added: 


Modified: 
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/Pointer.cpp
clang/lib/AST/ByteCode/Pointer.h
clang/test/AST/ByteCode/cxx11.cpp
clang/test/AST/ByteCode/cxx20.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 4d1e5c6b98a8d..db91e5e328485 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -2008,6 +2008,51 @@ bool DiagTypeid(InterpState &S, CodePtr OpPC) {
   return false;
 }
 
+bool arePotentiallyOverlappingStringLiterals(const Pointer &LHS,
+ const Pointer &RHS) {
+  unsigned LHSOffset = LHS.getIndex();
+  unsigned RHSOffset = RHS.getIndex();
+  unsigned LHSLength = (LHS.getNumElems() - 1) * LHS.elemSize();
+  unsigned RHSLength = (RHS.getNumElems() - 1) * RHS.elemSize();
+
+  StringRef LHSStr((const char *)LHS.atIndex(0).getRawAddress(), LHSLength);
+  StringRef RHSStr((const char *)RHS.atIndex(0).getRawAddress(), RHSLength);
+  int32_t IndexDiff = RHSOffset - LHSOffset;
+  if (IndexDiff < 0) {
+if (static_cast(LHSLength) < -IndexDiff)
+  return false;
+LHSStr = LHSStr.drop_front(-IndexDiff);
+  } else {
+if (static_cast(RHSLength) < IndexDiff)
+  return false;
+RHSStr = RHSStr.drop_front(IndexDiff);
+  }
+
+  unsigned ShorterCharWidth;
+  StringRef Shorter;
+  StringRef Longer;
+  if (LHSLength < RHSLength) {
+ShorterCharWidth = LHS.elemSize();
+Shorter = LHSStr;
+Longer = RHSStr;
+  } else {
+ShorterCharWidth = RHS.elemSize();
+Shorter = RHSStr;
+Longer = LHSStr;
+  }
+
+  // The null terminator isn't included in the string data, so check for it
+  // manually. If the longer string doesn't have a null terminator where the
+  // shorter string ends, they aren't potentially overlapping.
+  for (unsigned NullByte : llvm::seq(ShorterCharWidth)) {
+if (Shorter.size() + NullByte >= Longer.size())
+  break;
+if (Longer[Shorter.size() + NullByte])
+  return false;
+  }
+  return Shorter == Longer.take_front(Shorter.size());
+}
+
 // https://github.com/llvm/llvm-project/issues/102513
 #if defined(_MSC_VER) && !defined(__clang__) && !defined(NDEBUG)
 #pragma optimize("", off)

diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 33de09a263b3e..ae3d4a441a799 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1035,6 +1035,9 @@ static inline bool IsOpaqueConstantCall(const CallExpr 
*E) {
   Builtin == Builtin::BI__builtin_function_start);
 }
 
+bool arePotentiallyOverlappingStringLiterals(const Pointer &LHS,
+ const Pointer &RHS);
+
 template <>
 inline bool CmpHelperEQ(InterpState &S, CodePtr OpPC, CompareFn Fn) {
   using BoolT = PrimConv::T;
@@ -1069,6 +1072,18 @@ inline bool CmpHelperEQ(InterpState &S, CodePtr 
OpPC, CompareFn Fn) {
 return true;
   }
 
+  // FIXME: The source check here isn't entirely correct.
+  if (LHS.pointsToStringLiteral() && RHS.pointsToStringLiteral() &&
+  LHS.getFieldDesc()->asExpr() != RHS.getFieldDesc()->asExpr()) {
+if (arePotentiallyOverlappingStringLiterals(LHS, RHS)) {
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc, diag::note_constexpr_literal_comparison)
+  << LHS.toDiagnosticString(S.getASTContext())
+  << RHS.toDiagnosticString(S.getASTContext());
+  return false;
+}
+  }
+
   if (Pointer::hasSameBase(LHS, RHS)) {
 if (LHS.inUnion() && RHS.inUnion()) {
   // If the pointers point into a union, things are a little more

diff  --git a/clang/lib/AST/ByteCode/Pointer.cpp 
b/clang/lib/AST/ByteCode/Pointer.cpp
index 6c2566ba20bde..50453c72c582b 100644
--- a/clang/lib/AST/ByteCode/Pointer.cpp
+++ b/clang/lib/AST/ByteCode/Pointer.cpp
@@ -571,6 +571,17 @@ bool Pointer::pointsToLiteral() const {
   return E && !isa(E);
 }
 
+bool Pointer::pointsToStringLiteral() const {
+  if (isZero() || !isBlockPointer())
+return false;
+
+  if (block()->isDynamic())
+return false;
+
+  const Expr *E = block()->getDescriptor()->asExpr();
+  return E && isa(E);
+}
+
 std::optional>
 Pointer::computeSplitPoint(const Pointer &A, const Pointer &B) {
   if (!A.isBlockPointer() || !B.isBlockPointer())

diff  --git a/clang/lib/AST/ByteCode/Pointer.h 
b/clang/lib

[clang] [clang][bytecode] Partially address string literal uniqueness (PR #142555)

2025-06-03 Thread Timm Baeder via cfe-commits

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


[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gkey-instructions 
-gno-column-info -x c++ %s -debug-info-kind=line-tables-only -emit-llvm -o - \
+// RUN: | FileCheck %s --implicit-check-not atomGroup --implicit-check-not 
atomRank
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gkey-instructions 
-gno-column-info -x c %s -debug-info-kind=line-tables-only -emit-llvm -o - \
+// RUN: | FileCheck %s --implicit-check-not atomGroup --implicit-check-not 
atomRank
+
+typedef struct {
+  struct{} a;
+  double b;
+} s1;
+
+s1 f(int z, ...) {
+  __builtin_va_list list;
+  __builtin_va_start(list, z);
+// CHECK: vaarg.end:
+// CHECK-NEXT: %vaarg.addr = phi ptr
+// CHECK-NEXT: call void @llvm.memcpy{{.*}}, !dbg [[G1R1:!.*]]

OCHyams wrote:

The comment from test return.c covers this case:
```
// Check the stores to `retval` allocas and branches to `return` block are in
// the same atom group. They are both rank 1, which could in theory introduce
// an extra step in some optimized code. This low risk currently feels an
// acceptable for keeping the code a bit simpler (as opposed to adding
// scaffolding to make the store rank 2).
```

(But in this case the "store to retval" is a memcpy).

We want them in the same group because these are all instructions generated 
from the source `return some_value`.

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


[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -1118,6 +1118,8 @@ void CodeGenFunction::EmitBranchThroughCleanup(JumpDest 
Dest) {
 
   // Create the branch.
   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
+  // This is the primary instruction for this atom, acting in place of a ret.

OCHyams wrote:

The code below has since been added in another patch that's already landed 
(without the comment) - rebased to remove from diff

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


[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

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


[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams commented:

> If I understand correctly, most of the test changes are to ensure that return 
> instructions get /an/ atom group, without being specific about which? IMO 
> it'd be better to make that number explicit to avoid a return accidentally 
> being part of the wrong atom group. It's necessary for it to be a distinct 
> group, right? (A chore, but an important fact).

Done. Rebased (to address an inline comment and capture since-merged tests).

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


[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -0,0 +1,101 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gkey-instructions 
-gno-column-info -x c++ %s -debug-info-kind=line-tables-only -emit-llvm -o - \
+// RUN: | FileCheck %s --check-prefixes=CHECK,CHECK-CXX
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gkey-instructions 
-gno-column-info -x c %s -debug-info-kind=line-tables-only -emit-llvm -o - \
+// RUN: | FileCheck %s
+
+// Check the stores to `retval` allocas and branches to `return` block are in
+// the same atom group. They are both rank 1, which could in theory introduce
+// an extra step in some optimized code. This low risk currently feels an
+// acceptable for keeping the code a bit simpler (as opposed to adding
+// scaffolding to make the store rank 2).
+
+// Also check that in the case of a single return (no control flow) the
+// return instruction inherits the atom group of the branch to the return
+// block when the blocks get folded togather.

OCHyams wrote:

Yep in Clang - here 
https://github.com/llvm/llvm-project/blob/2e70da3fba14f9ff0b29f65fed174f075d94d9a4/clang/lib/CodeGen/CodeGenFunction.cpp#L336

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


[clang] [clang][AST] Reduce some AST node size. (PR #142585)

2025-06-03 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/142585

>From 1a233dbb9d58cf488551caf29d441f2c6a5b68b5 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 3 Jun 2025 08:42:37 +0200
Subject: [PATCH 1/2] [clang][modules] Remove the workaround for the lambda
 issue.

This code was originally introduced to fix issue #110401. The issue was the 
same lambda problem, which has since been properly fixed by PR #109167 and its 
follow-ups.
---
 clang/lib/AST/DeclCXX.cpp | 31 +--
 1 file changed, 1 insertion(+), 30 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index f1f31d8be78c9..42b11e60d4584 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1702,36 +1702,7 @@ static NamedDecl* getLambdaCallOperatorHelper(const 
CXXRecordDecl &RD) {
 
   assert(allLookupResultsAreTheSame(Calls) &&
  "More than one lambda call operator!");
-
-  // FIXME: If we have multiple call operators, we might be in a situation
-  // where we merged this lambda with one from another module; in that
-  // case, return our method (instead of that of the other lambda).
-  //
-  // This avoids situations where, given two modules A and B, if we
-  // try to instantiate A's call operator in a function in B, anything
-  // in the call operator that relies on local decls in the surrounding
-  // function will crash because it tries to find A's decls, but we only
-  // instantiated B's:
-  //
-  //   template 
-  //   void f() {
-  // using T = int;  // We only instantiate B's version of this.
-  // auto L = [](T) { }; // But A's call operator would want A's here.
-  //   }
-  //
-  // Walk the call operator’s redecl chain to find the one that belongs
-  // to this module.
-  //
-  // TODO: We need to fix this properly (see
-  // https://github.com/llvm/llvm-project/issues/90154).
-  Module *M = RD.getOwningModule();
-  for (Decl *D : Calls.front()->redecls()) {
-auto *MD = cast(D);
-if (MD->getOwningModule() == M)
-  return MD;
-  }
-
-  llvm_unreachable("Couldn't find our call operator!");
+  return Calls.front();
 }
 
 FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {

>From ab9ea84bbae33719761c43de0a4231bb030006df Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Sat, 10 May 2025 07:44:51 +0200
Subject: [PATCH 2/2] [clang][AST] Reduce AST node size

---
 clang/include/clang/AST/Expr.h| 31 +
 clang/include/clang/AST/ExprCXX.h | 74 +++--
 clang/include/clang/AST/Stmt.h| 78 +++
 clang/include/clang/AST/StmtCXX.h |  2 +-
 clang/lib/AST/Expr.cpp|  7 +-
 clang/lib/AST/ExprCXX.cpp |  3 +-
 clang/lib/Serialization/ASTReaderStmt.cpp | 14 ++--
 clang/lib/Serialization/ASTWriterStmt.cpp |  6 +-
 8 files changed, 149 insertions(+), 66 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 87bb9df9cef8f..b0dbfefcfe0dd 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3127,7 +3127,9 @@ class CallExpr : public Expr {
   /// Bluntly set a new number of arguments without doing any checks 
whatsoever.
   /// Only used during construction of a CallExpr in a few places in Sema.
   /// FIXME: Find a way to remove it.
-  void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
+  void setNumArgsUnsafe(unsigned NewNumArgs) {
+NumArgs = NewNumArgs;
+  }
 
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
@@ -4579,7 +4581,6 @@ class ShuffleVectorExpr : public Expr {
   // indices.  The number of values in this list is always
   // 2+the number of indices in the vector type.
   Stmt **SubExprs;
-  unsigned NumExprs;
 
 public:
   ShuffleVectorExpr(const ASTContext &C, ArrayRef args, QualType Type,
@@ -4605,25 +4606,27 @@ class ShuffleVectorExpr : public Expr {
   /// getNumSubExprs - Return the size of the SubExprs array.  This includes 
the
   /// constant expression, the actual arguments passed in, and the function
   /// pointers.
-  unsigned getNumSubExprs() const { return NumExprs; }
+  unsigned getNumSubExprs() const { return ShuffleVectorExprBits.NumExprs; }
 
   /// Retrieve the array of expressions.
   Expr **getSubExprs() { return reinterpret_cast(SubExprs); }
 
   /// getExpr - Return the Expr at the specified index.
   Expr *getExpr(unsigned Index) {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
   const Expr *getExpr(unsigned Index) const {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
 
   void setExprs(const ASTContext &C, ArrayRef Exprs

[clang] [KeyInstr][Clang] Ret atom (PR #134652)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams updated 
https://github.com/llvm/llvm-project/pull/134652

>From a8837383c3289ab1c1e93b5fa00371241fa55fb4 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Fri, 4 Apr 2025 16:28:39 +0100
Subject: [PATCH 01/12] [KeyInstr][Clang] Ret atom

This patch is part of a stack that teaches Clang to generate Key Instructions
metadata for C and C++.

The Key Instructions project is introduced, including a "quick summary" section
at the top which adds context for this PR, here:
https://discourse.llvm.org/t/rfc-improving-is-stmt-placement-for-better-interactive-debugging/82668

The feature is only functional in LLVM if LLVM is built with CMake flag
LLVM_EXPERIMENTAL_KEY_INSTRUCTIONs. Eventually that flag will be removed.

The Clang-side work is demoed here:
https://github.com/llvm/llvm-project/pull/130943
---
 clang/lib/CodeGen/CGCall.cpp  |  6 +-
 clang/lib/CodeGen/CGStmt.cpp  | 13 ++-
 clang/lib/CodeGen/CodeGenFunction.cpp | 15 
 .../DebugInfo/KeyInstructions/return-va-arg.c | 25 ++
 clang/test/DebugInfo/KeyInstructions/return.c | 90 +++
 5 files changed, 144 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/DebugInfo/KeyInstructions/return-va-arg.c
 create mode 100644 clang/test/DebugInfo/KeyInstructions/return.c

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 056caf64525a5..b422ff6182a0a 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3946,7 +3946,8 @@ void CodeGenFunction::EmitFunctionEpilog(const 
CGFunctionInfo &FI,
 
   // Functions with no result always return void.
   if (!ReturnValue.isValid()) {
-Builder.CreateRetVoid();
+auto *I = Builder.CreateRetVoid();
+addRetToOverrideOrNewSourceAtom(I, nullptr);
 return;
   }
 
@@ -4126,6 +4127,9 @@ void CodeGenFunction::EmitFunctionEpilog(const 
CGFunctionInfo &FI,
 
   if (RetDbgLoc)
 Ret->setDebugLoc(std::move(RetDbgLoc));
+
+  llvm::Value *Backup = RV ? Ret->getOperand(0) : nullptr;
+  addRetToOverrideOrNewSourceAtom(cast(Ret), Backup);
 }
 
 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 205a57cbab31a..35ac2bc95c6ae 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1589,6 +1589,7 @@ static bool isSwiftAsyncCallee(const CallExpr *CE) {
 /// if the function returns void, or may be missing one if the function returns
 /// non-void.  Fun stuff :).
 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
+  ApplyAtomGroup Grp(getDebugInfo());
   if (requiresReturnValueCheck()) {
 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
 auto *SLocPtr =
@@ -1598,6 +1599,7 @@ void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) 
{
 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
 assert(ReturnLocation.isValid() && "No valid return location");
 Builder.CreateStore(SLocPtr, ReturnLocation);
+//*OCH?*//
   }
 
   // Returning from an outlined SEH helper is UB, and we already warn on it.
@@ -1664,16 +1666,19 @@ void CodeGenFunction::EmitReturnStmt(const ReturnStmt 
&S) {
 // If this function returns a reference, take the address of the expression
 // rather than the value.
 RValue Result = EmitReferenceBindingToExpr(RV);
-Builder.CreateStore(Result.getScalarVal(), ReturnValue);
+auto *I = Builder.CreateStore(Result.getScalarVal(), ReturnValue);
+addInstToCurrentSourceAtom(I, I->getValueOperand());
   } else {
 switch (getEvaluationKind(RV->getType())) {
 case TEK_Scalar: {
   llvm::Value *Ret = EmitScalarExpr(RV);
-  if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
+  if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
 EmitStoreOfScalar(Ret, MakeAddrLValue(ReturnValue, RV->getType()),
   /*isInit*/ true);
-  else
-Builder.CreateStore(Ret, ReturnValue);
+  } else {
+auto *I = Builder.CreateStore(Ret, ReturnValue);
+addInstToCurrentSourceAtom(I, I->getValueOperand());
+  }
   break;
 }
 case TEK_Complex:
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 0388c67d0100d..f44fc408cc97f 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -342,6 +342,15 @@ llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
   // later by the actual 'ret' instruction.
   llvm::DebugLoc Loc = BI->getDebugLoc();
   Builder.SetInsertPoint(BI->getParent());
+
+  // Key Instructions: If there's only one `ret` then we want to put the
+  // instruction in the same source atom group as the store to the 
ret-value
+  // alloca and unconditional `br` to the return block that we're about to
+  // delete. It all comes from the same source (`return (value)`).
+

[clang] [clang][AST] Reduce some AST node size. (PR #142585)

2025-06-03 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 HEAD~1 HEAD --extensions h,cpp -- 
clang/include/clang/AST/Expr.h clang/include/clang/AST/ExprCXX.h 
clang/include/clang/AST/Stmt.h clang/include/clang/AST/StmtCXX.h 
clang/lib/AST/DeclCXX.cpp clang/lib/AST/Expr.cpp clang/lib/AST/ExprCXX.cpp 
clang/lib/Serialization/ASTReaderStmt.cpp 
clang/lib/Serialization/ASTWriterStmt.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index b0dbfefcf..43c28c8bf 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3127,9 +3127,7 @@ public:
   /// Bluntly set a new number of arguments without doing any checks 
whatsoever.
   /// Only used during construction of a CallExpr in a few places in Sema.
   /// FIXME: Find a way to remove it.
-  void setNumArgsUnsafe(unsigned NewNumArgs) {
-NumArgs = NewNumArgs;
-  }
+  void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
 
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
@@ -4626,7 +4624,8 @@ public:
   void setExprs(const ASTContext &C, ArrayRef Exprs);
 
   llvm::APSInt getShuffleMaskIdx(unsigned N) const {
-assert((N < ShuffleVectorExprBits.NumExprs - 2) && "Shuffle idx out of 
range!");
+assert((N < ShuffleVectorExprBits.NumExprs - 2) &&
+   "Shuffle idx out of range!");
 assert(isa(getExpr(N + 2)) &&
"Index expression must be a ConstantExpr");
 return cast(getExpr(N + 2))->getAPValueResult().getInt();
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index a6f380b32..48a6aea4f 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -765,7 +765,7 @@ protected:
 
 LLVM_PREFERRED_TYPE(ExprBitfields)
 unsigned : NumExprBits;
-
+
 LLVM_PREFERRED_TYPE(bool)
 bool CondIsTrue : 1;
   };

``




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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-aarch64-linux-fuzzer` running on `sanitizer-buildbot12` while 
building `clang` at step 1 "update-annotate-scripts".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/159/builds/23586


Here is the relevant piece of the build log for the reference

```
Step 1 (update-annotate-scripts) failure: update (failure)
git version 2.43.0
fatal: unable to access 'https://github.com/llvm/llvm-zorg.git/': The requested 
URL returned error: 502
fatal: unable to access 'https://github.com/llvm/llvm-zorg.git/': The requested 
URL returned error: 503

```



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


[clang] 038b162 - clang: Fix wrong C++ marker in tablegen file (#142534)

2025-06-03 Thread via cfe-commits

Author: Matt Arsenault
Date: 2025-06-03T23:50:18+09:00
New Revision: 038b1620467d48df7abd99b38165133c4f13dce6

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

LOG: clang: Fix wrong C++ marker in tablegen file (#142534)

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsBase.td 
b/clang/include/clang/Basic/BuiltinsBase.td
index cf15a31235e7e..09bc9f89059fe 100644
--- a/clang/include/clang/Basic/BuiltinsBase.td
+++ b/clang/include/clang/Basic/BuiltinsBase.td
@@ -1,4 +1,4 @@
-//===--- BuiltinsBase.td - common structured used by builtins ---*- C++ 
-*-===//
+//===--- BuiltinsBase.td - common structured used by builtins 
-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.



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


[clang] clang: Fix wrong C++ marker in tablegen file (PR #142534)

2025-06-03 Thread Matt Arsenault via cfe-commits

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`llvm-clang-x86_64-sie-ubuntu-fast` running on `sie-linux-worker` while 
building `clang` at step 6 "test-build-unified-tree-check-all".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/144/builds/26730


Here is the relevant piece of the build log for the reference

```
Step 6 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'Clang :: CoverageMapping/terminate-statements.cpp' 
FAILED 
Exit Code: 2

Command Output (stderr):
--
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang 
-cc1 -internal-isystem 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/lib/clang/21/include
 -nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-scei-ps4-unknown 
-main-file-name terminate-statements.cpp -I 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/Inputs
 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
 | 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/FileCheck
 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
 # RUN: at line 1
+ 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/FileCheck
 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
+ 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang 
-cc1 -internal-isystem 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/lib/clang/21/include
 -nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-scei-ps4-unknown 
-main-file-name terminate-statements.cpp -I 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/Inputs
 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.  Program arguments: 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang 
-cc1 -internal-isystem 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/lib/clang/21/include
 -nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-scei-ps4-unknown 
-main-file-name terminate-statements.cpp -I 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/Inputs
 
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
1.  
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:45:1:
 current parser token 'int'
2.  
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:37:5:
 LLVM IR generation of declaration 'f6'
3.  
/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:37:5:
 Generating code for declaration 'f6'
 #0 0x57078c7e6500 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang+0x2244500)
 #1 0x57078c7e390f llvm::sys::RunSignalHandlers() 
(/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang+0x224190f)
 #2 0x57078c7e3a5a SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #3 0x7ee6660ea520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x57078cc921a3 
clang::CodeGen::CodeGenFunction::EmitCXXForRangeStmt(clang::CXXForRangeStmt 
const&, llvm::ArrayRef) 
(/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang+0x26f01a3)
 #5 0x57078cc966dc 
clang::CodeGen::CodeGenFunction::EmitCompoundStmtWithoutScope(clang::CompoundStmt
 const&, bool, clang::CodeGen::AggValueSlot) 
(/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang+0x26f46dc)
 #6 0x57078ccfc46d 
clang::CodeGen::CodeGenFunction::EmitFunctionBody(clang::Stmt const*) 
(/home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/build/bin/clang+0x275a46d)
 #7 0x57078cd1317f 
clang::CodeGen::CodeGenFunction::GenerateCod

[clang-tools-extra] [clangd] Improve Markup Rendering (PR #140498)

2025-06-03 Thread Maksim Ivanov via cfe-commits


@@ -118,8 +138,8 @@ class Document {
   BulletList &addBulletList();
 
   /// Doesn't contain any trailing newlines.
-  /// We try to make the markdown human-readable, e.g. avoid extra escaping.
-  /// At least one client (coc.nvim) displays the markdown verbatim!

emaxx-google wrote:

If I understand correctly, this PR assumes that the input documentation string 
is written using Markdown. The current implementation in Clangd, however, is 
much more conservative in its assumptions - it only recognizes basic syntax 
features like backticks. Hence when rendering for `markdown`, everything else 
is escaped because the assumption is it's actually a plain text, so that all 
characters that'd (accidentally?) trigger special semantics in the Markdown 
renderer are mangled to be not treated as such:

```c++
// Tests whether C should be backslash-escaped in markdown.
<...>
// It's always safe to escape punctuation, but want minimal escaping.
// The strategy is to escape the first character of anything that might start
// a markdown grammar construct.
```

A change to pass documentation strings as-is would cause regressions on code 
bases where comments aren't written with the markdown syntax in mind.

P.S. As for coc-nvim - I personally don't use it, but if we're to do radical 
changes to how things are output, it's worth it checking we don't regress the 
UI for this known case.

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


[clang] 986254e - [Clang] Implement LWG3819 for `__reference_meows_from_temporary` (#142554)

2025-06-03 Thread via cfe-commits

Author: A. Jiang
Date: 2025-06-03T22:58:14+08:00
New Revision: 986254ee0702cee4effccc2e818ea32455aae9a0

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

LOG: [Clang] Implement LWG3819 for `__reference_meows_from_temporary` (#142554)

Also fix use cases for function reference binding
(`__reference_binds_to_temporary` is also affected despite being
deprecated).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTypeTraits.cpp
clang/test/SemaCXX/type-traits.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a73c71cdd7201..eccee1aeef846 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -703,6 +703,15 @@ Bug Fixes to Compiler Builtins
   are ``__builtin_is_cpp_trivially_relocatable``. It is recommended to use
   ``__builtin_trivially_relocate`` instead.
 
+- ``__reference_binds_to_temporary``, ``__reference_constructs_from_temporary``
+  and ``__reference_converts_from_temporary`` intrinsics no longer consider
+  function references can bind to temporary objects. (#GH114344)
+
+- ``__reference_constructs_from_temporary`` and
+  ``__reference_converts_from_temporary`` intrinsics detect reference binding
+  to prvalue instead of xvalue now if the second operand is an object type, per
+  `LWG3819 `_.
+
 Bug Fixes to Attribute Support
 ^^
  - Fixed crash when a parameter to the ``clang::annotate`` attribute evaluates 
to ``void``. See #GH119125

diff  --git a/clang/lib/Sema/SemaTypeTraits.cpp 
b/clang/lib/Sema/SemaTypeTraits.cpp
index 04f54d7044e4f..b849bbe94af62 100644
--- a/clang/lib/Sema/SemaTypeTraits.cpp
+++ b/clang/lib/Sema/SemaTypeTraits.cpp
@@ -1343,12 +1343,21 @@ static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait 
Kind,
 if (RD && RD->isAbstract())
   return false;
 
+// LWG3819: For reference_meows_from_temporary traits, && is not added to
+// the source object type.
+// Otherwise, compute the result of add_rvalue_reference_t.
+bool UseRawObjectType =
+Kind == clang::BTT_ReferenceBindsToTemporary ||
+Kind == clang::BTT_ReferenceConstructsFromTemporary ||
+Kind == clang::BTT_ReferenceConvertsFromTemporary;
+
 llvm::BumpPtrAllocator OpaqueExprAllocator;
 SmallVector ArgExprs;
 ArgExprs.reserve(Args.size() - 1);
 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
   QualType ArgTy = Args[I]->getType();
-  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
+  if ((ArgTy->isObjectType() && !UseRawObjectType) ||
+  ArgTy->isFunctionType())
 ArgTy = S.Context.getRValueReferenceType(ArgTy);
   ArgExprs.push_back(
   new (OpaqueExprAllocator.Allocate())
@@ -1386,6 +1395,10 @@ static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait 
Kind,
   if (!T->isReferenceType())
 return false;
 
+  // A function reference never binds to a temporary object.
+  if (T.getNonReferenceType()->isFunctionType())
+return false;
+
   if (!Init.isDirectReferenceBinding())
 return true;
 

diff  --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 56cca05402f45..3f0124755c674 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -3143,6 +3143,10 @@ void reference_binds_to_temporary_checks() {
   static_assert(!(__reference_binds_to_temporary(int, long)));
 
   static_assert((__reference_binds_to_temporary(const int &, long)));
+
+  // Test that function references are never considered bound to temporaries.
+  static_assert(!__reference_binds_to_temporary(void(&)(), void()));
+  static_assert(!__reference_binds_to_temporary(void(&&)(), void()));
 }
 
 
@@ -3156,6 +3160,14 @@ struct ExplicitConversionRef {
 explicit operator int&();
 };
 
+struct NonMovable {
+  NonMovable(NonMovable&&) = delete;
+};
+
+struct ConvertsFromNonMovable {
+  ConvertsFromNonMovable(NonMovable);
+};
+
 void reference_constructs_from_temporary_checks() {
   static_assert(!__reference_constructs_from_temporary(int &, int &));
   static_assert(!__reference_constructs_from_temporary(int &, int &&));
@@ -3193,6 +3205,16 @@ void reference_constructs_from_temporary_checks() {
 
   static_assert(__reference_constructs_from_temporary(const int &, long));
 
+  // Test that function references are never considered bound to temporaries.
+  static_assert(!__reference_constructs_from_temporary(void(&&)(), void()));
+  static_assert(!__reference_constructs_from_temporary(void(&)(), void()));
+
+  // LWG3819: reference_meows_from_temporary should not use is_meowible
+  
static_assert(__reference_constructs_from_temporary(ConvertsFromNonMovable&&, 
NonMov

[clang] [Clang] Implement LWG3819 for `__reference_meows_from_temporary` (PR #142554)

2025-06-03 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja closed 
https://github.com/llvm/llvm-project/pull/142554
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Fix crash on template-specialization (PR #142338)

2025-06-03 Thread Mark de Wever via cfe-commits

https://github.com/mark-de-wever-sonarsource updated 
https://github.com/llvm/llvm-project/pull/142338

>From 930e073e4d5bfbde8028fbb8330e6b91348cc20b Mon Sep 17 00:00:00 2001
From: Mark de Wever 
Date: Mon, 2 Jun 2025 08:57:59 +0200
Subject: [PATCH 1/2] Fix crash on template-specialization

This applies the name restoration as suggested by Richard Smith.

Fixes: #54279
---
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 5 +
 clang/test/CodeGenCXX/constructor-init.cpp | 2 +-
 clang/test/SemaTemplate/default-arguments.cpp  | 9 +
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 174c8fc59e4fa..9853466e01496 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -34,6 +34,7 @@
 #include "clang/Sema/SemaSwift.h"
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateInstCallback.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/TimeProfiler.h"
 #include 
 
@@ -5120,6 +5121,10 @@ bool Sema::addInstantiatedParametersToScope(
   // Simple case: not a parameter pack.
   assert(FParamIdx < Function->getNumParams());
   ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
+  DeclarationName name = FunctionParam->getDeclName();
+  auto _ = llvm::make_scope_exit([&]() {
+FunctionParam->setDeclName(name);
+  });
   FunctionParam->setDeclName(PatternParam->getDeclName());
   // If the parameter's type is not dependent, update it to match the type
   // in the pattern. They can differ in top-level cv-qualifiers, and we 
want
diff --git a/clang/test/CodeGenCXX/constructor-init.cpp 
b/clang/test/CodeGenCXX/constructor-init.cpp
index f191599f360e7..b5f4cc0b3d6c8 100644
--- a/clang/test/CodeGenCXX/constructor-init.cpp
+++ b/clang/test/CodeGenCXX/constructor-init.cpp
@@ -160,7 +160,7 @@ template struct X;
 
 // Make sure that the instantiated constructor initializes start and
 // end properly.
-// CHECK-LABEL: define linkonce_odr void @_ZN1XIiEC2ERKS0_(ptr {{[^,]*}} 
%this, ptr noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) %other) 
unnamed_addr
+// CHECK-LABEL: define linkonce_odr void @_ZN1XIiEC2ERKS0_(ptr {{[^,]*}} 
%this, ptr noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) %0) 
unnamed_addr
 // CHECK: {{store.*null}}
 // CHECK: {{store.*null}}
 // CHECK: ret
diff --git a/clang/test/SemaTemplate/default-arguments.cpp 
b/clang/test/SemaTemplate/default-arguments.cpp
index 5ea34c0254ec1..a366c3d8ab722 100644
--- a/clang/test/SemaTemplate/default-arguments.cpp
+++ b/clang/test/SemaTemplate/default-arguments.cpp
@@ -283,3 +283,12 @@ static_assert(S().SizeOfT() == sizeof(short 
*), "");
 } // namespace GH68490
 
 #endif
+
+namespace PR54279 {
+// Using a different name for the argument when there is a default argument
+// caused a crash.
+template  void f(const T &a, int c = 0);
+template <> void f(const int &unused, int) {
+  f(42);
+}
+}

>From 25d0d5dace764977949e91a1a65d81dc79239bb8 Mon Sep 17 00:00:00 2001
From: Mark de Wever 
Date: Tue, 3 Jun 2025 16:58:53 +0200
Subject: [PATCH 2/2] Address review comments

---
 clang/docs/ReleaseNotes.rst   |  1 +
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  4 +-
 clang/test/SemaTemplate/default-arguments.cpp | 40 +++
 3 files changed, 43 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 32266fce4d3cb..810b725c2a456 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -805,6 +805,7 @@ Bug Fixes to C++ Support
 - Clang modules now allow a module and its user to differ on 
TrivialAutoVarInit*
 - Fixed an access checking bug when initializing non-aggregates in default 
arguments (#GH62444), (#GH83608)
 - Fixed a pack substitution bug in deducing class template partial 
specializations. (#GH53609)
+- Fixed a crash when specializing a template function whose primary template 
has a default argument (#GH54279) (#GH95420)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9853466e01496..f926b0458ff9e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5121,9 +5121,9 @@ bool Sema::addInstantiatedParametersToScope(
   // Simple case: not a parameter pack.
   assert(FParamIdx < Function->getNumParams());
   ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
-  DeclarationName name = FunctionParam->getDeclName();
+  DeclarationName Name = FunctionParam->getDeclName();
   auto _ = llvm::make_scope_exit([&]() {
-FunctionParam->setDeclName(name);
+FunctionParam->setDeclName(Name);
   });
   FunctionParam->setDeclName(PatternParam->getDeclName());
  

[clang] [Clang] Fix crash on template-specialization (PR #142338)

2025-06-03 Thread Mark de Wever via cfe-commits

https://github.com/mark-de-wever-sonarsource edited 
https://github.com/llvm/llvm-project/pull/142338
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Improve Markup Rendering (PR #140498)

2025-06-03 Thread Maksim Ivanov via cfe-commits

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


[clang] [clang][AST] Reduce some AST node size. (PR #142585)

2025-06-03 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/142585

>From 1a233dbb9d58cf488551caf29d441f2c6a5b68b5 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 3 Jun 2025 08:42:37 +0200
Subject: [PATCH 1/3] [clang][modules] Remove the workaround for the lambda
 issue.

This code was originally introduced to fix issue #110401. The issue was the 
same lambda problem, which has since been properly fixed by PR #109167 and its 
follow-ups.
---
 clang/lib/AST/DeclCXX.cpp | 31 +--
 1 file changed, 1 insertion(+), 30 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index f1f31d8be78c9..42b11e60d4584 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1702,36 +1702,7 @@ static NamedDecl* getLambdaCallOperatorHelper(const 
CXXRecordDecl &RD) {
 
   assert(allLookupResultsAreTheSame(Calls) &&
  "More than one lambda call operator!");
-
-  // FIXME: If we have multiple call operators, we might be in a situation
-  // where we merged this lambda with one from another module; in that
-  // case, return our method (instead of that of the other lambda).
-  //
-  // This avoids situations where, given two modules A and B, if we
-  // try to instantiate A's call operator in a function in B, anything
-  // in the call operator that relies on local decls in the surrounding
-  // function will crash because it tries to find A's decls, but we only
-  // instantiated B's:
-  //
-  //   template 
-  //   void f() {
-  // using T = int;  // We only instantiate B's version of this.
-  // auto L = [](T) { }; // But A's call operator would want A's here.
-  //   }
-  //
-  // Walk the call operator’s redecl chain to find the one that belongs
-  // to this module.
-  //
-  // TODO: We need to fix this properly (see
-  // https://github.com/llvm/llvm-project/issues/90154).
-  Module *M = RD.getOwningModule();
-  for (Decl *D : Calls.front()->redecls()) {
-auto *MD = cast(D);
-if (MD->getOwningModule() == M)
-  return MD;
-  }
-
-  llvm_unreachable("Couldn't find our call operator!");
+  return Calls.front();
 }
 
 FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {

>From ab9ea84bbae33719761c43de0a4231bb030006df Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Sat, 10 May 2025 07:44:51 +0200
Subject: [PATCH 2/3] [clang][AST] Reduce AST node size

---
 clang/include/clang/AST/Expr.h| 31 +
 clang/include/clang/AST/ExprCXX.h | 74 +++--
 clang/include/clang/AST/Stmt.h| 78 +++
 clang/include/clang/AST/StmtCXX.h |  2 +-
 clang/lib/AST/Expr.cpp|  7 +-
 clang/lib/AST/ExprCXX.cpp |  3 +-
 clang/lib/Serialization/ASTReaderStmt.cpp | 14 ++--
 clang/lib/Serialization/ASTWriterStmt.cpp |  6 +-
 8 files changed, 149 insertions(+), 66 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 87bb9df9cef8f..b0dbfefcfe0dd 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3127,7 +3127,9 @@ class CallExpr : public Expr {
   /// Bluntly set a new number of arguments without doing any checks 
whatsoever.
   /// Only used during construction of a CallExpr in a few places in Sema.
   /// FIXME: Find a way to remove it.
-  void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
+  void setNumArgsUnsafe(unsigned NewNumArgs) {
+NumArgs = NewNumArgs;
+  }
 
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
@@ -4579,7 +4581,6 @@ class ShuffleVectorExpr : public Expr {
   // indices.  The number of values in this list is always
   // 2+the number of indices in the vector type.
   Stmt **SubExprs;
-  unsigned NumExprs;
 
 public:
   ShuffleVectorExpr(const ASTContext &C, ArrayRef args, QualType Type,
@@ -4605,25 +4606,27 @@ class ShuffleVectorExpr : public Expr {
   /// getNumSubExprs - Return the size of the SubExprs array.  This includes 
the
   /// constant expression, the actual arguments passed in, and the function
   /// pointers.
-  unsigned getNumSubExprs() const { return NumExprs; }
+  unsigned getNumSubExprs() const { return ShuffleVectorExprBits.NumExprs; }
 
   /// Retrieve the array of expressions.
   Expr **getSubExprs() { return reinterpret_cast(SubExprs); }
 
   /// getExpr - Return the Expr at the specified index.
   Expr *getExpr(unsigned Index) {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
   const Expr *getExpr(unsigned Index) const {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
 
   void setExprs(const ASTContext &C, ArrayRef Exprs

[clang] e6529dc - Revert "[KeyInstr][Clang] For range stmt atoms" (#142630)

2025-06-03 Thread via cfe-commits

Author: Orlando Cazalet-Hyams
Date: 2025-06-03T16:15:46+01:00
New Revision: e6529dcedb3955706a8af5710591f1ac1bac26a3

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

LOG: Revert "[KeyInstr][Clang] For range stmt atoms" (#142630)

Reverts llvm/llvm-project#134647

Bot failure:

https://lab.llvm.org/buildbot/#/builders/144/builds/26730/steps/6/logs/FAIL__Clang__terminate-statements_cpp

Added: 


Modified: 
clang/lib/CodeGen/CGStmt.cpp

Removed: 
clang/test/DebugInfo/KeyInstructions/for-range.cpp



diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8739455481767..205a57cbab31a 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,14 +1483,7 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
-  // Key Instructions: Emit the condition and branch as separate atoms to
-  // match existing loop stepping behaviour. FIXME: We could have the branch as
-  // the backup location for the condition, which would probably be a better
-  // experience.
-  if (auto *CondI = dyn_cast(BoolCondVal))
-addInstToNewSourceAtom(CondI, nullptr);
-  addInstToNewSourceAtom(I, nullptr);
+  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1516,10 +1509,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 EmitStmt(S.getBody());
   }
 
-  // The last block in the loop's body (which unconditionally branches to the
-  // `inc` block if there is one).
-  auto *FinalBodyBB = Builder.GetInsertBlock();
-
   EmitStopPoint(&S);
   // If there is an increment, emit it next.
   EmitBlock(Continue.getBlock());
@@ -1543,10 +1532,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
-
-  // We want the for closing brace to be step-able on to match existing
-  // behaviour.
-  addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {

diff  --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
deleted file mode 100644
index 921060f3b2462..0
--- a/clang/test/DebugInfo/KeyInstructions/for-range.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu  -gkey-instructions %s 
-debug-info-kind=line-tables-only -emit-llvm -o - \
-// RUN: | FileCheck %s
-
-// Perennial question: should the inc be its own source atom or not
-// (currently it is).
-
-// FIXME: See do.c and while.c regarding cmp and cond br groups.
-
-// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
-// marked as Key. Unclear whether that's desirable. Keep for now as that's
-// least risky (at worst it introduces an unnecessary step while debugging,
-// as opposed to potentially losing one we want).
-
-// Check the conditional branch (and the condition) in FOR_COND and
-// unconditional branch in FOR_BODY are Key Instructions.
-
-struct Range {
-int *begin();
-int *end();
-} r;
-
-// CHECK-LABEL: define dso_local void @_Z1av(
-// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
-// CHECK-NEXT:  [[ENTRY:.*:]]
-// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
-// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
-// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
-// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
-// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
-// CHECK:   [[FOR_COND]]:
-// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
-// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[[FOR_END:.*]], !dbg [[DBG21:![0-9]+]

[clang] Revert "[KeyInstr][Clang] For range stmt atoms" (PR #142630)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

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


[clang] Revert "[KeyInstr][Clang] For range stmt atoms" (PR #142630)

2025-06-03 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams created 
https://github.com/llvm/llvm-project/pull/142630

Reverts llvm/llvm-project#134647

Bot failure:
https://lab.llvm.org/buildbot/#/builders/144/builds/26730/steps/6/logs/FAIL__Clang__terminate-statements_cpp

>From 36efd649134e82ec7083c1fd02ff6f11b128604f Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Tue, 3 Jun 2025 16:15:12 +0100
Subject: [PATCH] Revert "[KeyInstr][Clang] For range stmt atoms (#134647)"

This reverts commit 10024363dd04b08279c24e7948a2e0e8e2a57b6f.
---
 clang/lib/CodeGen/CGStmt.cpp  | 17 +---
 .../DebugInfo/KeyInstructions/for-range.cpp   | 87 ---
 2 files changed, 1 insertion(+), 103 deletions(-)
 delete mode 100644 clang/test/DebugInfo/KeyInstructions/for-range.cpp

diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8739455481767..205a57cbab31a 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,14 +1483,7 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
-  // Key Instructions: Emit the condition and branch as separate atoms to
-  // match existing loop stepping behaviour. FIXME: We could have the branch as
-  // the backup location for the condition, which would probably be a better
-  // experience.
-  if (auto *CondI = dyn_cast(BoolCondVal))
-addInstToNewSourceAtom(CondI, nullptr);
-  addInstToNewSourceAtom(I, nullptr);
+  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1516,10 +1509,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 EmitStmt(S.getBody());
   }
 
-  // The last block in the loop's body (which unconditionally branches to the
-  // `inc` block if there is one).
-  auto *FinalBodyBB = Builder.GetInsertBlock();
-
   EmitStopPoint(&S);
   // If there is an increment, emit it next.
   EmitBlock(Continue.getBlock());
@@ -1543,10 +1532,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
-
-  // We want the for closing brace to be step-able on to match existing
-  // behaviour.
-  addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
diff --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
deleted file mode 100644
index 921060f3b2462..0
--- a/clang/test/DebugInfo/KeyInstructions/for-range.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu  -gkey-instructions %s 
-debug-info-kind=line-tables-only -emit-llvm -o - \
-// RUN: | FileCheck %s
-
-// Perennial question: should the inc be its own source atom or not
-// (currently it is).
-
-// FIXME: See do.c and while.c regarding cmp and cond br groups.
-
-// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
-// marked as Key. Unclear whether that's desirable. Keep for now as that's
-// least risky (at worst it introduces an unnecessary step while debugging,
-// as opposed to potentially losing one we want).
-
-// Check the conditional branch (and the condition) in FOR_COND and
-// unconditional branch in FOR_BODY are Key Instructions.
-
-struct Range {
-int *begin();
-int *end();
-} r;
-
-// CHECK-LABEL: define dso_local void @_Z1av(
-// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
-// CHECK-NEXT:  [[ENTRY:.*:]]
-// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
-// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
-// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
-// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
-// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
-// CHECK:   [[FOR_COND]]:
-// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
-// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[

[clang] Revert "[KeyInstr][Clang] For range stmt atoms" (PR #142630)

2025-06-03 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Orlando Cazalet-Hyams (OCHyams)


Changes

Reverts llvm/llvm-project#134647

Bot failure:
https://lab.llvm.org/buildbot/#/builders/144/builds/26730/steps/6/logs/FAIL__Clang__terminate-statements_cpp

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGStmt.cpp (+1-16) 
- (removed) clang/test/DebugInfo/KeyInstructions/for-range.cpp (-87) 


``diff
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 8739455481767..205a57cbab31a 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1483,14 +1483,7 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
 BoolCondVal, Stmt::getLikelihood(S.getBody()));
-  auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
-  // Key Instructions: Emit the condition and branch as separate atoms to
-  // match existing loop stepping behaviour. FIXME: We could have the branch as
-  // the backup location for the condition, which would probably be a better
-  // experience.
-  if (auto *CondI = dyn_cast(BoolCondVal))
-addInstToNewSourceAtom(CondI, nullptr);
-  addInstToNewSourceAtom(I, nullptr);
+  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
 
   if (ExitBlock != LoopExit.getBlock()) {
 EmitBlock(ExitBlock);
@@ -1516,10 +1509,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 EmitStmt(S.getBody());
   }
 
-  // The last block in the loop's body (which unconditionally branches to the
-  // `inc` block if there is one).
-  auto *FinalBodyBB = Builder.GetInsertBlock();
-
   EmitStopPoint(&S);
   // If there is an increment, emit it next.
   EmitBlock(Continue.getBlock());
@@ -1543,10 +1532,6 @@ CodeGenFunction::EmitCXXForRangeStmt(const 
CXXForRangeStmt &S,
 
   if (CGM.shouldEmitConvergenceTokens())
 ConvergenceTokenStack.pop_back();
-
-  // We want the for closing brace to be step-able on to match existing
-  // behaviour.
-  addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
 }
 
 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
diff --git a/clang/test/DebugInfo/KeyInstructions/for-range.cpp 
b/clang/test/DebugInfo/KeyInstructions/for-range.cpp
deleted file mode 100644
index 921060f3b2462..0
--- a/clang/test/DebugInfo/KeyInstructions/for-range.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu  -gkey-instructions %s 
-debug-info-kind=line-tables-only -emit-llvm -o - \
-// RUN: | FileCheck %s
-
-// Perennial question: should the inc be its own source atom or not
-// (currently it is).
-
-// FIXME: See do.c and while.c regarding cmp and cond br groups.
-
-// The stores in the setup (stores to __RANGE1, __BEGIN1, __END1) are all
-// marked as Key. Unclear whether that's desirable. Keep for now as that's
-// least risky (at worst it introduces an unnecessary step while debugging,
-// as opposed to potentially losing one we want).
-
-// Check the conditional branch (and the condition) in FOR_COND and
-// unconditional branch in FOR_BODY are Key Instructions.
-
-struct Range {
-int *begin();
-int *end();
-} r;
-
-// CHECK-LABEL: define dso_local void @_Z1av(
-// CHECK-SAME: ) #[[ATTR0:[0-9]+]] !dbg [[DBG10:![0-9]+]] {
-// CHECK-NEXT:  [[ENTRY:.*:]]
-// CHECK-NEXT:[[__RANGE1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__BEGIN1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[__END1:%.*]] = alloca ptr, align 8
-// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
-// CHECK-NEXT:store ptr @r, ptr [[__RANGE1]], align 8, !dbg 
[[DBG14:![0-9]+]]
-// CHECK-NEXT:[[CALL:%.*]] = call noundef ptr @_ZN5Range5beginEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG15:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL]], ptr [[__BEGIN1]], align 8, !dbg 
[[DBG16:![0-9]+]]
-// CHECK-NEXT:[[CALL1:%.*]] = call noundef ptr @_ZN5Range3endEv(ptr 
noundef nonnull align 1 dereferenceable(1) @r), !dbg [[DBG17:![0-9]+]]
-// CHECK-NEXT:store ptr [[CALL1]], ptr [[__END1]], align 8, !dbg 
[[DBG18:![0-9]+]]
-// CHECK-NEXT:br label %[[FOR_COND:.*]], !dbg [[DBG19:![0-9]+]]
-// CHECK:   [[FOR_COND]]:
-// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[__END1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[CMP:%.*]] = icmp ne ptr [[TMP0]], [[TMP1]], !dbg 
[[DBG20:![0-9]+]]
-// CHECK-NEXT:br i1 [[CMP]], label %[[FOR_BODY:.*]], label 
%[[FOR_END:.*]], !dbg [[DBG21:![0-9]+]]
-// CHECK:   [[FOR_BODY]]:
-// CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[__BEGIN1]], align 8, !dbg 
[[DBG19]]
-// CHECK-NEXT:[[TMP3:%.*]] = load i32, ptr [[TMP2]], align 4, !dbg 
[[DBG22:![0-9]+]]
-// CHECK-

[clang] [Clang] Fix crash on template-specialization (PR #142338)

2025-06-03 Thread Shafik Yaghmour via cfe-commits


@@ -160,7 +160,7 @@ template struct X;
 
 // Make sure that the instantiated constructor initializes start and
 // end properly.
-// CHECK-LABEL: define linkonce_odr void @_ZN1XIiEC2ERKS0_(ptr {{[^,]*}} 
%this, ptr noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) %other) 
unnamed_addr
+// CHECK-LABEL: define linkonce_odr void @_ZN1XIiEC2ERKS0_(ptr {{[^,]*}} 
%this, ptr noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) %0) 
unnamed_addr

shafik wrote:

What name does it change it to? Is this expected?

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


[clang] [C++20][Modules] Implement P1857R3 Modules Dependency Discovery (PR #107168)

2025-06-03 Thread via cfe-commits

yronglin wrote:

@Bigcheese I have a question about `A module directive may only appear as the 
first preprocessing tokens in a file (excluding the global module fragment.)`. 
IIUC, as you said in 
https://github.com/llvm/llvm-project/pull/90574#discussion_r1591569547, this 
rule intended to prohibit the following code? 
```C++
// error: User need to have a `module;` decl before any preprocessor directives.
#include "foo.h"
export module M;
```

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


[clang] [Driver] Teach Barmetal toolchain about GCC installation (PR #121829)

2025-06-03 Thread Peter Smith via cfe-commits

smithp35 wrote:

> Hi @smithp35, can you pls review the latest changes and approve this PR if 
> everything looks fine?

I'll take a look this week. You'll probably need an approval from PetrHosek 
too. I'm mostly coming at this from an angle of will it break anything in the 
existing bare-metal driver. Probably needs some input from the RISCV side.

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


[clang] [clang][modules] rename "AST" to precompiled in diagnostic messages NFCI (PR #142635)

2025-06-03 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/142635

As follow up to: 
https://github.com/llvm/llvm-project/commit/883130e33325282cfd31b68f5db52891442c20b7
 

>From f91e978a380ab3455843c120c4df66aa20ca8807 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Mon, 2 Jun 2025 19:38:28 -0700
Subject: [PATCH] [clang][modules] rename "AST" to precompiled in diagnostic
 messages, NFCI

---
 .../Basic/DiagnosticSerializationKinds.td | 54 +--
 clang/lib/Serialization/ASTReader.cpp | 11 ++--
 .../Modules/check-for-sanitizer-feature.cpp   |  2 +-
 .../test/Modules/cxx20-force-check-input.cppm |  4 +-
 clang/test/Modules/explicit-build.cpp |  4 +-
 .../test/Modules/fatal-module-loader-error.m  |  4 +-
 clang/test/Modules/ignored_macros.m   |  2 +-
 clang/test/Modules/load_failure.c |  2 +-
 clang/test/Modules/merge-target-features.cpp  |  6 +--
 clang/test/Modules/mismatch-diagnostics.cpp   |  2 +-
 .../Modules/module-imported-by-pch-path.m |  2 +-
 .../Modules/module-pch-different-cache-path.c |  4 +-
 clang/test/Modules/pr62359.cppm   |  4 +-
 clang/test/Modules/resolution-change.m|  4 +-
 clang/test/PCH/module-hash-difference.m   |  2 +-
 15 files changed, 54 insertions(+), 53 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 93e31c8155ffc..584c8d62280bf 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -13,13 +13,13 @@ def err_fe_unable_to_read_pch_file : Error<
 "unable to read PCH file %0: '%1'">;
 def err_fe_not_a_pch_file : Error<
 "input is not a PCH file: '%0'">;
-def err_fe_pch_malformed : Error<
-"malformed or corrupted AST file: '%0'">, DefaultFatal;
+def err_fe_ast_file_malformed : Error<
+"malformed or corrupted precompiled file: '%0'">, DefaultFatal;
 def err_fe_pch_malformed_block : Error<
 "malformed block record in PCH file: '%0'">, DefaultFatal;
 def err_fe_ast_file_modified : Error<
 "file '%0' has been modified since the "
-"%select{precompiled header|module file|AST file}1 '%2' was built"
+"%select{precompiled header|module file|precompiled file}1 '%2' was built"
 ": %select{size|mtime|content}3 changed%select{| (was %5, now %6)}4">,
 DefaultFatal;
 def err_fe_pch_file_overridden : Error<
@@ -31,19 +31,19 @@ def note_module_cache_path : Note<
 "after modifying system headers, please delete the module cache at '%0'">;
 
 def err_ast_file_targetopt_mismatch : Error<
-"AST file '%0' was compiled for the %1 '%2' but the current translation "
+"precompiled file '%0' was compiled for the %1 '%2' but the current 
translation "
 "unit is being compiled for target '%3'">;
 def err_ast_file_targetopt_feature_mismatch : Error<
-"%select{AST file '%1' was|current translation unit is}0 compiled with the 
target "
-"feature '%2' but the %select{current translation unit is|AST file '%1' 
was}0 "
+"%select{precompiled file '%1' was|current translation unit is}0 compiled 
with the target "
+"feature '%2' but the %select{current translation unit is|precompiled file 
'%1' was}0 "
 "not">;
 def err_ast_file_langopt_mismatch : Error<"%0 was %select{disabled|enabled}1 
in "
-"AST file '%3' but is currently %select{disabled|enabled}2">;
+"precompiled file '%3' but is currently %select{disabled|enabled}2">;
 def err_ast_file_langopt_value_mismatch : Error<
-  "%0 differs in AST file '%1' vs. current file">;
+  "%0 differs in precompiled file '%1' vs. current file">;
 def err_ast_file_diagopt_mismatch : Error<"%0 is currently enabled, but was 
not in "
-  "the AST file '%1'">;
-def err_ast_file_modulecache_mismatch : Error<"AST file '%2' was compiled with 
module cache "
+  "the precompiled file '%1'">;
+def err_ast_file_modulecache_mismatch : Error<"precompiled file '%2' was 
compiled with module cache "
   "path '%0', but the path is currently '%1'">;
 def warn_pch_vfsoverlay_mismatch : Warning<
   "PCH was compiled with different VFS overlay files than are currently in 
use">,
@@ -52,27 +52,27 @@ def note_pch_vfsoverlay_files : Note<"%select{PCH|current 
translation unit}0 has
 def note_pch_vfsoverlay_empty : Note<"%select{PCH|current translation unit}0 
has no VFS overlays">;
 
 def err_ast_file_version_too_old : Error<
-"%select{PCH|module|AST}0 file '%1' uses an older format that is no longer 
supported">;
+"%select{PCH|module|precompiled}0 file '%1' uses an older format that is 
no longer supported">;
 def err_ast_file_version_too_new : Error<
-"%select{PCH|module|AST}0 file '%1' uses a newer format that cannot be 
read">;
+"%select{PCH|module|precompiled }0 file '%1' uses a newer format that 
cannot be read">;
 def err_ast_file_different_branch : Error<
-"%select{PCH|module|AST}0 file '%1' built from a di

[clang] [clang][modules] rename "AST" to precompiled in diagnostic messages NFCI (PR #142635)

2025-06-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes

As follow up to: 
https://github.com/llvm/llvm-project/commit/883130e33325282cfd31b68f5db52891442c20b7
 

---

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


15 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSerializationKinds.td (+27-27) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+6-5) 
- (modified) clang/test/Modules/check-for-sanitizer-feature.cpp (+1-1) 
- (modified) clang/test/Modules/cxx20-force-check-input.cppm (+2-2) 
- (modified) clang/test/Modules/explicit-build.cpp (+2-2) 
- (modified) clang/test/Modules/fatal-module-loader-error.m (+2-2) 
- (modified) clang/test/Modules/ignored_macros.m (+1-1) 
- (modified) clang/test/Modules/load_failure.c (+1-1) 
- (modified) clang/test/Modules/merge-target-features.cpp (+3-3) 
- (modified) clang/test/Modules/mismatch-diagnostics.cpp (+1-1) 
- (modified) clang/test/Modules/module-imported-by-pch-path.m (+1-1) 
- (modified) clang/test/Modules/module-pch-different-cache-path.c (+2-2) 
- (modified) clang/test/Modules/pr62359.cppm (+2-2) 
- (modified) clang/test/Modules/resolution-change.m (+2-2) 
- (modified) clang/test/PCH/module-hash-difference.m (+1-1) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 93e31c8155ffc..584c8d62280bf 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -13,13 +13,13 @@ def err_fe_unable_to_read_pch_file : Error<
 "unable to read PCH file %0: '%1'">;
 def err_fe_not_a_pch_file : Error<
 "input is not a PCH file: '%0'">;
-def err_fe_pch_malformed : Error<
-"malformed or corrupted AST file: '%0'">, DefaultFatal;
+def err_fe_ast_file_malformed : Error<
+"malformed or corrupted precompiled file: '%0'">, DefaultFatal;
 def err_fe_pch_malformed_block : Error<
 "malformed block record in PCH file: '%0'">, DefaultFatal;
 def err_fe_ast_file_modified : Error<
 "file '%0' has been modified since the "
-"%select{precompiled header|module file|AST file}1 '%2' was built"
+"%select{precompiled header|module file|precompiled file}1 '%2' was built"
 ": %select{size|mtime|content}3 changed%select{| (was %5, now %6)}4">,
 DefaultFatal;
 def err_fe_pch_file_overridden : Error<
@@ -31,19 +31,19 @@ def note_module_cache_path : Note<
 "after modifying system headers, please delete the module cache at '%0'">;
 
 def err_ast_file_targetopt_mismatch : Error<
-"AST file '%0' was compiled for the %1 '%2' but the current translation "
+"precompiled file '%0' was compiled for the %1 '%2' but the current 
translation "
 "unit is being compiled for target '%3'">;
 def err_ast_file_targetopt_feature_mismatch : Error<
-"%select{AST file '%1' was|current translation unit is}0 compiled with the 
target "
-"feature '%2' but the %select{current translation unit is|AST file '%1' 
was}0 "
+"%select{precompiled file '%1' was|current translation unit is}0 compiled 
with the target "
+"feature '%2' but the %select{current translation unit is|precompiled file 
'%1' was}0 "
 "not">;
 def err_ast_file_langopt_mismatch : Error<"%0 was %select{disabled|enabled}1 
in "
-"AST file '%3' but is currently %select{disabled|enabled}2">;
+"precompiled file '%3' but is currently %select{disabled|enabled}2">;
 def err_ast_file_langopt_value_mismatch : Error<
-  "%0 differs in AST file '%1' vs. current file">;
+  "%0 differs in precompiled file '%1' vs. current file">;
 def err_ast_file_diagopt_mismatch : Error<"%0 is currently enabled, but was 
not in "
-  "the AST file '%1'">;
-def err_ast_file_modulecache_mismatch : Error<"AST file '%2' was compiled with 
module cache "
+  "the precompiled file '%1'">;
+def err_ast_file_modulecache_mismatch : Error<"precompiled file '%2' was 
compiled with module cache "
   "path '%0', but the path is currently '%1'">;
 def warn_pch_vfsoverlay_mismatch : Warning<
   "PCH was compiled with different VFS overlay files than are currently in 
use">,
@@ -52,27 +52,27 @@ def note_pch_vfsoverlay_files : Note<"%select{PCH|current 
translation unit}0 has
 def note_pch_vfsoverlay_empty : Note<"%select{PCH|current translation unit}0 
has no VFS overlays">;
 
 def err_ast_file_version_too_old : Error<
-"%select{PCH|module|AST}0 file '%1' uses an older format that is no longer 
supported">;
+"%select{PCH|module|precompiled}0 file '%1' uses an older format that is 
no longer supported">;
 def err_ast_file_version_too_new : Error<
-"%select{PCH|module|AST}0 file '%1' uses a newer format that cannot be 
read">;
+"%select{PCH|module|precompiled }0 file '%1' uses a newer format that 
cannot be read">;
 def err_ast_file_different_branch : Error<
-"%select{PCH|module|AST}0 file '%1' built

[clang] [clang][modules] rename "AST" to precompiled in diagnostic messages NFCI (PR #142635)

2025-06-03 Thread Jan Svoboda via cfe-commits

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


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


[clang] [clang][Sema] Refine unused-member-function diagnostic message for constructors (PR #84515)

2025-06-03 Thread Aaron Ballman via cfe-commits


@@ -402,7 +402,7 @@ def warn_unused_function : Warning<"unused function %0">,
   InGroup, DefaultIgnore;
 def warn_unused_template : Warning<"unused %select{function|variable}0 
template %1">,
   InGroup, DefaultIgnore;
-def warn_unused_member_function : Warning<"unused member function %0">,
+def warn_unused_member_function : Warning<"unused %select{constructor|member 
function %1}0">,

AaronBallman wrote:

> However, note that only default constructors are considered “special members” 
> (see CXXSpecialMemberKind).

It supports more than just a default constructor:
https://github.com/llvm/llvm-project/blob/d0fb83531b07f608da064ed98e6213f32a5544e9/clang/include/clang/Sema/Sema.h#L422

So I was thinking something more like:
```
def warn_unused_member_function : Warning<
  "unused %select{member function %1|%sub{select_special_member_kind}1}0">,
  InGroup, DefaultIgnore;
```
and
```
DefaultedFunctionKind DFK = getDefaultedFunctionKind(DiagD);
if (DFK.isSpecialMember())
  Diag(DiagD->getLocation(), diag::warn_unused_member_function) << /*special 
member*/1 << DFK.asSpecialMember()) << DiagRange;
else if (isa(DiagD))
  Diag(DiagD->getLocation(), diag::warn_unused_member_function) << /*member*/0 
<< DiagD << DiagRange;
else
  Diag(DiagD->getLocation(), diag::warn_unused_function) << DiagD << DiagRange;
```

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


[clang] [clang][AST] Reduce some AST node size. (PR #142585)

2025-06-03 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/142585

>From b6b83987f117ed037fb4de4fc5be7740bab295e1 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 3 Jun 2025 08:42:37 +0200
Subject: [PATCH] [clang][AST] Reduce AST node size

---
 clang/include/clang/AST/Expr.h| 28 
 clang/include/clang/AST/ExprCXX.h | 74 +++--
 clang/include/clang/AST/Stmt.h| 78 +++
 clang/include/clang/AST/StmtCXX.h |  2 +-
 clang/lib/AST/Expr.cpp|  7 +-
 clang/lib/AST/ExprCXX.cpp |  3 +-
 clang/lib/Serialization/ASTReaderStmt.cpp | 14 ++--
 clang/lib/Serialization/ASTWriterStmt.cpp |  6 +-
 8 files changed, 147 insertions(+), 65 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 87bb9df9cef8f..43c28c8bf649f 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4579,7 +4579,6 @@ class ShuffleVectorExpr : public Expr {
   // indices.  The number of values in this list is always
   // 2+the number of indices in the vector type.
   Stmt **SubExprs;
-  unsigned NumExprs;
 
 public:
   ShuffleVectorExpr(const ASTContext &C, ArrayRef args, QualType Type,
@@ -4605,25 +4604,28 @@ class ShuffleVectorExpr : public Expr {
   /// getNumSubExprs - Return the size of the SubExprs array.  This includes 
the
   /// constant expression, the actual arguments passed in, and the function
   /// pointers.
-  unsigned getNumSubExprs() const { return NumExprs; }
+  unsigned getNumSubExprs() const { return ShuffleVectorExprBits.NumExprs; }
 
   /// Retrieve the array of expressions.
   Expr **getSubExprs() { return reinterpret_cast(SubExprs); }
 
   /// getExpr - Return the Expr at the specified index.
   Expr *getExpr(unsigned Index) {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
   const Expr *getExpr(unsigned Index) const {
-assert((Index < NumExprs) && "Arg access out of range!");
+assert((Index < ShuffleVectorExprBits.NumExprs) &&
+   "Arg access out of range!");
 return cast(SubExprs[Index]);
   }
 
   void setExprs(const ASTContext &C, ArrayRef Exprs);
 
   llvm::APSInt getShuffleMaskIdx(unsigned N) const {
-assert((N < NumExprs - 2) && "Shuffle idx out of range!");
+assert((N < ShuffleVectorExprBits.NumExprs - 2) &&
+   "Shuffle idx out of range!");
 assert(isa(getExpr(N + 2)) &&
"Index expression must be a ConstantExpr");
 return cast(getExpr(N + 2))->getAPValueResult().getInt();
@@ -4631,10 +4633,12 @@ class ShuffleVectorExpr : public Expr {
 
   // Iterators
   child_range children() {
-return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
+return child_range(&SubExprs[0],
+   &SubExprs[0] + ShuffleVectorExprBits.NumExprs);
   }
   const_child_range children() const {
-return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
+return const_child_range(&SubExprs[0],
+ &SubExprs[0] + ShuffleVectorExprBits.NumExprs);
   }
 };
 
@@ -4776,13 +4780,13 @@ class ChooseExpr : public Expr {
   enum { COND, LHS, RHS, END_EXPR };
   Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
   SourceLocation BuiltinLoc, RParenLoc;
-  bool CondIsTrue;
+
 public:
   ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
  ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
  bool condIsTrue)
-  : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
-CondIsTrue(condIsTrue) {
+  : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP) {
+ChooseExprBits.CondIsTrue = condIsTrue;
 SubExprs[COND] = cond;
 SubExprs[LHS] = lhs;
 SubExprs[RHS] = rhs;
@@ -4798,9 +4802,9 @@ class ChooseExpr : public Expr {
   bool isConditionTrue() const {
 assert(!isConditionDependent() &&
"Dependent condition isn't true or false");
-return CondIsTrue;
+return ChooseExprBits.CondIsTrue;
   }
-  void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
+  void setIsConditionTrue(bool isTrue) { ChooseExprBits.CondIsTrue = isTrue; }
 
   bool isConditionDependent() const {
 return getCond()->isTypeDependent() || getCond()->isValueDependent();
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 6ed049c915481..4c9636f990db0 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -2974,10 +2974,6 @@ class TypeTraitExpr final
 ///   __array_extent(int[10][20], 1) == 20
 /// \endcode
 class ArrayTypeTraitExpr : public Expr {
-  /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
-  LLVM_PREFERRED_TYPE(ArrayTypeTrait)
-  unsigned ATT : 2;
-
   /// The value of the type 

[clang] [clang][modules] rename "AST" to precompiled in diagnostic messages NFCI (PR #142635)

2025-06-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Cyndy Ishida (cyndyishida)


Changes

As follow up to: 
https://github.com/llvm/llvm-project/commit/883130e33325282cfd31b68f5db52891442c20b7
 

---

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


15 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSerializationKinds.td (+27-27) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+6-5) 
- (modified) clang/test/Modules/check-for-sanitizer-feature.cpp (+1-1) 
- (modified) clang/test/Modules/cxx20-force-check-input.cppm (+2-2) 
- (modified) clang/test/Modules/explicit-build.cpp (+2-2) 
- (modified) clang/test/Modules/fatal-module-loader-error.m (+2-2) 
- (modified) clang/test/Modules/ignored_macros.m (+1-1) 
- (modified) clang/test/Modules/load_failure.c (+1-1) 
- (modified) clang/test/Modules/merge-target-features.cpp (+3-3) 
- (modified) clang/test/Modules/mismatch-diagnostics.cpp (+1-1) 
- (modified) clang/test/Modules/module-imported-by-pch-path.m (+1-1) 
- (modified) clang/test/Modules/module-pch-different-cache-path.c (+2-2) 
- (modified) clang/test/Modules/pr62359.cppm (+2-2) 
- (modified) clang/test/Modules/resolution-change.m (+2-2) 
- (modified) clang/test/PCH/module-hash-difference.m (+1-1) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 93e31c8155ffc..584c8d62280bf 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -13,13 +13,13 @@ def err_fe_unable_to_read_pch_file : Error<
 "unable to read PCH file %0: '%1'">;
 def err_fe_not_a_pch_file : Error<
 "input is not a PCH file: '%0'">;
-def err_fe_pch_malformed : Error<
-"malformed or corrupted AST file: '%0'">, DefaultFatal;
+def err_fe_ast_file_malformed : Error<
+"malformed or corrupted precompiled file: '%0'">, DefaultFatal;
 def err_fe_pch_malformed_block : Error<
 "malformed block record in PCH file: '%0'">, DefaultFatal;
 def err_fe_ast_file_modified : Error<
 "file '%0' has been modified since the "
-"%select{precompiled header|module file|AST file}1 '%2' was built"
+"%select{precompiled header|module file|precompiled file}1 '%2' was built"
 ": %select{size|mtime|content}3 changed%select{| (was %5, now %6)}4">,
 DefaultFatal;
 def err_fe_pch_file_overridden : Error<
@@ -31,19 +31,19 @@ def note_module_cache_path : Note<
 "after modifying system headers, please delete the module cache at '%0'">;
 
 def err_ast_file_targetopt_mismatch : Error<
-"AST file '%0' was compiled for the %1 '%2' but the current translation "
+"precompiled file '%0' was compiled for the %1 '%2' but the current 
translation "
 "unit is being compiled for target '%3'">;
 def err_ast_file_targetopt_feature_mismatch : Error<
-"%select{AST file '%1' was|current translation unit is}0 compiled with the 
target "
-"feature '%2' but the %select{current translation unit is|AST file '%1' 
was}0 "
+"%select{precompiled file '%1' was|current translation unit is}0 compiled 
with the target "
+"feature '%2' but the %select{current translation unit is|precompiled file 
'%1' was}0 "
 "not">;
 def err_ast_file_langopt_mismatch : Error<"%0 was %select{disabled|enabled}1 
in "
-"AST file '%3' but is currently %select{disabled|enabled}2">;
+"precompiled file '%3' but is currently %select{disabled|enabled}2">;
 def err_ast_file_langopt_value_mismatch : Error<
-  "%0 differs in AST file '%1' vs. current file">;
+  "%0 differs in precompiled file '%1' vs. current file">;
 def err_ast_file_diagopt_mismatch : Error<"%0 is currently enabled, but was 
not in "
-  "the AST file '%1'">;
-def err_ast_file_modulecache_mismatch : Error<"AST file '%2' was compiled with 
module cache "
+  "the precompiled file '%1'">;
+def err_ast_file_modulecache_mismatch : Error<"precompiled file '%2' was 
compiled with module cache "
   "path '%0', but the path is currently '%1'">;
 def warn_pch_vfsoverlay_mismatch : Warning<
   "PCH was compiled with different VFS overlay files than are currently in 
use">,
@@ -52,27 +52,27 @@ def note_pch_vfsoverlay_files : Note<"%select{PCH|current 
translation unit}0 has
 def note_pch_vfsoverlay_empty : Note<"%select{PCH|current translation unit}0 
has no VFS overlays">;
 
 def err_ast_file_version_too_old : Error<
-"%select{PCH|module|AST}0 file '%1' uses an older format that is no longer 
supported">;
+"%select{PCH|module|precompiled}0 file '%1' uses an older format that is 
no longer supported">;
 def err_ast_file_version_too_new : Error<
-"%select{PCH|module|AST}0 file '%1' uses a newer format that cannot be 
read">;
+"%select{PCH|module|precompiled }0 file '%1' uses a newer format that 
cannot be read">;
 def err_ast_file_different_branch : Error<
-"%select{PCH|module|AST}0 file '%

[clang] [llvm] [RISCV] Add SiFive X390 processor definition (PR #142517)

2025-06-03 Thread Min-Yih Hsu via cfe-commits


@@ -290,7 +290,51 @@ def SIFIVE_X280 : RISCVProcessorModel<"sifive-x280", 
SiFive7Model,
FeatureStdExtZvfh,
FeatureStdExtZba,
FeatureStdExtZbb],
-  SiFiveX280TuneFeatures>;
+  SiFiveIntelligenceTuneFeatures>;
+
+def SIFIVE_X390 : RISCVProcessorModel<"sifive-x390", NoSchedModel,
+  [Feature64Bit,

mshockwave wrote:

Unfortunately it lacks Zicclsm (misaligned load/store), which is part of 
RVA20U64 and subsequent profiles.

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


[clang] [ubsan] Add more -fsanitize-annotate-debug-info checks (PR #141997)

2025-06-03 Thread Thurston Dang via cfe-commits


@@ -2817,7 +2817,9 @@ void CodeGenFunction::EmitVTablePtrCheckForCall(const 
CXXRecordDecl *RD,
 RD = LeastDerivedClassWithSameLayout(RD);
 
   auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
-  ApplyDebugLocation ApplyTrapDI(*this, SanitizerAnnotateDebugInfo(Ordinal));
+  ApplyDebugLocation ApplyTrapDI(

thurstond wrote:

Fixed in 
https://github.com/llvm/llvm-project/pull/141997/commits/ff5ffbf9d4ad126d21147b818629c9bb01f1e90d

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


[clang] [llvm] [PowerPC] frontend get target feature from backend with cpu name (PR #137670)

2025-06-03 Thread Fangrui Song via cfe-commits


@@ -16,6 +16,7 @@
 
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/MC/MCSubtargetInfo.h"

MaskRay wrote:

@diggerlin This is blocking and should be addressed before landing.

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


[clang] [Clang] Separate implicit int conversion on negation sign to new diagnostic group (PR #139429)

2025-06-03 Thread Steven Wu via cfe-commits


@@ -352,6 +352,10 @@ Improvements to Clang's diagnostics
 - Now correctly diagnose a tentative definition of an array with static
   storage duration in pedantic mode in C. (#GH50661)
 
+- Split diagnosis of implicit integer comparison on negation to a new
+  diagnostic group ``-Wimplicit-int-comparison-on-negation``, grouped under

cachemeifyoucan wrote:

typo here: it spells `-Wimplicit-int-conversion-on-negation` in the actual 
implementation 

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


[clang] [HLSL][SPIRV] Add vk::constant_id attribute. (PR #142638)

2025-06-03 Thread Steven Perron via cfe-commits

https://github.com/s-perron created 
https://github.com/llvm/llvm-project/pull/142638

The vk::constant_id attribute is used to indicate that a global const variable
represents a specialization constant in SPIR-V. This PR adds this
attribute to clang.

The documetation for the attribute is 
[here](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/SPIR-V.rst#specialization-constants).

Fixes #142448


>From 022bc4d031ea1655b82dc701fff315abd002ca15 Mon Sep 17 00:00:00 2001
From: Steven Perron 
Date: Fri, 30 May 2025 12:32:21 -0400
Subject: [PATCH] [HLSL][SPIRV] Add vk::constant_id attribute.

The vk::constant_id attribute is used to indicate that a global const variable
represents a specialization constant in SPIR-V. This PR adds this
attribute to clang.

The documetation for the attribute is 
[here](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/SPIR-V.rst#specialization-constants).

Fixes #142448
---
 clang/include/clang/Basic/Attr.td |  8 +++
 clang/include/clang/Basic/AttrDocs.td | 15 +
 .../clang/Basic/DiagnosticSemaKinds.td| 15 +
 clang/include/clang/Sema/SemaHLSL.h   |  3 +
 clang/lib/AST/ExprConstant.cpp|  5 ++
 clang/lib/Basic/Attributes.cpp|  3 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 23 +++
 clang/lib/Sema/SemaDecl.cpp   | 18 ++
 clang/lib/Sema/SemaDeclAttr.cpp   |  3 +
 clang/lib/Sema/SemaHLSL.cpp   | 61 ++-
 .../test/AST/HLSL/vk.spec-constnat.usage.hlsl | 12 
 .../SpirvType.alignment.hlsl  |  0
 .../SpirvType.hlsl|  0
 .../vk-features/vk.spec-constant.hlsl | 44 +
 .../SemaHLSL/vk.spec-constant.error1.hlsl | 39 
 15 files changed, 247 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/AST/HLSL/vk.spec-constnat.usage.hlsl
 rename clang/test/CodeGenHLSL/{inline-spirv => 
vk-features}/SpirvType.alignment.hlsl (100%)
 rename clang/test/CodeGenHLSL/{inline-spirv => vk-features}/SpirvType.hlsl 
(100%)
 create mode 100644 clang/test/CodeGenHLSL/vk-features/vk.spec-constant.hlsl
 create mode 100644 clang/test/SemaHLSL/vk.spec-constant.error1.hlsl

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index db02449a3dd12..51d1ddf80c65f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4949,6 +4949,14 @@ def HLSLWaveSize: InheritableAttr {
   let Documentation = [WaveSizeDocs];
 }
 
+def HLSLVkConstantId : InheritableAttr {
+  let Spellings = [CXX11<"vk", "constant_id">];
+  let Args = [IntArgument<"Id">];
+  let Subjects = SubjectList<[Var]>;
+  let LangOpts = [HLSL];
+  let Documentation = [VkConstantIdDocs];
+}
+
 def RandomizeLayout : InheritableAttr {
   let Spellings = [GCC<"randomize_layout">];
   let Subjects = SubjectList<[Record]>;
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 65d66dd398ad1..8ddf109b733c1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8195,6 +8195,21 @@ and 
https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html
   }];
 }
 
+def VkConstantIdDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The ``vk::constant_id`` attribute specify the id for a SPIR-V specialization
+constant. The attribute applies to const global scalar variables. The variable 
must be initialized with a C++11 constexpr.
+In SPIR-V, the
+variable will be replaced with an `OpSpecConstant` with the given id.
+The syntax is:
+
+.. code-block:: text
+
+  ``[[vk::constant_id()]] const T Name = ``
+}];
+}
+
 def RootSignatureDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index efc842bb4c42e..9214775246a15 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12888,6 +12888,21 @@ def err_spirv_enum_not_int : Error<
 def err_spirv_enum_not_valid : Error<
"invalid value for %select{storage class}0 argument">;
 
+def err_specialization_const_lit_init
+: Error<"variable with 'vk::constant_id' attribute cannot have an "
+"initializer that is not a constexpr">;
+def err_specialization_const_is_not_externally_visible
+: Error<"variable with 'vk::constant_id' attribute must be externally "
+"visible">;
+def err_specialization_const_missing_initializer
+: Error<
+  "variable with 'vk::constant_id' attribute must have an 
initializer">;
+def err_specialization_const_missing_const
+: Error<"variable with 'vk::constant_id' attribute must be const">;
+def err_specialization_const_is_not_int_or_float
+: Error<"variable with 'vk::constant_id' attribute must be an enum, bool,

[clang] [clang] Fixed Constant Evaluation don't Call Destructor (PR #140278)

2025-06-03 Thread via cfe-commits

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


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


[clang] [Clang] Fix crash on template-specialization (PR #142338)

2025-06-03 Thread Younan Zhang via cfe-commits


@@ -5120,6 +5121,10 @@ bool Sema::addInstantiatedParametersToScope(
   // Simple case: not a parameter pack.
   assert(FParamIdx < Function->getNumParams());
   ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
+  DeclarationName name = FunctionParam->getDeclName();
+  auto _ = llvm::make_scope_exit([&]() {
+FunctionParam->setDeclName(name);

zyn0217 wrote:

> I notice we have a `FunctionParam->setDeclName(PatternParam->getDeclName());` 
> not far below this point. Do we also need to apply a fix there?

No? Unless we allowed default arguments on parameter packs


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


[clang] [llvm] Non constant size and offset in DWARF (PR #141106)

2025-06-03 Thread Tom Tromey via cfe-commits

tromey wrote:

Rebased and adapted to the `LLVM_ABI` change.

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


[clang] [clang] Diagnose [[nodiscard]] return types in Objective-C++ (PR #142541)

2025-06-03 Thread John McCall via cfe-commits

https://github.com/rjmccall commented:

Generally LGTM, although I agree with requests above.

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


[clang-tools-extra] [clang-doc] [test] Generalize error message patterns (PR #142373)

2025-06-03 Thread Paul Kirth via cfe-commits

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

Thanks for pointing this out. I'll try to follow up later today w/ a less 
brittle check.

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


[clang-tools-extra] [clang-doc] [test] Generalize error message patterns (PR #142373)

2025-06-03 Thread Paul Kirth via cfe-commits

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


[clang] [AArch64] Add MSVC-style mangling for SVE types. (PR #141887)

2025-06-03 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

Ping

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


[clang-tools-extra] [clang-doc] [test] Generalize error message patterns (PR #142373)

2025-06-03 Thread Samarth Narang via cfe-commits

snarang181 wrote:

@ilovepi, for this check, should we just be looking for "clang doc error: " and 
remove the directory substring matching entirely?  

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


[clang-tools-extra] b76b3f3 - [clang-doc] Add test case for #141990 (#142209)

2025-06-03 Thread via cfe-commits

Author: Paul Kirth
Date: 2025-06-03T09:38:18-07:00
New Revision: b76b3f3b399d422bb7c07c86b8598652f1fb5668

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

LOG: [clang-doc] Add test case for #141990 (#142209)

When we landed the fix for the assertion in #141990, we hadn't yet
reduced the test case sufficiently for a regression test.

Added: 
clang-tools-extra/test/clang-doc/DR-141990.cpp

Modified: 


Removed: 




diff  --git a/clang-tools-extra/test/clang-doc/DR-141990.cpp 
b/clang-tools-extra/test/clang-doc/DR-141990.cpp
new file mode 100644
index 0..019afb0654c20
--- /dev/null
+++ b/clang-tools-extra/test/clang-doc/DR-141990.cpp
@@ -0,0 +1,18 @@
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: clang-doc -output=%t %s 2>&1 | FileCheck %s 
--implicit-check-not="{{warning|error}}"
+
+// COM: This case triggered an assertion before #141990:
+// COM: clang-doc: llvm-project/clang/lib/AST/Decl.cpp:2985:
+// COM:   Expr *clang::ParmVarDecl::getDefaultArg(): Assertion 
`!hasUninstantiatedDefaultArg()
+// COM:   && "Default argument is not yet instantiated!"' failed.
+
+template 
+class c;
+int e;
+
+template 
+class c {
+public:
+  void f(int n = e);
+};
+class B : c<> {};



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


[clang-tools-extra] [clang-doc] Add test case for #141990 (PR #142209)

2025-06-03 Thread Paul Kirth via cfe-commits

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


[clang] 9788521 - [clang] Don't evaluate the initializer of constexpr-unknown parameters. (#142498)

2025-06-03 Thread via cfe-commits

Author: Eli Friedman
Date: 2025-06-03T09:51:37-07:00
New Revision: 97885213bd4507b204b050c3cd570e365d21cc7d

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

LOG: [clang] Don't evaluate the initializer of constexpr-unknown parameters. 
(#142498)

If we see a parameter of reference type that isn't part of the frame,
don't try to evaluate its default argument. Just treat it as a
constexpr-unknown value.

Fixes #141114.  Fixes #141858.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-p2280r4.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index b20e2690d0eee..ab964e592de80 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -3550,7 +3550,12 @@ static bool evaluateVarDeclInit(EvalInfo &Info, const 
Expr *E,
   // should begin within the evaluation of E
   // Used to be C++20 [expr.const]p5.12.2:
   // ... its lifetime began within the evaluation of E;
-  if (isa(VD) && !AllowConstexprUnknown) {
+  if (isa(VD)) {
+if (AllowConstexprUnknown) {
+  Result = &Info.CurrentCall->createConstexprUnknownAPValues(VD, Base);
+  return true;
+}
+
 // Assume parameters of a potential constant expression are usable in
 // constant expressions.
 if (!Info.checkingPotentialConstantExpression() ||

diff  --git a/clang/test/SemaCXX/constant-expression-p2280r4.cpp 
b/clang/test/SemaCXX/constant-expression-p2280r4.cpp
index c14250a268f6c..50637917ba210 100644
--- a/clang/test/SemaCXX/constant-expression-p2280r4.cpp
+++ b/clang/test/SemaCXX/constant-expression-p2280r4.cpp
@@ -250,3 +250,15 @@ namespace uninit_reference_used {
   // expected-note {{in call to 'g5()'}}
 
 }
+
+namespace param_reference {
+  constexpr int arbitrary = -12345;
+  constexpr void f(const int &x = arbitrary) { // expected-note {{declared 
here}}
+constexpr const int &v1 = x; // expected-error {{must be initialized by a 
constant expression}} \
+// expected-note {{reference to 'x' is not a constant expression}}
+constexpr const int &v2 = (x, arbitrary); // expected-warning {{left 
operand of comma operator has no effect}}
+constexpr int v3 = x; // expected-error {{must be initialized by a 
constant expression}}
+static_assert(x==arbitrary); // expected-error {{static assertion 
expression is not an integral constant expression}}
+static_assert(&x - &x == 0);
+  }
+}



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


[clang] [clang] Don't evaluate the initializer of constexpr-unknown parameters. (PR #142498)

2025-06-03 Thread Eli Friedman via cfe-commits

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


[clang] [clang] Don't evaluate the initializer of constexpr-unknown parameters. (PR #142498)

2025-06-03 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

/cherry-pick 97885213bd4507b204b050c3cd570e365d21cc7d

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


[clang] [CIR][NFS] Fix missing return statement warning (PR #142591)

2025-06-03 Thread Henrich Lauko via cfe-commits

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


[clang] [CIR][NFS] Fix missing return statement warning (PR #142591)

2025-06-03 Thread Henrich Lauko via cfe-commits

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

lgtm

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


[clang] [llvm] [NFC][RootSignature] Move RootSignature util functions (PR #142491)

2025-06-03 Thread Finn Plummer via cfe-commits


@@ -0,0 +1,65 @@
+//===- HLSLRootSignatureUtils.h - HLSL Root Signature helpers 
-===//
+//
+// 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
+//
+//===--===//
+///
+/// \file This file contains helper obejcts for working with HLSL Root
+/// Signatures.
+///
+//===--===//
+
+#ifndef LLVM_FRONTEND_HLSL_HLSLROOTSIGNATUREUTILS_H
+#define LLVM_FRONTEND_HLSL_HLSLROOTSIGNATUREUTILS_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Frontend/HLSL/HLSLRootSignature.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace llvm {
+class LLVMContext;
+class MDNode;
+class Metadata;
+
+namespace hlsl {
+namespace rootsig {
+
+LLVM_ABI raw_ostream &operator<<(raw_ostream &OS,
+ const DescriptorTableClause &Clause);
+
+LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DescriptorTable 
&Table);
+
+LLVM_ABI void dumpRootElements(raw_ostream &OS, ArrayRef 
Elements);
+
+class MetadataBuilder {

inbelic wrote:

Resolved offline.

I agree with this but I think it doesn't outweigh the negatives of having to 
move all commonly used functions to be public. And we don't get any linking 
benefits.

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


[clang-tools-extra] a568617 - [clang-doc] Reenable time trace support (#141139)

2025-06-03 Thread via cfe-commits

Author: Paul Kirth
Date: 2025-06-03T09:56:25-07:00
New Revision: a56861777a7a584842c27cbc82e2355ded744c0e

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

LOG: [clang-doc] Reenable time trace support (#141139)

This patch re-enables -ftime-trace support in clang-doc. Initial support
in #97644 was reverted, and never relanded. This patch adds back the
command line option, and leverages the RAII tracing infrastructure more
thoroughly.

Added: 


Modified: 
clang-tools-extra/clang-doc/BitcodeReader.cpp
clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp
clang-tools-extra/clang-doc/Mapper.cpp
clang-tools-extra/clang-doc/Representation.cpp
clang-tools-extra/clang-doc/Representation.h
clang-tools-extra/clang-doc/tool/ClangDocMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp 
b/clang-tools-extra/clang-doc/BitcodeReader.cpp
index f8e338eb7c6ed..546dd0254ec01 100644
--- a/clang-tools-extra/clang-doc/BitcodeReader.cpp
+++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp
@@ -9,6 +9,7 @@
 #include "BitcodeReader.h"
 #include "llvm/ADT/IndexedMap.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 
@@ -672,6 +673,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, 
T I) {
 
 template <>
 llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) {
+  llvm::TimeTraceScope("Reducing infos", "readRecord");
   Record R;
   llvm::StringRef Blob;
   llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob);
@@ -683,6 +685,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, 
Reference *I) {
 // Read a block of records into a single info.
 template 
 llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) {
+  llvm::TimeTraceScope("Reducing infos", "readBlock");
   if (llvm::Error Err = Stream.EnterSubBlock(ID))
 return Err;
 
@@ -713,6 +716,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T 
I) {
 
 template 
 llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) {
+  llvm::TimeTraceScope("Reducing infos", "readSubBlock");
   switch (ID) {
   // Blocks can only have certain types of sub blocks.
   case BI_COMMENT_BLOCK_ID: {
@@ -819,6 +823,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned 
ID, T I) {
 
 ClangDocBitcodeReader::Cursor
 ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) {
+  llvm::TimeTraceScope("Reducing infos", "skipUntilRecordOrBlock");
   BlockOrRecordID = 0;
 
   while (!Stream.AtEndOfStream()) {
@@ -880,6 +885,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() {
 }
 
 llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() {
+  llvm::TimeTraceScope("Reducing infos", "readBlockInfoBlock");
   Expected> MaybeBlockInfo =
   Stream.ReadBlockInfoBlock();
   if (!MaybeBlockInfo)
@@ -895,6 +901,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() {
 template 
 llvm::Expected>
 ClangDocBitcodeReader::createInfo(unsigned ID) {
+  llvm::TimeTraceScope("Reducing infos", "createInfo");
   std::unique_ptr I = std::make_unique();
   if (auto Err = readBlock(ID, static_cast(I.get(
 return std::move(Err);
@@ -903,6 +910,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) {
 
 llvm::Expected>
 ClangDocBitcodeReader::readBlockToInfo(unsigned ID) {
+  llvm::TimeTraceScope("Reducing infos", "readBlockToInfo");
   switch (ID) {
   case BI_NAMESPACE_BLOCK_ID:
 return createInfo(ID);

diff  --git a/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp 
b/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp
index 65dc2e93582e8..8b7e4896c9fde 100644
--- a/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp
+++ b/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Mustache.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/TimeProfiler.h"
 
 using namespace llvm;
 using namespace llvm::json;
@@ -125,13 +126,18 @@ static Error setupTemplateFiles(const 
clang::doc::ClangDocContext &CDCtx) {
 Error MustacheHTMLGenerator::generateDocs(
 StringRef RootDir, StringMap> Infos,
 const clang::doc::ClangDocContext &CDCtx) {
-  if (auto Err = setupTemplateFiles(CDCtx))
-return Err;
+  {
+llvm::TimeTraceScope TS("Setup Templates");
+if (auto Err = setupTemplateFiles(CDCtx))
+  return Err;
+  }
+
   // Track which directories we already tried to create.
   StringSet<> CreatedDirs;
   // Collect all output by file name and create the necessary directories.
   StringMap> FileToInfos;
   for (const auto &Group : Infos) {
+llvm::TimeTraceScope TS("setup directories");
 doc::Info *Info = Group.getValue().get();
 
 SmallString<

[clang-tools-extra] [clang-doc] Reenable time trace support (PR #141139)

2025-06-03 Thread Paul Kirth via cfe-commits

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


[clang] [clang][Darwin] Simplify deployment version assignment in the Driver (PR #142013)

2025-06-03 Thread Steven Wu via cfe-commits


@@ -1938,11 +1942,22 @@ struct DarwinPlatform {
   SourceKind Kind;
   DarwinPlatformKind Platform;
   DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
-  VersionTuple NativeTargetVersion;
-  std::string OSVersion;
-  bool HasOSVersion = true, InferSimulatorFromArch = true;
+  // When compiling for a zippered target, this means both target &
+  // target variant is set on the command line, ZipperedOSVersion holds the
+  // OSVersion tied to the main target value.
+  VersionTuple ZipperedOSVersion;
+  // We allow multiple ways to set or default the OS
+  // version used for compilation. The ResolvedOSVersion always represents what
+  // will be used.
+  VersionTuple ResolvedOSVersion;

cachemeifyoucan wrote:

The only complaint now is I am not sure `ResolvedOSVersion` is a good name 
here, or maybe we can fix the implementation to make it a truly "resolved" 
version number. I don't like this is being initialized with being "resolved", 
you can get it before set it.

Ideally, I hope there is an explicit resolve function needs to be called before 
this is available.

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


[clang] [clang] Don't evaluate the initializer of constexpr-unknown parameters. (PR #142498)

2025-06-03 Thread via cfe-commits

llvmbot wrote:


Failed to cherry-pick: 97885213bd4507b204b050c3cd570e365d21cc7d

https://github.com/llvm/llvm-project/actions/runs/15423178980

Please manually backport the fix and push it to your github fork.  Once this is 
done, please create a [pull 
request](https://github.com/llvm/llvm-project/compare)

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


[clang] [llvm] [HLSL][SPIR-V] Implement vk::ext_builtin_input attribute (PR #138530)

2025-06-03 Thread Justin Bogner via cfe-commits
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= 
Message-ID:
In-Reply-To: 


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


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


[clang] [llvm] [HLSL][SPIR-V] Implement vk::ext_builtin_input attribute (PR #138530)

2025-06-03 Thread Justin Bogner via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 



@@ -140,6 +140,11 @@ def SharedVar : SubsetSubjecthasGlobalStorage() && !S->getTLSKind()}],
   "global variables">;
 
+def HLSLInputBuiltin : SubsetSubjecthasGlobalStorage() &&
+S->getStorageClass()==StorageClass::SC_Static &&
+S->getType().isConstQualified()}],
+ "static const globals">;

bogner wrote:

Spacing looks a little funny here. Did you know that clang-format (mostly) 
works on .td files? It's a bit tricky to use here since the file as a whole 
isn't clang-format clean, but I get the following:
```suggestion
def HLSLInputBuiltin
: SubsetSubjecthasGlobalStorage() &&
   S->getStorageClass() == StorageClass::SC_Static &&
   S->getType().isConstQualified()}],
"static const globals">;
```

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


[clang] 9ec5afe - [NFC][RootSignature] Move RootSignature util functions (#142491)

2025-06-03 Thread via cfe-commits

Author: Finn Plummer
Date: 2025-06-03T09:59:50-07:00
New Revision: 9ec5afea773783b73b575d397dfdc8fba1fd596b

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

LOG: [NFC][RootSignature] Move RootSignature util functions (#142491)

`HLSLRootSignature.h` was originally created to hold the struct
definitions of an `llvm::hlsl::rootsig::RootElement` and some helper
functions for it.

However, there many users of the structs that don't require any of the
helper methods. This requires us to link the `FrontendHLSL` library,
where we otherwise wouldn't need to.

For instance:
- This [revert](https://github.com/llvm/llvm-project/pull/142005) was
required as it requires linking to the unrequired `FrontendHLSL` library
- As part of the change required here:
https://github.com/llvm/llvm-project/issues/126557. We will want to add
an `HLSLRootSignatureVersion` enum. Ideally this could live with the
root signature struct defs, but we don't want to link the helper objects
into `clang/Basic/TargetOptions.h`

This change allows the struct definitions to be kept in a single header
file and to then have the `FrontendHLSL` library only be linked when
required.

Added: 
llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp

Modified: 
clang/lib/AST/TextNodeDumper.cpp
clang/lib/CodeGen/CGHLSLRuntime.cpp
llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h
llvm/lib/Frontend/HLSL/CMakeLists.txt
llvm/unittests/Frontend/HLSLRootSignatureDumpTest.cpp

Removed: 
llvm/lib/Frontend/HLSL/HLSLRootSignature.cpp



diff  --git a/clang/lib/AST/TextNodeDumper.cpp 
b/clang/lib/AST/TextNodeDumper.cpp
index 112e902dfb374..1b84b8824047b 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -24,7 +24,7 @@
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TypeTraits.h"
 #include "llvm/ADT/StringExtras.h"
-#include "llvm/Frontend/HLSL/HLSLRootSignature.h"
+#include "llvm/Frontend/HLSL/HLSLRootSignatureUtils.h"
 
 #include 
 #include 

diff  --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index cfe9dc1192d9d..dbfdd0e1ecfbb 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -23,6 +23,7 @@
 #include "clang/AST/Type.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Frontend/HLSL/HLSLRootSignatureUtils.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/GlobalVariable.h"

diff  --git a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h 
b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h
index ca383a828b5cc..2f028817b45b6 100644
--- a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h
+++ b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h
@@ -6,25 +6,19 @@
 //
 
//===--===//
 ///
-/// \file This file contains helper objects for working with HLSL Root
-/// Signatures.
+/// \file This file contains structure definitions of HLSL Root Signature
+/// objects.
 ///
 
//===--===//
 
 #ifndef LLVM_FRONTEND_HLSL_HLSLROOTSIGNATURE_H
 #define LLVM_FRONTEND_HLSL_HLSLROOTSIGNATURE_H
 
-#include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/DXILABI.h"
-#include "llvm/Support/raw_ostream.h"
 #include 
 
 namespace llvm {
-class LLVMContext;
-class MDNode;
-class Metadata;
-
 namespace hlsl {
 namespace rootsig {
 
@@ -195,8 +189,6 @@ struct DescriptorTable {
   uint32_t NumClauses = 0;
 };
 
-LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DescriptorTable 
&Table);
-
 static const uint32_t NumDescriptorsUnbounded = 0x;
 static const uint32_t DescriptorTableOffsetAppend = 0x;
 // Models DTClause : CBV | SRV | UAV | Sampler, by collecting like parameters
@@ -225,9 +217,6 @@ struct DescriptorTableClause {
   }
 };
 
-LLVM_ABI raw_ostream &operator<<(raw_ostream &OS,
- const DescriptorTableClause &Clause);
-
 struct StaticSampler {
   Register Reg;
   SamplerFilter Filter = SamplerFilter::Anisotropic;
@@ -264,32 +253,6 @@ using RootElement =
 std::variant;
 
-LLVM_ABI void dumpRootElements(raw_ostream &OS, ArrayRef 
Elements);
-
-class MetadataBuilder {
-public:
-  MetadataBuilder(llvm::LLVMContext &Ctx, ArrayRef Elements)
-  : Ctx(Ctx), Elements(Elements) {}
-
-  /// Iterates through the elements and dispatches onto the correct Build 
method
-  ///
-  /// Accumulates the root signature and returns the Metadata node that is just
-  /// a list of all the elements
-  LLVM_ABI MDNode *BuildRootSignature();
-
-private:
-  /// Define the vario

[clang] [llvm] [NFC][RootSignature] Move RootSignature util functions (PR #142491)

2025-06-03 Thread Finn Plummer via cfe-commits

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


[clang] [llvm] [HLSL][SPIR-V] Implement vk::ext_builtin_input attribute (PR #138530)

2025-06-03 Thread Nathan Gauër via cfe-commits


@@ -554,6 +554,19 @@ static void initializeBufferFromBinding(CodeGenModule &CGM,
Args);
 }
 
+void CGHLSLRuntime::handleGlobalVarDefinition(const VarDecl *VD,
+  llvm::GlobalVariable *GV) {
+  if (auto Attr = VD->getAttr()) {
+LLVMContext &Ctx = GV->getContext();
+IRBuilder<> B(GV->getContext());
+MDNode *Operands = MDNode::get(
+Ctx, {ConstantAsMetadata::get(B.getInt32(11)),

Keenuts wrote:

Will do (11 is the `Spirv::Decoration::Builtin` operand)

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


[clang] [alpha.webkit.UncheckedCallArgsChecker] Forwarding r-value reference should not result in a warning (PR #142471)

2025-06-03 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated 
https://github.com/llvm/llvm-project/pull/142471

>From e915af753e5d51afea1b313adea4d89ecd5e678d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 2 Jun 2025 13:58:50 -0600
Subject: [PATCH 1/2] [alpha.webkit.UncheckedCallArgsChecker] Forwarding
 r-value reference should not result in a warning

This PR fixes the bug that the checker emits a warning when a function takes 
T&& and passes it to
another function using std::move. We should treat std::move like any other 
pointer conversion and
the origin of the pointer to be that of the argument.
---
 .../Checkers/WebKit/ASTUtils.cpp  |  5 
 .../Checkers/WebKit/call-args-checked.cpp | 23 +++
 2 files changed, 28 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index f087fc8fa19fd..7dedb8f8f6766 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -118,6 +118,11 @@ bool tryToFindPtrOrigin(
   }
 }
   }
+  
+  if (call->isCallToStdMove() && call->getNumArgs() == 1) {
+E = call->getArg(0)->IgnoreParenCasts();
+continue;
+  }
 
   if (auto *callee = call->getDirectCallee()) {
 if (isCtorOfSafePtr(callee)) {
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-checked.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-checked.cpp
index e24b04dcd3cf9..c938ba5f7de46 100644
--- a/clang/test/Analysis/Checkers/WebKit/call-args-checked.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-checked.cpp
@@ -2,6 +2,20 @@
 
 #include "mock-types.h"
 
+namespace std {
+
+template  struct remove_reference {
+  typedef T type;
+};
+
+template  struct remove_reference {
+  typedef T type;
+};
+
+template typename remove_reference::type&& move(T&& t);
+
+} // namespace std
+
 RefCountableAndCheckable* makeObj();
 CheckedRef makeObjChecked();
 void someFunction(RefCountableAndCheckable*);
@@ -54,3 +68,12 @@ void foo() {
 }
 
 }
+
+namespace call_with_std_move {
+
+void consume(CheckedObj&&);
+void foo(CheckedObj&& obj) {
+  consume(std::move(obj));
+}
+
+}

>From 73c949dc119ac458663f6c31d4a859c6528f7986 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Tue, 3 Jun 2025 10:53:14 -0600
Subject: [PATCH 2/2] Fix formatting

---
 clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 7dedb8f8f6766..81fca5d719b4d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -118,7 +118,7 @@ bool tryToFindPtrOrigin(
   }
 }
   }
-  
+
   if (call->isCallToStdMove() && call->getNumArgs() == 1) {
 E = call->getArg(0)->IgnoreParenCasts();
 continue;

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


[clang] [clang][CGObjC] Sign the v-table pointer in ObjC exception RTTI. (PR #135562)

2025-06-03 Thread John McCall via cfe-commits


@@ -7676,10 +7676,26 @@ CGObjCNonFragileABIMac::GetInterfaceEHType(const 
ObjCInterfaceDecl *ID,
   }
 
   llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
+  llvm::Constant *VTablePtr = llvm::ConstantExpr::getInBoundsGetElementPtr(
+  VTableGV->getValueType(), VTableGV, VTableIdx);
+
   ConstantInitBuilder builder(CGM);
   auto values = builder.beginStruct(ObjCTypes.EHTypeTy);
-  values.add(llvm::ConstantExpr::getInBoundsGetElementPtr(
-  VTableGV->getValueType(), VTableGV, VTableIdx));
+
+  if (auto &Schema =
+  CGM.getCodeGenOpts().PointerAuth.CXXTypeInfoVTablePointer) {
+uint32_t discrimination = 0;
+if (Schema.hasOtherDiscrimination()) {
+  assert(Schema.getOtherDiscrimination() ==
+ PointerAuthSchema::Discrimination::Constant);
+  discrimination = Schema.getConstantDiscrimination();
+}
+values.addSignedPointer(
+VTablePtr, Schema.getKey(), Schema.isAddressDiscriminated(),
+llvm::ConstantInt::get(CGM.IntPtrTy, discrimination));

rjmccall wrote:

I think you can just call the `addSignedPointer` variant that takes a schema 
and pass null values for the decl and type.

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


[clang] [llvm] [AArch64TargetParser]Fix reconstructFromParsedFeatures ignoring negative features (PR #142236)

2025-06-03 Thread Matthias Braun via cfe-commits

https://github.com/MatzeB updated 
https://github.com/llvm/llvm-project/pull/142236

>From 92da4def0f7c39a6348669387cfc874ee03f8471 Mon Sep 17 00:00:00 2001
From: Matthias Braun 
Date: Fri, 30 May 2025 16:19:16 -0700
Subject: [PATCH 1/2] [AArch64TargetParser]Fix reconstructFromParsedFeatures
 ignoring negative features

The `targetFeatureToExtension` function used by
reconstructFromParsedFeatures only found positive `+FEATURE` strings,
but not negative `-FEATURE` strings. Extend the function to handle both
to fix `reconstructFromParsedFeatures`.
---
 llvm/lib/TargetParser/AArch64TargetParser.cpp|  5 +++--
 llvm/unittests/TargetParser/TargetParserTest.cpp | 16 
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/TargetParser/AArch64TargetParser.cpp 
b/llvm/lib/TargetParser/AArch64TargetParser.cpp
index e13c6e6d28c2b..4a2523440f0f0 100644
--- a/llvm/lib/TargetParser/AArch64TargetParser.cpp
+++ b/llvm/lib/TargetParser/AArch64TargetParser.cpp
@@ -60,7 +60,7 @@ uint64_t AArch64::getFMVPriority(ArrayRef 
Features) {
   ExtensionSet FeatureBits;
   for (const StringRef Feature : Features) {
 std::optional FMV = parseFMVExtension(Feature);
-if (!FMV) {
+if (!FMV && Feature.starts_with('+')) {
   if (std::optional Info = 
targetFeatureToExtension(Feature))
 FMV = lookupFMVByID(Info->ID);
 }
@@ -181,7 +181,8 @@ std::optional 
AArch64::parseFMVExtension(StringRef FMVExt) {
 std::optional
 AArch64::targetFeatureToExtension(StringRef TargetFeature) {
   for (const auto &E : Extensions)
-if (TargetFeature == E.PosTargetFeature)
+if (TargetFeature == E.PosTargetFeature ||
+TargetFeature == E.NegTargetFeature)
   return E;
   return {};
 }
diff --git a/llvm/unittests/TargetParser/TargetParserTest.cpp 
b/llvm/unittests/TargetParser/TargetParserTest.cpp
index f4c93334ac682..468ef57cb5b9b 100644
--- a/llvm/unittests/TargetParser/TargetParserTest.cpp
+++ b/llvm/unittests/TargetParser/TargetParserTest.cpp
@@ -1831,6 +1831,22 @@ TEST_P(AArch64ExtensionDependenciesBaseCPUTestFixture,
   }
 }
 
+TEST(TargetParserTest, testAArch64ReconstructFromParsedFeatures) {
+  AArch64::ExtensionSet Extensions;
+  std::vector FeatureOptions = {
+  "-sve2", "-Baz", "+sve", "+FooBar", "+sve2", "+neon", "-sve",
+  };
+  std::vector NonExtensions;
+  Extensions.reconstructFromParsedFeatures(FeatureOptions, NonExtensions);
+
+  std::vector NonExtensionsExpected = {"-Baz", "+FooBar"};
+  ASSERT_THAT(NonExtensions, testing::ContainerEq(NonExtensionsExpected));
+  std::vector Features;
+  Extensions.toLLVMFeatureList(Features);
+  std::vector FeaturesExpected = {"+sve2", "+neon", "-sve"};
+  ASSERT_THAT(FeaturesExpected, testing::ContainerEq(FeaturesExpected));
+}
+
 AArch64ExtensionDependenciesBaseArchTestParams
 AArch64ExtensionDependenciesArchData[] = {
 // Base architecture features

>From 34d6e7f35e146cfaad63fe49133a326b6b180953 Mon Sep 17 00:00:00 2001
From: Matthias Braun 
Date: Tue, 3 Jun 2025 10:06:51 -0700
Subject: [PATCH 2/2] Add a test on the clang side as well

---
 clang/test/CodeGen/aarch64-always-inline-feature-bug.c | 8 
 1 file changed, 8 insertions(+)
 create mode 100644 clang/test/CodeGen/aarch64-always-inline-feature-bug.c

diff --git a/clang/test/CodeGen/aarch64-always-inline-feature-bug.c 
b/clang/test/CodeGen/aarch64-always-inline-feature-bug.c
new file mode 100644
index 0..27c3983c66d2b
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-always-inline-feature-bug.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple aarch64-- -target-feature +neon -target-feature 
+sve\
+// RUN:   -target-feature -sve -emit-llvm %s -o - | FileCheck %s
+
+// Reproducer for bug where clang would reject always_inline for unrelated
+// target features if they were disable with `-feature` on the command line.
+// CHECK: @bar
+__attribute__((always_inline)) __attribute__((target("neon"))) void foo() {}
+void bar() { foo(); }

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


[clang] [clang] Fixed Constant Evaluation don't Call Destructor (PR #140278)

2025-06-03 Thread via cfe-commits


@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only %s -verify
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only %s -verify 
-fexperimental-new-constant-interpreter
+
+namespace GH139818{
+struct A {
+  constexpr ~A() { ref = false; }
+  constexpr operator bool() {
+return b;
+  }
+  bool b;
+  bool& ref;
+};
+
+constexpr bool f1() {
+  bool ret = true;
+  for (bool b = false; A x{b, ret}; b = true) {}
+  return ret;
+}
+
+static_assert(!f1());
+
+struct Y {
+  constexpr ~Y() noexcept(false) { throw "oops"; }  // expected-error 
{{cannot use 'throw' with exceptions disabled}}

Mr-Anyone wrote:

I think I have updated it, thanks. 

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


[clang] [llvm] [AArch64TargetParser]Fix reconstructFromParsedFeatures ignoring negative features (PR #142236)

2025-06-03 Thread Matthias Braun via cfe-commits

MatzeB wrote:

Cannot test with `--print-enabled-extensions` as clang has its own logic to 
parse target features.

But I added a test based on the `always_inline` compatibility check logic that 
is close to the original issue we ran into.

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


[clang] [ubsan] Add more -fsanitize-annotate-debug-info checks (PR #141997)

2025-06-03 Thread Thurston Dang via cfe-commits


@@ -2817,7 +2817,9 @@ void CodeGenFunction::EmitVTablePtrCheckForCall(const 
CXXRecordDecl *RD,
 RD = LeastDerivedClassWithSameLayout(RD);
 
   auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
-  ApplyDebugLocation ApplyTrapDI(*this, SanitizerAnnotateDebugInfo(Ordinal));
+  ApplyDebugLocation ApplyTrapDI(

thurstond wrote:

Change reverted because it is already in SanitizerScope in some codepaths

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


[clang] [llvm] [HLSL][RootSignature] Metadata generation of StaticSampler (PR #142642)

2025-06-03 Thread Finn Plummer via cfe-commits

https://github.com/inbelic created 
https://github.com/llvm/llvm-project/pull/142642

Implements metadata generation of a Root Signature from its in-memory 
representation. It follows the same style as: 
https://github.com/llvm/llvm-project/pull/139633.

This pr handles `StaticSamplers`. It also handles converting the else-if chain 
into a `std::visit` to allow for future compiler warnings when adding 
additional `RootElement` variants.

The metadata follows the format described 
[here](https://github.com/llvm/wg-hlsl/blob/main/proposals/0002-root-signature-in-clang.md#metadata-schema).

- Implement `BuildStaticSampler` into HLSLRootSignature.h
- Add sample testcases demonstrating functionality

Note: there is no validation of metadata nodes as the 
`llvm::hlsl::rootsig::RootElement` that generates it will have already been 
validated.

Resolves https://github.com/llvm/llvm-project/issues/126586

>From 018378494bae2f93b9566439adc16f92bc82130c Mon Sep 17 00:00:00 2001
From: Finn Plummer 
Date: Mon, 2 Jun 2025 22:33:43 +
Subject: [PATCH 1/2] [HLSL][RootSignature] Metadata generation of
 StaticSampler

---
 clang/test/CodeGenHLSL/RootSignature.hlsl | 36 ++-
 .../Frontend/HLSL/HLSLRootSignatureUtils.h|  1 +
 .../Frontend/HLSL/HLSLRootSignatureUtils.cpp  | 33 +
 3 files changed, 69 insertions(+), 1 deletion(-)

diff --git a/clang/test/CodeGenHLSL/RootSignature.hlsl 
b/clang/test/CodeGenHLSL/RootSignature.hlsl
index 34caa3eb6b714..ca843ffbb1ced 100644
--- a/clang/test/CodeGenHLSL/RootSignature.hlsl
+++ b/clang/test/CodeGenHLSL/RootSignature.hlsl
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -emit-llvm -o - %s | 
FileCheck %s
 
 // CHECK: !dx.rootsignatures = !{![[#EMPTY_ENTRY:]], ![[#DT_ENTRY:]],
-// CHECK-SAME: ![[#RF_ENTRY:]], ![[#RC_ENTRY:]], ![[#RD_ENTRY:]]}
+// CHECK-SAME: ![[#RF_ENTRY:]], ![[#RC_ENTRY:]], ![[#RD_ENTRY:]], 
![[#SS_ENTRY:]]}
 
 // CHECK: ![[#EMPTY_ENTRY]] = !{ptr @EmptyEntry, ![[#EMPTY:]]}
 // CHECK: ![[#EMPTY]] = !{}
@@ -66,6 +66,40 @@ void RootConstantsEntry() {}
 [numthreads(1,1,1)]
 void RootDescriptorsEntry() {}
 
+// CHECK: ![[#SS_ENTRY]] = !{ptr @StaticSamplerEntry, ![[#SS_RS:]]}
+// CHECK: ![[#SS_RS]] = !{![[#STATIC_SAMPLER:]]}
+
+// checking filter = 0x4
+// CHECK: ![[#STATIC_SAMPLER]] = !{!"StaticSampler", i32 4,
+
+// checking texture address[U|V|W]
+// CHECK-SAME: i32 2, i32 3, i32 5,
+
+// checking mipLODBias, maxAnisotropy, comparisonFunc, borderColor
+// CHECK-SAME: float 0x40403999A000, i32 9, i32 3, i32 2,
+
+// checking minLOD, maxLOD
+// CHECK-SAME: float -1.28e+02, float 1.28e+02,
+
+// checking register, space and visibility
+// CHECK-SAME: i32 42, i32 0, i32 0}
+
+#define SampleStaticSampler \
+  "StaticSampler(s42, " \
+  " filter = FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, " \
+  " addressU = TEXTURE_ADDRESS_MIRROR, " \
+  " addressV = TEXTURE_ADDRESS_CLAMP, " \
+  " addressW = TEXTURE_ADDRESS_MIRRORONCE, " \
+  " mipLODBias = 32.45f, maxAnisotropy = 9, " \
+  " comparisonFunc = COMPARISON_EQUAL, " \
+  " borderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE, " \
+  " minLOD = -128.f, maxLOD = 128.f, " \
+  " space = 0, visibility = SHADER_VISIBILITY_ALL, " \
+  ")"
+[shader("compute"), RootSignature(SampleStaticSampler)]
+[numthreads(1,1,1)]
+void StaticSamplerEntry() {}
+
 // Sanity test to ensure no root is added for this function as there is only
 // two entries in !dx.roosignatures
 [shader("compute")]
diff --git a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h 
b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
index 365197a4dfdb5..6d959ad5bdc7f 100644
--- a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
+++ b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
@@ -52,6 +52,7 @@ class MetadataBuilder {
   MDNode *BuildRootDescriptor(const RootDescriptor &Descriptor);
   MDNode *BuildDescriptorTable(const DescriptorTable &Table);
   MDNode *BuildDescriptorTableClause(const DescriptorTableClause &Clause);
+  MDNode *BuildStaticSampler(const StaticSampler &Sampler);
 
   llvm::LLVMContext &Ctx;
   ArrayRef Elements;
diff --git a/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp 
b/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
index aa1f1957d9cbe..304660916a93c 100644
--- a/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
+++ b/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
@@ -182,6 +182,8 @@ MDNode *MetadataBuilder::BuildRootSignature() {
   ElementMD = BuildDescriptorTableClause(*Clause);
 else if (const auto &Table = std::get_if(&Element))
   ElementMD = BuildDescriptorTable(*Table);
+else if (const auto &Sampler = std::get_if(&Element))
+  ElementMD = BuildStaticSampler(*Sampler);
 
 // FIXME(#126586): remove once all RootElemnt variants are handled in a
 // visit or otherwise
@@ -274,6 +276,37 @@ MDNode *MetadataBuilder::BuildDescriptorTableClause(
});
 }
 
+MDNode *MetadataBuilder::BuildStaticSampler(cons

[clang] [llvm] [HLSL][RootSignature] Metadata generation of StaticSampler (PR #142642)

2025-06-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Finn Plummer (inbelic)


Changes

Implements metadata generation of a Root Signature from its in-memory 
representation. It follows the same style as: 
https://github.com/llvm/llvm-project/pull/139633.

This pr handles `StaticSamplers`. It also handles converting the else-if chain 
into a `std::visit` to allow for future compiler warnings when adding 
additional `RootElement` variants.

The metadata follows the format described 
[here](https://github.com/llvm/wg-hlsl/blob/main/proposals/0002-root-signature-in-clang.md#metadata-schema).

- Implement `BuildStaticSampler` into HLSLRootSignature.h
- Add sample testcases demonstrating functionality

Note: there is no validation of metadata nodes as the 
`llvm::hlsl::rootsig::RootElement` that generates it will have already been 
validated.

Resolves https://github.com/llvm/llvm-project/issues/126586

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


3 Files Affected:

- (modified) clang/test/CodeGenHLSL/RootSignature.hlsl (+35-1) 
- (modified) llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h (+1) 
- (modified) llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp (+66-16) 


``diff
diff --git a/clang/test/CodeGenHLSL/RootSignature.hlsl 
b/clang/test/CodeGenHLSL/RootSignature.hlsl
index 34caa3eb6b714..ca843ffbb1ced 100644
--- a/clang/test/CodeGenHLSL/RootSignature.hlsl
+++ b/clang/test/CodeGenHLSL/RootSignature.hlsl
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -emit-llvm -o - %s | 
FileCheck %s
 
 // CHECK: !dx.rootsignatures = !{![[#EMPTY_ENTRY:]], ![[#DT_ENTRY:]],
-// CHECK-SAME: ![[#RF_ENTRY:]], ![[#RC_ENTRY:]], ![[#RD_ENTRY:]]}
+// CHECK-SAME: ![[#RF_ENTRY:]], ![[#RC_ENTRY:]], ![[#RD_ENTRY:]], 
![[#SS_ENTRY:]]}
 
 // CHECK: ![[#EMPTY_ENTRY]] = !{ptr @EmptyEntry, ![[#EMPTY:]]}
 // CHECK: ![[#EMPTY]] = !{}
@@ -66,6 +66,40 @@ void RootConstantsEntry() {}
 [numthreads(1,1,1)]
 void RootDescriptorsEntry() {}
 
+// CHECK: ![[#SS_ENTRY]] = !{ptr @StaticSamplerEntry, ![[#SS_RS:]]}
+// CHECK: ![[#SS_RS]] = !{![[#STATIC_SAMPLER:]]}
+
+// checking filter = 0x4
+// CHECK: ![[#STATIC_SAMPLER]] = !{!"StaticSampler", i32 4,
+
+// checking texture address[U|V|W]
+// CHECK-SAME: i32 2, i32 3, i32 5,
+
+// checking mipLODBias, maxAnisotropy, comparisonFunc, borderColor
+// CHECK-SAME: float 0x40403999A000, i32 9, i32 3, i32 2,
+
+// checking minLOD, maxLOD
+// CHECK-SAME: float -1.28e+02, float 1.28e+02,
+
+// checking register, space and visibility
+// CHECK-SAME: i32 42, i32 0, i32 0}
+
+#define SampleStaticSampler \
+  "StaticSampler(s42, " \
+  " filter = FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, " \
+  " addressU = TEXTURE_ADDRESS_MIRROR, " \
+  " addressV = TEXTURE_ADDRESS_CLAMP, " \
+  " addressW = TEXTURE_ADDRESS_MIRRORONCE, " \
+  " mipLODBias = 32.45f, maxAnisotropy = 9, " \
+  " comparisonFunc = COMPARISON_EQUAL, " \
+  " borderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE, " \
+  " minLOD = -128.f, maxLOD = 128.f, " \
+  " space = 0, visibility = SHADER_VISIBILITY_ALL, " \
+  ")"
+[shader("compute"), RootSignature(SampleStaticSampler)]
+[numthreads(1,1,1)]
+void StaticSamplerEntry() {}
+
 // Sanity test to ensure no root is added for this function as there is only
 // two entries in !dx.roosignatures
 [shader("compute")]
diff --git a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h 
b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
index 365197a4dfdb5..6d959ad5bdc7f 100644
--- a/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
+++ b/llvm/include/llvm/Frontend/HLSL/HLSLRootSignatureUtils.h
@@ -52,6 +52,7 @@ class MetadataBuilder {
   MDNode *BuildRootDescriptor(const RootDescriptor &Descriptor);
   MDNode *BuildDescriptorTable(const DescriptorTable &Table);
   MDNode *BuildDescriptorTableClause(const DescriptorTableClause &Clause);
+  MDNode *BuildStaticSampler(const StaticSampler &Sampler);
 
   llvm::LLVMContext &Ctx;
   ArrayRef Elements;
diff --git a/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp 
b/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
index aa1f1957d9cbe..0a866374bf5dc 100644
--- a/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
+++ b/llvm/lib/Frontend/HLSL/HLSLRootSignatureUtils.cpp
@@ -169,25 +169,44 @@ void dumpRootElements(raw_ostream &OS, 
ArrayRef Elements) {
   OS << "}";
 }
 
+namespace {
+
+// We use the OverloadBuild with std::visit to ensure the compiler catches if a
+// new RootElement variant type is added but it's metadata generation isn't
+// handled.
+template  struct OverloadedBuild : Ts... {
+  using Ts::operator()...;
+};
+template  OverloadedBuild(Ts...) -> OverloadedBuild;
+
+} // namespace
+
 MDNode *MetadataBuilder::BuildRootSignature() {
+  const auto Visitor = OverloadedBuild{
+  [this](const RootFlags &Flags) -> MDNode * {
+return BuildRootFlags(Flags);
+  },
+  [this](const RootConstants &Constants) -> MDNode * {
+return BuildRootConstants(Con

[clang] [CIR] Upstream splat op for VectorType (PR #139827)

2025-06-03 Thread Amr Hesham via cfe-commits

https://github.com/AmrDeveloper updated 
https://github.com/llvm/llvm-project/pull/139827

>From bd7175f78a855add650201b93e87c09b70ccd1dc Mon Sep 17 00:00:00 2001
From: AmrDeveloper 
Date: Tue, 13 May 2025 21:35:06 +0200
Subject: [PATCH 1/3] [CIR] Upstream splat op for VectorType

---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  | 32 +
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp|  8 +++
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 56 
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   | 10 +++
 clang/test/CIR/CodeGen/vector-ext.cpp | 63 ++
 clang/test/CIR/CodeGen/vector.cpp | 65 ++-
 clang/test/CIR/IR/vector.cir  | 34 ++
 7 files changed, 267 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 237daed32532a..7b3cf3899c3c6 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -2194,4 +2194,36 @@ def VecShuffleDynamicOp : CIR_Op<"vec.shuffle.dynamic",
   let hasVerifier = 1;
 }
 
+//===--===//
+// VecSplatOp
+//===--===//
+
+def VecSplatOp : CIR_Op<"vec.splat", [Pure,
+  TypesMatchWith<"type of 'value' matches element type of 'result'", "result",
+ "value", "cast($_self).getElementType()">]> {
+
+  let summary = "Convert a scalar into a vector";
+  let description = [{
+The `cir.vec.splat` operation creates a vector value from a scalar value.
+All elements of the vector have the same value, that of the given scalar.
+
+It's a separate operation from `cir.vec.create` because more
+efficient LLVM IR can be generated for it, and because some optimization 
and
+analysis passes can benefit from knowing that all elements of the vector
+have the same value.
+
+```mlir
+%value = cir.const #cir.int<3> : !s32i
+%value_vec = cir.vec.splat %value : !s32i, !cir.vector<4 x !s32i>
+```
+  }];
+
+  let arguments = (ins CIR_AnyType:$value);
+  let results = (outs CIR_VectorType:$result);
+
+  let assemblyFormat = [{
+$value `:` type($value) `,` qualified(type($result)) attr-dict
+  }];
+}
+
 #endif // CLANG_CIR_DIALECT_IR_CIROPS_TD
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 77287ec45972d..61e6cb8ae04b8 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -1762,6 +1762,14 @@ mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr 
*ce) {
   cgf.convertType(destTy));
   }
 
+  case CK_VectorSplat: {
+// Create a vector object and fill all elements with the same scalar value.
+assert(destTy->isVectorType() && "CK_VectorSplat to non-vector type");
+return builder.create(
+cgf.getLoc(subExpr->getSourceRange()), cgf.convertType(destTy),
+Visit(subExpr));
+  }
+
   default:
 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
"CastExpr: ", ce->getCastKindName());
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index f61e85ce3ccec..b1544545ee4be 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -1730,6 +1730,7 @@ void ConvertCIRToLLVMPass::runOnOperation() {
CIRToLLVMVecExtractOpLowering,
CIRToLLVMVecInsertOpLowering,
CIRToLLVMVecCmpOpLowering,
+   CIRToLLVMVecSplatOpLowering,
CIRToLLVMVecShuffleDynamicOpLowering
   // clang-format on
   >(converter, patterns.getContext());
@@ -1880,6 +1881,61 @@ mlir::LogicalResult 
CIRToLLVMVecCmpOpLowering::matchAndRewrite(
   return mlir::success();
 }
 
+mlir::LogicalResult CIRToLLVMVecSplatOpLowering::matchAndRewrite(
+cir::VecSplatOp op, OpAdaptor adaptor,
+mlir::ConversionPatternRewriter &rewriter) const {
+  // Vector splat can be implemented with an `insertelement` and a
+  // `shufflevector`, which is better than an `insertelement` for each
+  // element in the vector. Start with an undef vector. Insert the value into
+  // the first element. Then use a `shufflevector` with a mask of all 0 to
+  // fill out the entire vector with that value.
+  const auto vecTy = mlir::cast(op.getType());
+  const mlir::Type llvmTy = typeConverter->convertType(vecTy);
+  const mlir::Location loc = op.getLoc();
+  const mlir::Value poison = rewriter.create(loc, 
llvmTy);
+
+  const mlir::Value elementValue = adaptor.getValue();
+  if (mlir::isa(elementValue.getDefiningOp())) {
+// If the splat value is poison, then we can just use poison value
+// for the entire vector.
+rewriter.replaceOp(op, poison)

[clang] [CIR] Upstream lowering of conditional operators to TernaryOp (PR #138156)

2025-06-03 Thread Erich Keane via cfe-commits


@@ -98,6 +98,14 @@ class ScalarExprEmitter : public 
StmtVisitor {
 
   mlir::Value emitPromoted(const Expr *e, QualType promotionType);
 
+  mlir::Value maybePromoteBoolResult(mlir::Value value,
+ mlir::Type dstTy) const {
+if (mlir::isa(dstTy))
+  return builder.createBoolToInt(value, dstTy);
+if (mlir::isa(dstTy))
+  return value;
+  }

erichkeane wrote:

Note the 'else' case here is problematic.  We need a return here.

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


[clang] [ubsan] Add more -fsanitize-annotate-debug-info checks (PR #141997)

2025-06-03 Thread Vitaly Buka via cfe-commits


@@ -2817,7 +2817,9 @@ void CodeGenFunction::EmitVTablePtrCheckForCall(const 
CXXRecordDecl *RD,
 RD = LeastDerivedClassWithSameLayout(RD);
 
   auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
-  ApplyDebugLocation ApplyTrapDI(*this, SanitizerAnnotateDebugInfo(Ordinal));
+  ApplyDebugLocation ApplyTrapDI(

vitalybuka wrote:

If so, I maybe make SanitizerScope ++/-- so we can nest them?

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


[clang] [ubsan] Add more -fsanitize-annotate-debug-info checks (PR #141997)

2025-06-03 Thread Vitaly Buka via cfe-commits


@@ -2817,7 +2817,9 @@ void CodeGenFunction::EmitVTablePtrCheckForCall(const 
CXXRecordDecl *RD,
 RD = LeastDerivedClassWithSameLayout(RD);
 
   auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
-  ApplyDebugLocation ApplyTrapDI(*this, SanitizerAnnotateDebugInfo(Ordinal));
+  ApplyDebugLocation ApplyTrapDI(

vitalybuka wrote:

Probably in follow up patches

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


[clang-tools-extra] [clang-doc] Reenable time trace support (PR #141139)

2025-06-03 Thread Paul Kirth via cfe-commits

ilovepi wrote:

### Merge activity

* **Jun 3, 4:54 PM UTC**: A user started a stack merge that includes this pull 
request via 
[Graphite](https://app.graphite.dev/github/pr/llvm/llvm-project/141139).


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


[clang] ee46630 - [Clang][Sema] Add fortify warnings for stpcpy (#141646)

2025-06-03 Thread via cfe-commits

Author: Sharjeel Khan
Date: 2025-06-03T10:34:08-07:00
New Revision: ee46630dd06dd1e4f564f9fa9bb0daf3e9e29c98

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

LOG: [Clang][Sema] Add fortify warnings for stpcpy (#141646)

As mentioned in https://github.com/llvm/llvm-project/issues/142230, I am
adding fortify warnings for functions missing in Clang and I am starting
with stpcpy.

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/warn-fortify-source.c

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3193359923fdb..49593e55a6933 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1257,6 +1257,8 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
   switch (BuiltinID) {
   default:
 return;
+  case Builtin::BI__builtin_stpcpy:
+  case Builtin::BIstpcpy:
   case Builtin::BI__builtin_strcpy:
   case Builtin::BIstrcpy: {
 DiagID = diag::warn_fortify_strlen_overflow;
@@ -1265,6 +1267,7 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 break;
   }
 
+  case Builtin::BI__builtin___stpcpy_chk:
   case Builtin::BI__builtin___strcpy_chk: {
 DiagID = diag::warn_fortify_strlen_overflow;
 SourceSize = ComputeStrLenArgument(1);

diff  --git a/clang/test/Sema/warn-fortify-source.c 
b/clang/test/Sema/warn-fortify-source.c
index a12460b963cd0..f48ea0907c657 100644
--- a/clang/test/Sema/warn-fortify-source.c
+++ b/clang/test/Sema/warn-fortify-source.c
@@ -71,6 +71,14 @@ void call_strcpy_nowarn(void) {
   __builtin_strcpy(dst, src);
 }
 
+void call_stpcpy(void) {
+  const char *const src = "abcd";
+  char dst1[5];
+  char dst2[4];
+  __builtin_stpcpy(dst1, src);
+  __builtin_stpcpy(dst2, src); // expected-warning {{'stpcpy' will always 
overflow; destination buffer has size 4, but the source string has length 5 
(including NUL byte)}}
+}
+
 void call_memmove(void) {
   char s1[10], s2[20];
   __builtin_memmove(s2, s1, 20);



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


[clang] [Clang][Sema] Add fortify warnings for stpcpy (PR #141646)

2025-06-03 Thread Sharjeel Khan via cfe-commits

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


[clang] [llvm] [AArch64TargetParser]Fix reconstructFromParsedFeatures ignoring negative features (PR #142236)

2025-06-03 Thread Matthias Braun via cfe-commits


@@ -1831,6 +1831,22 @@ TEST_P(AArch64ExtensionDependenciesBaseCPUTestFixture,
   }
 }
 
+TEST(TargetParserTest, testAArch64ReconstructFromParsedFeatures) {

MatzeB wrote:

typo in the test is fixed now.

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


[clang] [clang][dep-scan] Resolve lexer crash from a permutation of invalid tokens (PR #142452)

2025-06-03 Thread Argyrios Kyrtzidis via cfe-commits


@@ -503,6 +503,10 @@ bool Scanner::lexModuleDirectiveBody(DirectiveKind Kind, 
const char *&First,
   diag::err_dep_source_scanner_missing_semi_after_at_import);
 if (Tok.is(tok::semi))
   break;
+if (Tok.is(tok::hash) || Tok.is(tok::at))
+  return reportError(

akyrtzi wrote:

I'll take a look into the code to offer a suggestion.

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


[clang] [clang] Don't evaluate the initializer of constexpr-unknown parameters. (PR #142498)

2025-06-03 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

Backported manually: #142648

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


[clang] [KeyInstr][Clang] For range stmt atoms (PR #134647)

2025-06-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `premerge-monolithic-linux` 
running on `premerge-linux-1` while building `clang` at step 7 
"test-build-unified-tree-check-all".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/153/builds/33693


Here is the relevant piece of the build log for the reference

```
Step 7 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'Clang :: CoverageMapping/terminate-statements.cpp' 
FAILED 
Exit Code: 2

Command Output (stderr):
--
/build/buildbot/premerge-monolithic-linux/build/bin/clang -cc1 
-internal-isystem 
/build/buildbot/premerge-monolithic-linux/build/lib/clang/21/include 
-nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-unknown-linux-gnu 
-main-file-name terminate-statements.cpp -I 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/Inputs
 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
 | /build/buildbot/premerge-monolithic-linux/build/bin/FileCheck 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
 # RUN: at line 1
+ /build/buildbot/premerge-monolithic-linux/build/bin/clang -cc1 
-internal-isystem 
/build/buildbot/premerge-monolithic-linux/build/lib/clang/21/include 
-nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-unknown-linux-gnu 
-main-file-name terminate-statements.cpp -I 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/Inputs
 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
+ /build/buildbot/premerge-monolithic-linux/build/bin/FileCheck 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.  Program arguments: 
/build/buildbot/premerge-monolithic-linux/build/bin/clang -cc1 
-internal-isystem 
/build/buildbot/premerge-monolithic-linux/build/lib/clang/21/include 
-nostdsysteminc -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-fexceptions -fcxx-exceptions -emit-llvm-only -triple x86_64-unknown-linux-gnu 
-main-file-name terminate-statements.cpp -I 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/Inputs
 
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp
1.  
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:45:1:
 current parser token 'int'
2.  
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:37:5:
 LLVM IR generation of declaration 'f6'
3.  
/build/buildbot/premerge-monolithic-linux/llvm-project/clang/test/CoverageMapping/terminate-statements.cpp:37:5:
 Generating code for declaration 'f6'
 #0 0x5ca145940d88 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/lib/Support/Unix/Signals.inc:804:13
 #1 0x5ca14593e8be llvm::sys::RunSignalHandlers() 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/lib/Support/Signals.cpp:106:18
 #2 0x5ca145941461 SignalHandler(int, siginfo_t*, void*) 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/lib/Support/Unix/Signals.inc:0:3
 #3 0x7e8d6d900520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x5ca145c8fff9 asInt 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/PointerIntPair.h:41:5
 #5 0x5ca145c8fff9 operator long 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/PointerIntPair.h:45:48
 #6 0x5ca145c8fff9 getPointer 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/PointerIntPair.h:94:58
 #7 0x5ca145c8fff9 getPrev 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/ilist_node_base.h:41:54
 #8 0x5ca145c8fff9 getPrev 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/ilist_node.h:123:59
 #9 0x5ca145c8fff9 empty 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/ilist_node.h:319:45
#10 0x5ca145c8fff9 empty 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/ADT/simple_ilist.h:139:54
#11 0x5ca145c8fff9 getTerminator 
/build/buildbot/premerge-monolithic-linux/llvm-project/llvm/include/llvm/IR/BasicB

[clang] [ubsan] Add more -fsanitize-annotate-debug-info checks (PR #141997)

2025-06-03 Thread Thurston Dang via cfe-commits


@@ -2817,7 +2817,9 @@ void CodeGenFunction::EmitVTablePtrCheckForCall(const 
CXXRecordDecl *RD,
 RD = LeastDerivedClassWithSameLayout(RD);
 
   auto [Ordinal, _] = SanitizerInfoFromCFICheckKind(TCK);
-  ApplyDebugLocation ApplyTrapDI(*this, SanitizerAnnotateDebugInfo(Ordinal));
+  ApplyDebugLocation ApplyTrapDI(

thurstond wrote:

I checked again and found that all callers to EmitVTablePtrCheck 
(EmitVTablePtrCheckForCall, EmitVTablePtrCheckForCast) establish 
SanitizerDebugLocation. Hence, we don't need nested SanitizerDebugLocation; 
instead, I removed SanitizerDebugLocation from EmitVTablePtrCheck: 
https://github.com/llvm/llvm-project/pull/141997/commits/aead894277f56e16bb63b5f9e40b6e6dfcebb01a

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


[clang] [docs][coroutines] Revamp "Debugging C++ coroutines" (PR #142651)

2025-06-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-coroutines

Author: Adrian Vogelsgesang (vogelsgesang)


Changes

This commit is a major overhaul of the documentation on debugging C++ 
coroutines with the following goals:

* Make it more accessible to casual C++ programmers, i.e. non-toolchain 
developers. Move the low-level details around ABI further down, and instead 
start with real-life examples and copy-paste-friendly code, first.
* Cover LLDB in addition to GCC. Provide copy-pasteable scripts for LLDB and 
not only GCC.
* Cover additional topics, such as:
  * single-stepping into a coroutine
  * using `__builtin_return_address` for tracking suspension points (inspired 
by Folly's blog series on coroutine debugging)
* Document LLDB's support for devirtualization of `std::coroutine_handle`, both 
from an end user perspective as well as its internal implementation

---

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


4 Files Affected:

- (modified) clang/docs/DebuggingCoroutines.rst (+844-459) 
- (added) clang/docs/coro-async-task-continuations.png () 
- (added) clang/docs/coro-generator-suspended.png () 
- (added) clang/docs/coro-generator-variables.png () 


``diff
diff --git a/clang/docs/DebuggingCoroutines.rst 
b/clang/docs/DebuggingCoroutines.rst
index 80df321340724..b33e2cda91a30 100644
--- a/clang/docs/DebuggingCoroutines.rst
+++ b/clang/docs/DebuggingCoroutines.rst
@@ -8,470 +8,966 @@ Debugging C++ Coroutines
 Introduction
 
 
-For performance and other architectural reasons, the C++ Coroutines feature in
-the Clang compiler is implemented in two parts of the compiler.  Semantic
-analysis is performed in Clang, and Coroutine construction and optimization
-takes place in the LLVM middle-end.
+Coroutines in C++ were introduced in C++20, and their user experience for
+debugging them can still be challenging. This document guides you how to most
+efficiently debug coroutines and how to navigate existing shortcomings in
+debuggers and compilers.
+
+Coroutines are generally used either as generators or for asynchronous
+programming. In this document, we will discuss both use cases. Even if you are
+using coroutines for asynchronous programming, you should still read the
+generators section, as it will introduce foundational debugging techniques also
+applicable to the debugging of asynchronous programming.
+
+Both compilers (clang, gcc, ...) and debuggers (lldb, gdb, ...) are
+still improving their support for coroutines. As such, we recommend to use the
+latest available version of your toolchain.
+
+This document focuses on clang and lldb. The screenshots show
+[lldb-dap](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.lldb-dap)
+in combination with VS Code. The same techniques can also be used in other
+IDEs.
+
+Debugging clang-compiled binaries with gdb is possible, but requires more
+scripting. This guide comes with a basic GDB script for coroutine debugging.
+
+This guide will first showcase the more polished, bleeding-edge experience, but
+will also show you how to debug coroutines with older toolchains. In general,
+the older your toolchain, the deeper you will have to dive into the
+implementation details of coroutines (such as their ABI). The further down in
+this document, the more low-level, technical the content will become. If you
+are on an up-to-date toolchain, you will hopefully be able to stop reading
+earlier.
+
+Debugging generators
+
+
+The first major use case for coroutines in C++ are generators, i.e. functions
+which can produce values via ``co_yield``. Values are produced lazily,
+on-demand. For that purpose, every time a new value is requested the coroutine
+gets resumed. As soon as it reaches a ``co_yield`` and thereby returns the
+requested value, the coroutine is suspended again.
+
+This logic is encapsulated in a ``generator`` type similar to
 
-However, this design forces us to generate insufficient debugging information.
-Typically, the compiler generates debug information in the Clang frontend, as
-debug information is highly language specific. However, this is not possible
-for Coroutine frames because the frames are constructed in the LLVM middle-end.
-
-To mitigate this problem, the LLVM middle end attempts to generate some debug
-information, which is unfortunately incomplete, since much of the language
-specific information is missing in the middle end.
+.. code-block:: c++
 
-This document describes how to use this debug information to better debug
-coroutines.
+  // generator.hpp
+  #include 
 
-Terminology
-===
+  // `generator` is a stripped down, minimal generator type.
+  template
+  struct generator {
+struct promise_type {
+  T current_value{};
 
-Due to the recent nature of C++20 Coroutines, the terminology used to describe
-the concepts of Coroutines is not settled.  This section defines a common,
-understa

[clang] [docs][coroutines] Revamp "Debugging C++ coroutines" (PR #142651)

2025-06-03 Thread Adrian Vogelsgesang via cfe-commits

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


  1   2   3   4   5   >