[clang] [clang][bytecode] Diagnose comparing pointers to fields... (PR #137159)

2025-04-24 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/137159

>From a489e3957eeb23fc38758c9a6670a3abd082321d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 24 Apr 2025 13:19:25 +0200
Subject: [PATCH] [clang][bytecode] Diagnose comparing pointers to fields...

... with different access specifiers.
---
 clang/lib/AST/ByteCode/Interp.h | 13 +
 clang/lib/AST/ByteCode/Pointer.cpp  | 42 +
 clang/lib/AST/ByteCode/Pointer.h|  9 ++-
 clang/test/AST/ByteCode/records.cpp | 23 
 4 files changed, 86 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 99b032bee9e3d..0a52a64240c04 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1007,6 +1007,19 @@ inline bool CmpHelper(InterpState &S, CodePtr 
OpPC, CompareFn Fn) {
 return false;
   }
 
+  // Diagnose comparisons between fields with different access specifiers.
+  if (std::optional> Split =
+  Pointer::computeSplitPoint(LHS, RHS)) {
+const FieldDecl *LF = Split->first.getField();
+const FieldDecl *RF = Split->second.getField();
+if (LF && RF && !LF->getParent()->isUnion() &&
+LF->getAccess() != RF->getAccess()) {
+  S.CCEDiag(S.Current->getSource(OpPC),
+diag::note_constexpr_pointer_comparison_differing_access)
+  << LF << LF->getAccess() << RF << RF->getAccess() << LF->getParent();
+}
+  }
+
   unsigned VL = LHS.getByteOffset();
   unsigned VR = RHS.getByteOffset();
   S.Stk.push(BoolT::from(Fn(Compare(VL, VR;
diff --git a/clang/lib/AST/ByteCode/Pointer.cpp 
b/clang/lib/AST/ByteCode/Pointer.cpp
index 059503cae3561..6c2566ba20bde 100644
--- a/clang/lib/AST/ByteCode/Pointer.cpp
+++ b/clang/lib/AST/ByteCode/Pointer.cpp
@@ -571,6 +571,48 @@ bool Pointer::pointsToLiteral() const {
   return E && !isa(E);
 }
 
+std::optional>
+Pointer::computeSplitPoint(const Pointer &A, const Pointer &B) {
+  if (!A.isBlockPointer() || !B.isBlockPointer())
+return std::nullopt;
+
+  if (A.asBlockPointer().Pointee != B.asBlockPointer().Pointee)
+return std::nullopt;
+  if (A.isRoot() && B.isRoot())
+return std::nullopt;
+
+  if (A == B)
+return std::make_pair(A, B);
+
+  auto getBase = [](const Pointer &P) -> Pointer {
+if (P.isArrayElement())
+  return P.expand().getArray();
+return P.getBase();
+  };
+
+  Pointer IterA = A;
+  Pointer IterB = B;
+  Pointer CurA = IterA;
+  Pointer CurB = IterB;
+  for (;;) {
+if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
+  CurA = IterA;
+  IterA = getBase(IterA);
+} else {
+  CurB = IterB;
+  IterB = getBase(IterB);
+}
+
+if (IterA == IterB)
+  return std::make_pair(CurA, CurB);
+
+if (IterA.isRoot() && IterB.isRoot())
+  return std::nullopt;
+  }
+
+  llvm_unreachable("The loop above should've returned.");
+}
+
 std::optional Pointer::toRValue(const Context &Ctx,
  QualType ResultType) const {
   const ASTContext &ASTCtx = Ctx.getASTContext();
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index 8ede706f2736f..e168154a55f58 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -492,7 +492,11 @@ class Pointer {
 return ElemDesc ? ElemDesc->ElemRecord : nullptr;
   }
   /// Returns the field information.
-  const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
+  const FieldDecl *getField() const {
+if (const Descriptor *FD = getFieldDesc())
+  return FD->asFieldDecl();
+return nullptr;
+  }
 
   /// Checks if the storage is extern.
   bool isExtern() const {
@@ -724,6 +728,9 @@ class Pointer {
   /// Checks if both given pointers point to the same block.
   static bool pointToSameBlock(const Pointer &A, const Pointer &B);
 
+  static std::optional>
+  computeSplitPoint(const Pointer &A, const Pointer &B);
+
   /// Whether this points to a block that's been created for a "literal 
lvalue",
   /// i.e. a non-MaterializeTemporaryExpr Expr.
   bool pointsToLiteral() const;
diff --git a/clang/test/AST/ByteCode/records.cpp 
b/clang/test/AST/ByteCode/records.cpp
index da851785323a5..b4059f009b887 100644
--- a/clang/test/AST/ByteCode/records.cpp
+++ b/clang/test/AST/ByteCode/records.cpp
@@ -1787,3 +1787,26 @@ namespace IntegralBaseCast {
 
   static_assert(f() == 0, "");
 }
+
+namespace AccessMismatch {
+  struct A {
+  public:
+constexpr A() : a(0), b(0) {}
+int a;
+constexpr bool cmp() const { return &a < &b; } // both-note {{comparison 
of address of fields 'a' and 'b' of 'A' with differing access specifiers 
(public vs private) has unspecified value}}
+  private:
+int b;
+  };
+  static_assert(A().cmp(), ""); // both-error {{constant expression}} \
+// both-note {{in call}}
+
+  class B {
+  public:
+

[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: kadir çetinkaya (kadircet)


Changes

Previously we would defer evaluation of CLEs until LValue to RValue
conversions, which would result in creating values within wrong scope
and triggering use-after-frees.

This patch instead eagerly evaluates CLEs, within the scope requiring
them. This requires storing an extra pointer for CLE expressions with
static storage.


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


4 Files Affected:

- (modified) clang/include/clang/AST/Expr.h (+12) 
- (modified) clang/lib/AST/Expr.cpp (+9) 
- (modified) clang/lib/AST/ExprConstant.cpp (+25-8) 
- (added) clang/test/AST/static-compound-literals.cpp (+12) 


``diff
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index a83320a7ddec2..95c0f910c22f8 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3489,6 +3489,11 @@ class CompoundLiteralExpr : public Expr {
   /// The int part of the pair stores whether this expr is file scope.
   llvm::PointerIntPair TInfoAndScope;
   Stmt *Init;
+
+  /// Value of constant literals with static storage duration. Used only for
+  /// constant folding as CompoundLiteralExpr is not an ICE.
+  mutable APValue *StaticValue = nullptr;
+
 public:
   CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
   QualType T, ExprValueKind VK, Expr *init, bool fileScope)
@@ -3518,6 +3523,13 @@ class CompoundLiteralExpr : public Expr {
 TInfoAndScope.setPointer(tinfo);
   }
 
+  bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
+  APValue *getOrCreateStaticValue(ASTContext& Ctx) const;
+  APValue &getStaticValue() const {
+assert(StaticValue);
+return *StaticValue;
+  }
+
   SourceLocation getBeginLoc() const LLVM_READONLY {
 // FIXME: Init should never be null.
 if (!Init)
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 59c0e47c7c195..442e85b892a51 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -5467,3 +5467,12 @@ ConvertVectorExpr *ConvertVectorExpr::Create(
   return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
  RParenLoc, FPFeatures);
 }
+
+APValue *CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {
+  assert(hasStaticStorage());
+  if (!StaticValue) {
+StaticValue = new (Ctx) APValue;
+Ctx.addDestruction(StaticValue);
+  }
+  return StaticValue;
+}
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 7c933f47bf7f0..2379e78c1631a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4596,10 +4596,6 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 return false;
   }
 
-  APValue Lit;
-  if (!Evaluate(Lit, Info, CLE->getInitializer()))
-return false;
-
   // According to GCC info page:
   //
   // 6.28 Compound Literals
@@ -4622,7 +4618,12 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 }
   }
 
-  CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
+  APValue *Lit =
+  CLE->hasStaticStorage()
+  ? &CLE->getStaticValue()
+  : Info.CurrentCall->getTemporary(Base, LVal.Base.getVersion());
+
+  CompleteObject LitObj(LVal.Base, Lit, Base->getType());
   return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
 } else if (isa(Base) || isa(Base)) {
   // Special-case character extraction so we don't have to construct an
@@ -9125,9 +9126,25 @@ bool
 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  "lvalue compound literal in c++?");
-  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
-  // only see this when folding in C, so there's no standard to follow here.
-  return Success(E);
+  APValue *Lit;
+  // If CompountLiteral has static storage, its value can be used outside
+  // this expression. So evaluate it once and store it in ASTContext.
+  if (E->hasStaticStorage()) {
+Lit = E->getOrCreateStaticValue(Info.Ctx);
+Result.set(E);
+// Reset any previously evaluated state, otherwise evaluation below might
+// fail.
+// FIXME: Should we just re-use the previously evaluated value instead?
+*Lit = APValue();
+  } else {
+Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
+ ScopeKind::FullExpression, 
Result);
+  }
+  if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
+*Lit = APValue();
+return false;
+  }
+  return true;
 }
 
 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
diff --git a/clang/test/AST/static-compound-literals.cpp 
b/clang/test/AST/st

[clang] [clang] Do not share ownership of `HeaderSearchOptions` (PR #132984)

2025-04-24 Thread Aaron Ballman via cfe-commits

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

The changes LGTM, so if we don't hear back from the folks we've pinged in the 
next few days, I'd say this is safe to land.

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


[clang] [Clang] Consider preferred_type in bitfield warnings (#116760) (PR #116785)

2025-04-24 Thread Martin Storsjö via cfe-commits

mstorsjo wrote:

This change makes Clang produce warnings when building Clang itself; warnings 
looking like this:
```
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:352:1: 
warning: bit-field 'FPEvalMethod' is not wide enough to store all enumerators 
of preferred type 'FPEvalMethodKind' [-Wpreferred-type-bitfield-enum-conversion]
  352 | BENIGN_ENUM_LANGOPT(FPEvalMethod, FPEvalMethodKind, 2, 
FEM_UnsetOnCommandLine, "FP type used for floating point arithmetic")
  | ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:67:6: 
note: expanded from macro 'BENIGN_ENUM_LANGOPT'
   67 |  COMPATIBLE_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  |  ^ 
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:62:6: 
note: expanded from macro 'COMPATIBLE_ENUM_LANGOPT'
   62 |  ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  |  ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.h:646:37: 
note: expanded from macro 'ENUM_LANGOPT'
  646 |   void set##Name(Type Value) { Name = static_cast(Value); }
  | ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:352:53:
 note: widen this field to 3 bits to store all values of 'FPEvalMethodKind'
  352 | BENIGN_ENUM_LANGOPT(FPEvalMethod, FPEvalMethodKind, 2, 
FEM_UnsetOnCommandLine, "FP type used for floating point arithmetic")
  | ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:352:1: 
note: preferred type for bit-field 'FPEvalMethodKind' specified here
  352 | BENIGN_ENUM_LANGOPT(FPEvalMethod, FPEvalMethodKind, 2, 
FEM_UnsetOnCommandLine, "FP type used for floating point arithmetic")
  | ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:67:6: 
note: expanded from macro 'BENIGN_ENUM_LANGOPT'
   67 |  COMPATIBLE_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  |  ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.def:62:6: 
note: expanded from macro 'COMPATIBLE_ENUM_LANGOPT'
   62 |  ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  |  ^
/home/martin/code/llvm-project/clang/include/clang/Basic/LangOptions.h:493:3: 
note: expanded from macro 'ENUM_LANGOPT'
  493 |   LLVM_PREFERRED_TYPE(Type) \
  |   ^
/home/martin/code/llvm-project/llvm/include/llvm/Support/Compiler.h:687:47: 
note: expanded from macro 'LLVM_PREFERRED_TYPE'
  687 | #define LLVM_PREFERRED_TYPE(T) __attribute__((preferred_type(T)))
  |   ^
```

I've seen such warnings when building Clang for x86_64 linux, aarch64 linux and 
aarch64 mingw at least.

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


[clang] Thread Safety Analysis: Support reentrant capabilities (PR #137133)

2025-04-24 Thread Aaron Ballman via cfe-commits


@@ -3990,6 +3990,13 @@ def LocksExcluded : InheritableAttr {
   let Documentation = [Undocumented];
 }
 
+def ReentrantCapability : InheritableAttr {
+  let Spellings = [Clang<"reentrant_capability">];
+  let Subjects = SubjectList<[Record, TypedefName]>;
+  let Documentation = [Undocumented];

AaronBallman wrote:

We generally don't want new, undocumented attributes. However, I think this is 
fine because we have dedicated documentation for this elsewhere which is being 
updated, and this matches the same lack of documentation as the rest of the 
thread safety attributes.

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/136404

>From 87ca1f6992d1413d1d2b2e0d230b4f41e1979fef Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Fri, 18 Apr 2025 18:45:00 +0530
Subject: [PATCH 1/2] Fix cuda flag with clang-repl

---
 clang/include/clang/Interpreter/Interpreter.h | 10 ++-
 clang/lib/Interpreter/DeviceOffload.cpp   | 39 +--
 clang/lib/Interpreter/DeviceOffload.h |  4 +-
 clang/lib/Interpreter/Interpreter.cpp | 65 ++-
 4 files changed, 75 insertions(+), 43 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b1b63aedf86ab..59089cf639f96 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -95,6 +95,9 @@ class Interpreter {
   // An optional parser for CUDA offloading
   std::unique_ptr DeviceParser;
 
+  // An optional action for CUDA offloading
+  std::unique_ptr DeviceAct;
+
   /// List containing information about each incrementally parsed piece of 
code.
   std::list PTUs;
 
@@ -175,10 +178,11 @@ class Interpreter {
   llvm::Expected ExtractValueFromExpr(Expr *E);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
-  CodeGenerator *getCodeGen() const;
-  std::unique_ptr GenModule();
+  CodeGenerator *getCodeGen(IncrementalAction *Action = nullptr) const;
+  std::unique_ptr GenModule(IncrementalAction *Action = nullptr);
   PartialTranslationUnit &RegisterPTU(TranslationUnitDecl *TU,
-  std::unique_ptr M = {});
+  std::unique_ptr M = {},
+  IncrementalAction *Action = nullptr);
 
   // A cache for the compiled destructors used to for de-allocation of managed
   // clang::Values.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp 
b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..d9b00787f038d 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)
+llvm::Error &Err, std::list &PTUs)
 : IncrementalParser(*DeviceInstance, Err), PTUs(PTUs), VFS(FS),
   CodeGenOpts(HostInstance.getCodeGenOpts()),
-  TargetOpts(HostInstance.getTargetOpts()) {
+  TargetOpts(DeviceInstance->getTargetOpts()) {
   if (Err)
 return;
-  DeviceCI = std::move(DeviceInstance);
   StringRef Arch = TargetOpts.CPU;
   if (!Arch.starts_with("sm_") || Arch.substr(3).getAsInteger(10, SMVersion)) {
+DeviceInstance.release();
 Err = llvm::joinErrors(std::move(Err), llvm::make_error(
"Invalid CUDA architecture",

llvm::inconvertibleErrorCode()));
 return;
   }
+  DeviceCI = std::move(DeviceInstance);
 }
 
 llvm::Expected
@@ -50,25 +51,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();
-  if (!PTX)
-return PTX.takeError();
-
-  auto Err = GenerateFatbinary();
-  if (Err)
-return std::move(Err);
-
-  std::string FatbinFileName =
-  "/incr_module_" + std::to_string(PTUs.size()) + ".fatbin";
-  VFS->addFile(FatbinFileName, 0,
-   llvm::MemoryBuffer::getMemBuffer(
-   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
-   "", false));
-
-  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
-
-  FatbinContent.clear();
-
   return PTU;
 }
 
@@ -172,6 +154,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();
+
+  std::string FatbinFileName = "/" + PTU.TheModule->getName().str() + 
".fatbin";
+
+  VFS->addFile(FatbinFileName, 0,
+   llvm::MemoryBuffer::getMemBuffer(
+   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
+   "", false));
+
+  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
+
+  FatbinContent.clear();
+
   return llvm::Error::success();
 }
 
diff --git a/clang/lib/Interpreter/DeviceOffload.h 
b/clang/lib/Interpreter/DeviceOffload.h
index b9a1acab004c3..23d89046c09e1 100644
--- a/clang/lib/Interpreter/DeviceOffload.h
+++ b/clang/lib/Interpreter/DeviceOffload.h
@@ -24,14 +24,14 @@ class CodeGenOptions;
 class TargetOptions;
 
 class IncrementalCUDADeviceParser : public IncrementalParser {
-  const std::list &PTUs;
+  std::list &PTUs;
 
 public:
   IncrementalCUDADeviceParser(
   std::unique_ptr DeviceInstance,
   CompilerInstance &HostInstance,
   llvm::IntrusiveRefCntPtr VFS,
-  llvm::Error &Err, const std::list &PTUs);
+  llvm::Error &Err, std::l

[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/136404

>From 6c64e64c4a3b56f50808cae244b29da1231525f1 Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Fri, 18 Apr 2025 18:45:00 +0530
Subject: [PATCH] Fix cuda flag with clang-repl

---
 clang/include/clang/Interpreter/Interpreter.h | 13 ++--
 clang/lib/Interpreter/DeviceOffload.cpp   | 39 ++--
 clang/lib/Interpreter/DeviceOffload.h |  4 +-
 clang/lib/Interpreter/Interpreter.cpp | 59 ++-
 4 files changed, 72 insertions(+), 43 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b1b63aedf86ab..56213f88b9e30 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -41,6 +41,7 @@ class CXXRecordDecl;
 class Decl;
 class IncrementalExecutor;
 class IncrementalParser;
+class IncrementalCUDADeviceParser;
 
 /// Create a pre-configured \c CompilerInstance for incremental processing.
 class IncrementalCompilerBuilder {
@@ -93,7 +94,10 @@ class Interpreter {
   std::unique_ptr IncrExecutor;
 
   // An optional parser for CUDA offloading
-  std::unique_ptr DeviceParser;
+  std::unique_ptr DeviceParser;
+
+  // An optional action for CUDA offloading
+  std::unique_ptr DeviceAct;
 
   /// List containing information about each incrementally parsed piece of 
code.
   std::list PTUs;
@@ -175,10 +179,11 @@ class Interpreter {
   llvm::Expected ExtractValueFromExpr(Expr *E);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
-  CodeGenerator *getCodeGen() const;
-  std::unique_ptr GenModule();
+  CodeGenerator *getCodeGen(IncrementalAction *Action = nullptr) const;
+  std::unique_ptr GenModule(IncrementalAction *Action = nullptr);
   PartialTranslationUnit &RegisterPTU(TranslationUnitDecl *TU,
-  std::unique_ptr M = {});
+  std::unique_ptr M = {},
+  IncrementalAction *Action = nullptr);
 
   // A cache for the compiled destructors used to for de-allocation of managed
   // clang::Values.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp 
b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..d9b00787f038d 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)
+llvm::Error &Err, std::list &PTUs)
 : IncrementalParser(*DeviceInstance, Err), PTUs(PTUs), VFS(FS),
   CodeGenOpts(HostInstance.getCodeGenOpts()),
-  TargetOpts(HostInstance.getTargetOpts()) {
+  TargetOpts(DeviceInstance->getTargetOpts()) {
   if (Err)
 return;
-  DeviceCI = std::move(DeviceInstance);
   StringRef Arch = TargetOpts.CPU;
   if (!Arch.starts_with("sm_") || Arch.substr(3).getAsInteger(10, SMVersion)) {
+DeviceInstance.release();
 Err = llvm::joinErrors(std::move(Err), llvm::make_error(
"Invalid CUDA architecture",

llvm::inconvertibleErrorCode()));
 return;
   }
+  DeviceCI = std::move(DeviceInstance);
 }
 
 llvm::Expected
@@ -50,25 +51,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();
-  if (!PTX)
-return PTX.takeError();
-
-  auto Err = GenerateFatbinary();
-  if (Err)
-return std::move(Err);
-
-  std::string FatbinFileName =
-  "/incr_module_" + std::to_string(PTUs.size()) + ".fatbin";
-  VFS->addFile(FatbinFileName, 0,
-   llvm::MemoryBuffer::getMemBuffer(
-   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
-   "", false));
-
-  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
-
-  FatbinContent.clear();
-
   return PTU;
 }
 
@@ -172,6 +154,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();
+
+  std::string FatbinFileName = "/" + PTU.TheModule->getName().str() + 
".fatbin";
+
+  VFS->addFile(FatbinFileName, 0,
+   llvm::MemoryBuffer::getMemBuffer(
+   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
+   "", false));
+
+  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
+
+  FatbinContent.clear();
+
   return llvm::Error::success();
 }
 
diff --git a/clang/lib/Interpreter/DeviceOffload.h 
b/clang/lib/Interpreter/DeviceOffload.h
index b9a1acab004c3..23d89046c09e1 100644
--- a/clang/lib/Interpreter/DeviceOffload.h
+++ b/clang/lib/Interpreter/DeviceOffload.h
@@ -24,14 +24,14 @@ class CodeGenOptions;
 class TargetOptions;
 
 class IncrementalCUDADevi

[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

anutosh491 wrote:

Making a note of the major changes below !

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


[clang] [clang][SPIR-V] Addrspace of opencl_global should always be 1 (PR #136753)

2025-04-24 Thread Alex Voicu via cfe-commits

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

LGTM, thanks! FWIW, perhaps it'd be worthwhile (as a follow-up, not here) to 
simply make the DefIsGen AS map correct/valid, and replace the dummy bits?

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


[clang-tools-extra] [clang-tidy] Add check 'bugprone-invalid-enum-default-initialization' (PR #136823)

2025-04-24 Thread via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 



@@ -3,7 +3,7 @@
 bugprone-invalid-enum-default-initialization
 
 
-Detect default initialization (to 0) of variables with `enum` type where
+Detect default initialization (to 0) of variables with ``enum`` type where

EugeneZelenko wrote:

```suggestion
Detects default initialization (to 0) of variables with ``enum`` type where
```

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


[clang-tools-extra] [clang-tidy] Add check 'bugprone-invalid-enum-default-initialization' (PR #136823)

2025-04-24 Thread via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -125,6 +125,12 @@ New checks
   Finds potentially erroneous calls to ``reset`` method on smart pointers when
   the pointee type also has a ``reset`` method.
 
+- New :doc:`bugprone-invalid-enum-default-initialization
+  ` check.
+
+  Detect default initialization (to 0) of variables with ``enum`` type where

EugeneZelenko wrote:

```suggestion
  Detects default initialization (to 0) of variables with ``enum`` type where
```

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


[clang] [CIR] Upstream TernaryOp (PR #137184)

2025-04-24 Thread Erich Keane via cfe-commits


@@ -609,8 +609,8 @@ def ConditionOp : CIR_Op<"condition", [
 
//===--===//
 
 def YieldOp : CIR_Op<"yield", [ReturnLike, Terminator,
-   ParentOneOf<["IfOp", "ScopeOp", "WhileOp",
-"ForOp", "DoWhileOp"]>]> {
+   ParentOneOf<["IfOp", "TernaryOp", "ScopeOp",

erichkeane wrote:

What is the ordering of this list?  Does it make sense to group them in some 
way?  Or perhaps alpha order?

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


[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2025-04-24 Thread Yingwei Zheng via cfe-commits


@@ -2799,9 +2799,30 @@ CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
   llvm::LoadInst *Load =
   Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
   CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
-  return makeNaturalAddressForPointer(Load, 
RefLVal.getType()->getPointeeType(),
-  CharUnits(), /*ForPointeeType=*/true,
-  PointeeBaseInfo, PointeeTBAAInfo);
+  QualType PTy = RefLVal.getType()->getPointeeType();
+  if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {

dtcxzyw wrote:

Removed. It was needed by `!dereferenceable`.


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


[clang] [CIR] Upstream TernaryOp (PR #137184)

2025-04-24 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

Not the best one to do the full review here, but had 2 comments.

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


[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2025-04-24 Thread Yingwei Zheng via cfe-commits


@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - %s -O2 | 
FileCheck %s
 
-// Make sure the call to b() doesn't get optimized out.
+// Make sure the call to b() is eliminated.
 extern struct x {char& x,y;}y;
 int b();  
 int a() { if (!&y.x) b(); }

dtcxzyw wrote:

Deleted.

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


[clang] [CIR] Upstream TernaryOp (PR #137184)

2025-04-24 Thread Erich Keane via cfe-commits

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


[clang] [CIR] Upstream TernaryOp (PR #137184)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Morris Hafner (mmha)


Changes

This patch adds TernaryOp to CIR plus a pass that flattens the operator in 
FlattenCFG.

This is the first PR out of (probably) 3 wrt. TernaryOp. I split the patches up 
to make reviewing them easier. As such, this PR is only about adding the CIR 
operation. The next PR will be about the CodeGen bits from the C++ conditional 
operator and the final one will add the cir-simplify transform for TernaryOp 
and SelectOp.

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


6 Files Affected:

- (modified) clang/include/clang/CIR/Dialect/IR/CIROps.td (+55-2) 
- (modified) clang/lib/CIR/Dialect/IR/CIRDialect.cpp (+42) 
- (modified) clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp (+55-5) 
- (added) clang/test/CIR/IR/ternary.cir (+30) 
- (added) clang/test/CIR/Lowering/ternary.cir (+30) 
- (added) clang/test/CIR/Transforms/ternary.cir (+68) 


``diff
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 81b447f31feca..76ad5c3666c1b 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -609,8 +609,8 @@ def ConditionOp : CIR_Op<"condition", [
 
//===--===//
 
 def YieldOp : CIR_Op<"yield", [ReturnLike, Terminator,
-   ParentOneOf<["IfOp", "ScopeOp", "WhileOp",
-"ForOp", "DoWhileOp"]>]> {
+   ParentOneOf<["IfOp", "TernaryOp", "ScopeOp",
+"WhileOp", "ForOp", 
"DoWhileOp"]>]> {
   let summary = "Represents the default branching behaviour of a region";
   let description = [{
 The `cir.yield` operation terminates regions on different CIR operations,
@@ -1246,6 +1246,59 @@ def SelectOp : CIR_Op<"select", [Pure,
   }];
 }
 
+//===--===//
+// TernaryOp
+//===--===//
+
+def TernaryOp : CIR_Op<"ternary",
+  [DeclareOpInterfaceMethods,
+   RecursivelySpeculatable, AutomaticAllocationScope, NoRegionArguments]> {
+  let summary = "The `cond ? a : b` C/C++ ternary operation";
+  let description = [{
+The `cir.ternary` operation represents C/C++ ternary, much like a `select`
+operation. The first argument is a `cir.bool` condition to evaluate, 
followed
+by two regions to execute (true or false). This is different from `cir.if`
+since each region is one block sized and the `cir.yield` closing the block
+scope should have one argument.
+
+Example:
+
+```mlir
+// x = cond ? a : b;
+
+%x = cir.ternary (%cond, true_region {
+  ...
+  cir.yield %a : i32
+}, false_region {
+  ...
+  cir.yield %b : i32
+}) -> i32
+```
+  }];
+  let arguments = (ins CIR_BoolType:$cond);
+  let regions = (region AnyRegion:$trueRegion,
+AnyRegion:$falseRegion);
+  let results = (outs Optional:$result);
+
+  let skipDefaultBuilders = 1;
+  let builders = [
+OpBuilder<(ins "mlir::Value":$cond,
+  "llvm::function_ref":$trueBuilder,
+  "llvm::function_ref":$falseBuilder)
+  >
+  ];
+
+  // All constraints already verified elsewhere.
+  let hasVerifier = 0;
+
+  let assemblyFormat = [{
+`(` $cond `,`
+  `true` $trueRegion `,`
+  `false` $falseRegion
+`)` `:` functional-type(operands, results) attr-dict
+  }];
+}
+
 
//===--===//
 // GlobalOp
 
//===--===//
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp 
b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 89daf20c5f478..e80d243cb396f 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -1058,6 +1058,48 @@ LogicalResult cir::BinOp::verify() {
   return mlir::success();
 }
 
+//===--===//
+// TernaryOp
+//===--===//
+
+/// Given the region at `index`, or the parent operation if `index` is None,
+/// return the successor regions. These are the regions that may be selected
+/// during the flow of control. `operands` is a set of optional attributes that
+/// correspond to a constant value for each operand, or null if that operand is
+/// not a constant.
+void cir::TernaryOp::getSuccessorRegions(
+mlir::RegionBranchPoint point, SmallVectorImpl ®ions) {
+  // The `true` and the `false` region branch back to the parent operation.
+  if (!point.isParent()) {
+regions.push_back(RegionSuccessor(this->getODSResults(0)));
+return;
+  }
+
+  // If the condition isn't constant, both regions may be execu

[clang-tools-extra] [clang-tidy] Add check bugprone-misleading-setter-of-reference (PR #132242)

2025-04-24 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,58 @@
+//===--- MisleadingSetterOfReferenceCheck.cpp - 
clang-tidy-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MisleadingSetterOfReferenceCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void MisleadingSetterOfReferenceCheck::registerMatchers(MatchFinder *Finder) {
+  auto RefField =
+  fieldDecl(unless(isPublic()),

NagyDonat wrote:

I agree that those cases (where a public reference member has a setter function 
with misleading type) are "twice buggy" (because public members should not have 
a setter function in any case), but this means that they are very unlikely to 
appear in the analyzed code, so we shouldn't complicate the behavior of this 
checker with extra code for it.

As we discussed on the meeting, please remove the `unless(isPublic())` 
condition.

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


[clang] [CIR] Upstream TernaryOp (PR #137184)

2025-04-24 Thread Morris Hafner via cfe-commits

https://github.com/mmha created https://github.com/llvm/llvm-project/pull/137184

This patch adds TernaryOp to CIR plus a pass that flattens the operator in 
FlattenCFG.

This is the first PR out of (probably) 3 wrt. TernaryOp. I split the patches up 
to make reviewing them easier. As such, this PR is only about adding the CIR 
operation. The next PR will be about the CodeGen bits from the C++ conditional 
operator and the final one will add the cir-simplify transform for TernaryOp 
and SelectOp.

>From 1eed90e3859c2ad8d703708f89976cad8f0faeec Mon Sep 17 00:00:00 2001
From: Morris Hafner 
Date: Thu, 24 Apr 2025 16:12:37 +0200
Subject: [PATCH] [CIR] Upstream TernaryOp

This patch adds TernaryOp to CIR plus a pass that flattens the operator in 
FlattenCFG.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  | 57 +++-
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp   | 42 
 .../lib/CIR/Dialect/Transforms/FlattenCFG.cpp | 60 ++--
 clang/test/CIR/IR/ternary.cir | 30 
 clang/test/CIR/Lowering/ternary.cir   | 30 
 clang/test/CIR/Transforms/ternary.cir | 68 +++
 6 files changed, 280 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/CIR/IR/ternary.cir
 create mode 100644 clang/test/CIR/Lowering/ternary.cir
 create mode 100644 clang/test/CIR/Transforms/ternary.cir

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 81b447f31feca..76ad5c3666c1b 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -609,8 +609,8 @@ def ConditionOp : CIR_Op<"condition", [
 
//===--===//
 
 def YieldOp : CIR_Op<"yield", [ReturnLike, Terminator,
-   ParentOneOf<["IfOp", "ScopeOp", "WhileOp",
-"ForOp", "DoWhileOp"]>]> {
+   ParentOneOf<["IfOp", "TernaryOp", "ScopeOp",
+"WhileOp", "ForOp", 
"DoWhileOp"]>]> {
   let summary = "Represents the default branching behaviour of a region";
   let description = [{
 The `cir.yield` operation terminates regions on different CIR operations,
@@ -1246,6 +1246,59 @@ def SelectOp : CIR_Op<"select", [Pure,
   }];
 }
 
+//===--===//
+// TernaryOp
+//===--===//
+
+def TernaryOp : CIR_Op<"ternary",
+  [DeclareOpInterfaceMethods,
+   RecursivelySpeculatable, AutomaticAllocationScope, NoRegionArguments]> {
+  let summary = "The `cond ? a : b` C/C++ ternary operation";
+  let description = [{
+The `cir.ternary` operation represents C/C++ ternary, much like a `select`
+operation. The first argument is a `cir.bool` condition to evaluate, 
followed
+by two regions to execute (true or false). This is different from `cir.if`
+since each region is one block sized and the `cir.yield` closing the block
+scope should have one argument.
+
+Example:
+
+```mlir
+// x = cond ? a : b;
+
+%x = cir.ternary (%cond, true_region {
+  ...
+  cir.yield %a : i32
+}, false_region {
+  ...
+  cir.yield %b : i32
+}) -> i32
+```
+  }];
+  let arguments = (ins CIR_BoolType:$cond);
+  let regions = (region AnyRegion:$trueRegion,
+AnyRegion:$falseRegion);
+  let results = (outs Optional:$result);
+
+  let skipDefaultBuilders = 1;
+  let builders = [
+OpBuilder<(ins "mlir::Value":$cond,
+  "llvm::function_ref":$trueBuilder,
+  "llvm::function_ref":$falseBuilder)
+  >
+  ];
+
+  // All constraints already verified elsewhere.
+  let hasVerifier = 0;
+
+  let assemblyFormat = [{
+`(` $cond `,`
+  `true` $trueRegion `,`
+  `false` $falseRegion
+`)` `:` functional-type(operands, results) attr-dict
+  }];
+}
+
 
//===--===//
 // GlobalOp
 
//===--===//
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp 
b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 89daf20c5f478..e80d243cb396f 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -1058,6 +1058,48 @@ LogicalResult cir::BinOp::verify() {
   return mlir::success();
 }
 
+//===--===//
+// TernaryOp
+//===--===//
+
+/// Given the region at `index`, or the parent operation if `index` is None,
+/// return the successor regions. These are the regions that may be selected
+/// during the flow of control. `operands` is a set of optional attributes that
+/// correspond to a constant value for each

[clang] d859cb6 - [OpenACC] Fix variable dereference found by static analysis

2025-04-24 Thread via cfe-commits

Author: erichkeane
Date: 2025-04-24T07:43:16-07:00
New Revision: d859cb68836191cfa469d0c951134b53ee31298e

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

LOG: [OpenACC] Fix variable dereference found by static analysis

Reported here: https://github.com/llvm/llvm-project/issues/137116

Fixes: 137116

Added: 


Modified: 
clang/lib/Sema/SemaOpenACCClause.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenACCClause.cpp 
b/clang/lib/Sema/SemaOpenACCClause.cpp
index fba40c834e703..6cf6888e2a3a9 100644
--- a/clang/lib/Sema/SemaOpenACCClause.cpp
+++ b/clang/lib/Sema/SemaOpenACCClause.cpp
@@ -2085,32 +2085,31 @@ bool 
SemaOpenACC::CheckDeclareClause(SemaOpenACC::OpenACCParsedClause &Clause,
   }
 } else {
   const auto *DRE = cast(VarExpr);
-  const VarDecl *Var = dyn_cast(DRE->getDecl());
-  if (Var)
+  if (const auto *Var = dyn_cast(DRE->getDecl())) {
 CurDecl = Var->getCanonicalDecl();
 
-  // OpenACC3.3 2.13:
-  // A 'declare' directive must be in the same scope as the declaration of
-  // any var that appears in the clauses of the directive or any scope
-  // within a C/C++ function.
-  // We can't really check 'scope' here, so we check declaration context,
-  // which is a reasonable approximation, but misses scopes inside of
-  // functions.
-  if (removeLinkageSpecDC(Var->getCanonicalDecl()
-  ->getLexicalDeclContext()
-  ->getPrimaryContext()) != DC) {
-Diag(VarExpr->getBeginLoc(), diag::err_acc_declare_same_scope)
-<< Clause.getClauseKind();
-continue;
-  }
-  // OpenACC3.3 2.13:
-  // C and C++ extern variables may only appear in 'create',
-  // 'copyin', 'deviceptr', 'device_resident', or 'link' clauses on a
-  // 'declare' directive.
-  if (!IsSpecialClause && Var && Var->hasExternalStorage()) {
-Diag(VarExpr->getBeginLoc(), diag::err_acc_declare_extern)
-<< Clause.getClauseKind();
-continue;
+// OpenACC3.3 2.13:
+// A 'declare' directive must be in the same scope as the declaration 
of
+// any var that appears in the clauses of the directive or any scope
+// within a C/C++ function.
+// We can't really check 'scope' here, so we check declaration context,
+// which is a reasonable approximation, but misses scopes inside of
+// functions.
+if (removeLinkageSpecDC(
+Var->getLexicalDeclContext()->getPrimaryContext()) != DC) {
+  Diag(VarExpr->getBeginLoc(), diag::err_acc_declare_same_scope)
+  << Clause.getClauseKind();
+  continue;
+}
+// OpenACC3.3 2.13:
+// C and C++ extern variables may only appear in 'create',
+// 'copyin', 'deviceptr', 'device_resident', or 'link' clauses on a
+// 'declare' directive.
+if (!IsSpecialClause && Var->hasExternalStorage()) {
+  Diag(VarExpr->getBeginLoc(), diag::err_acc_declare_extern)
+  << Clause.getClauseKind();
+  continue;
+}
   }
 
   // OpenACC3.3 2.13:



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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Balazs Benics via cfe-commits

steakhal wrote:

Do you have data about the analysis times per file, and per analysis entry 
point?
Compared against the current llvm main, and also if this workaround would 
restore the original running times before 
https://github.com/llvm/llvm-project/commit/bb27d5e5c6b194a1440b8ac4e5ace68d0ee2a849?

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


[libclc] [libclc] Support the generic address space (PR #137183)

2025-04-24 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

Even as a compiler implementation detail, libclc should not need to consider 
the address space mapping. 

There is a clang bug if there is different mangling. The itanium mangling 
should be coming from the source type / original address space, not whatever IR 
address space value that happens to map to 

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


[libclc] [libclc] Support the generic address space (PR #137183)

2025-04-24 Thread Matt Arsenault via cfe-commits

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


[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-04-24 Thread via cfe-commits

macurtis-amd wrote:

@nikic ping

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


[clang] [clang-refactor] Add Matcher Edit refactoring rule (PR #123782)

2025-04-24 Thread Сергеев Игнатий via cfe-commits

IgnatSergeev wrote:

@bartlettroscoe, 
> So is this really transforming the AST?

Well yeah, you are right, it replaces it with text, but what i ment, is that it 
supports replacements with EditGenerators, which are really expressive (a few 
words about them 
https://clang.llvm.org/docs/ClangTransformerTutorial.html#editgenerators-advanced)

But i would say that even clang-refactor uses source code transformations, it 
doesn`t change AST

> For example, there appears to be an "Extract Function" refactor that might 
> actually be able to refactor real C++ code

The link you provided is to a test tool, but i see how you can adapt this to 
some tool
And speaking about "Extract Function", i searched through that file, and found 
only a rename symbol refactor

After a brief look, i think it uses source code transformations too
main -> calls rename 
(https://github.com/swiftlang/llvm-project/blob/next/clang/tools/clang-refactor-test/ClangRefactorTest.cpp#L520)
 -> calls clang_Refactoring_initiateAction and after uses it`s action 
(https://github.com/swiftlang/llvm-project/blob/next/clang/tools/libclang/CRefactor.cpp#L1384)
 -> creates RefactoringAction 
(https://github.com/swiftlang/llvm-project/blob/next/clang/tools/libclang/CRefactor.cpp#L750)
 that uses RefactoringOperation and RenamingAction for refactoring

RenamingAction is based on Refactoring library (the same that clang-refactor 
uses) and it use the same source code transformations 
(https://github.com/swiftlang/llvm-project/blob/next/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp)
And RefactoringOperation 
(https://github.com/swiftlang/llvm-project/blob/next/clang/include/clang/Tooling/Refactor/RefactoringOperation.h)
 uses RefactoringResult that as i see in comment also uses raw source code 
transformations
![image](https://github.com/user-attachments/assets/b2fabe88-d582-4cde-a071-1a6af7df24ce)

I hope my it makes sense
So at the end it is still a source code transformation, these functions don`t 
allow you to get transformed AST
But that was a brief look, i could be wrong

> LLNL ROSE Outliner tool

At first glance could be what you want

> The question is how his does this clang transformer mapping of AST to source 
> code work for larger chucks of C++ code, like for "Extract Function"?

Maybe it`s possible, but i couldn`t invent something like that
At least not purely using transformer, it`s mostly used for local 
transformations, as there are much more of those

> Or, perhaps everyone is waiting for better AI to be able to refactor C++ 
> automatically?

Actually, that`s an interesting idea

But to be honest, i think that there are`t many "users" for large refactoring 
tools, so when they are needed people write small portion of their own 
transformations, so they doesn`t get to open source


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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits


@@ -2523,6 +2523,20 @@ bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
   return true;
 }
 
+/// Return the innermost location context which is inlined at `Node`, unless
+/// it's the top-level (entry point) location context.
+static const LocationContext *getInlinedLocationContext(ExplodedNode *Node,
+ExplodedGraph &G) {
+  const LocationContext *CalleeLC = Node->getLocation().getLocationContext();
+  const LocationContext *RootLC =

NagyDonat wrote:

Very good questions!

I strongly suspect that in practice the graph always has only one root and the 
"multiple roots" representation is just one of the many pointlessly generic 
fragments that were added during the early development of the project – but I'm 
just moving this code to a helper function (because I need to call it from a 
second location) and I didn't check whether its assumptions are correct.

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


[clang] [clang] fix unresolved dependent template specialization mangling (PR #135111)

2025-04-24 Thread Matheus Izvekov via cfe-commits


@@ -399,3 +399,20 @@ namespace type_qualifier {
   // CHECK: @_ZN14type_qualifier1gIPiEEvDTcmcvv_ELi1EE
   template void g(int);
 }
+
+namespace unresolved_template_specialization_type {
+  template  struct enable_if {};
+  struct Foo {
+static const int value = true;
+  };
+  struct HashStateBase {
+template  using is_hashable = Foo;
+  };
+  template  struct raw_hash_set {
+template 
+static enable_if::value>
+AbslHashValue() {}
+  };
+  template enable_if raw_hash_set::AbslHashValue();
+  // CHECH: 
@_ZN39unresolved_template_specialization_type12raw_hash_setIiE13AbslHashValueINS_13HashStateBaseEEENS_9enable_ifIXsrNT_11is_hashableIiEE5valueEEEv

mizvekov wrote:

Ops, good catch, will fix.

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


[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Erich Keane via cfe-commits


@@ -8197,6 +8197,16 @@ def err_address_space_qualified_new : Error<
 def err_address_space_qualified_delete : Error<
   "'delete' cannot delete objects of type %0 in address space '%1'">;
 
+def note_default_init_const_member : Note<
+  "member %0 declared 'const' here">;
+def warn_default_init_const : Warning<
+  "default initialization of an object of type %0%select{| with const member}1 
"
+  "is incompatible with C++">,
+  InGroup, DefaultIgnore;
+def warn_default_init_const_unsafe : Warning<

erichkeane wrote:

Does it make sense to combine these two with the 'unsafeness' being a select?

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


[clang] [llvm] [mlir] [TableGen] Only store direct superclasses in Record (PR #123072)

2025-04-24 Thread Jay Foad via cfe-commits

https://github.com/jayfoad updated 
https://github.com/llvm/llvm-project/pull/123072

>From f12511a0fd30c47ea08e6c126cae558215758183 Mon Sep 17 00:00:00 2001
From: Jay Foad 
Date: Wed, 15 Jan 2025 13:34:41 +
Subject: [PATCH 01/16] Change API of getSuperClasses

---
 llvm/include/llvm/TableGen/Record.h   |  5 ++--
 llvm/lib/TableGen/DetailedRecordsBackend.cpp  |  4 +--
 llvm/lib/TableGen/JSONBackend.cpp |  4 ++-
 llvm/lib/TableGen/Record.cpp  | 26 ++-
 llvm/lib/TableGen/SetTheory.cpp   |  4 ++-
 llvm/lib/TableGen/TGParser.cpp|  9 ---
 llvm/utils/TableGen/CallingConvEmitter.cpp| 11 
 .../TableGen/Common/CodeGenRegisters.cpp  |  4 ++-
 .../utils/TableGen/SearchableTableEmitter.cpp |  5 ++--
 9 files changed, 49 insertions(+), 23 deletions(-)

diff --git a/llvm/include/llvm/TableGen/Record.h 
b/llvm/include/llvm/TableGen/Record.h
index b15e9fc7328da..79e9b88c34a56 100644
--- a/llvm/include/llvm/TableGen/Record.h
+++ b/llvm/include/llvm/TableGen/Record.h
@@ -1718,8 +1718,9 @@ class Record {
   ArrayRef getAssertions() const { return Assertions; }
   ArrayRef getDumps() const { return Dumps; }
 
-  ArrayRef> getSuperClasses() const {
-return SuperClasses;
+  void getSuperClasses(
+  SmallVectorImpl> &Classes) const {
+Classes.append(SuperClasses);
   }
 
   /// Determine whether this record has the specified direct superclass.
diff --git a/llvm/lib/TableGen/DetailedRecordsBackend.cpp 
b/llvm/lib/TableGen/DetailedRecordsBackend.cpp
index 4a337248c941a..2a1623e64e439 100644
--- a/llvm/lib/TableGen/DetailedRecordsBackend.cpp
+++ b/llvm/lib/TableGen/DetailedRecordsBackend.cpp
@@ -152,8 +152,8 @@ void DetailedRecordsEmitter::printTemplateArgs(const Record 
&Rec,
 // are enclosed in parentheses.
 void DetailedRecordsEmitter::printSuperclasses(const Record &Rec,
raw_ostream &OS) {
-  ArrayRef> Superclasses =
-  Rec.getSuperClasses();
+  SmallVector> Superclasses;
+  Rec.getSuperClasses(Superclasses);
   if (Superclasses.empty()) {
 OS << "  Superclasses: (none)\n";
 return;
diff --git a/llvm/lib/TableGen/JSONBackend.cpp 
b/llvm/lib/TableGen/JSONBackend.cpp
index d648019ac46e8..fecd16764fca2 100644
--- a/llvm/lib/TableGen/JSONBackend.cpp
+++ b/llvm/lib/TableGen/JSONBackend.cpp
@@ -151,7 +151,9 @@ void JSONEmitter::run(raw_ostream &OS) {
 
 json::Array SuperClasses;
 // Add this def to the instance list for each of its superclasses.
-for (const auto &[SuperClass, Loc] : Def->getSuperClasses()) {
+SmallVector> SCs;
+Def->getSuperClasses(SCs);
+for (const auto &[SuperClass, Loc] : SCs) {
   std::string SuperName = SuperClass->getNameInitAsString();
   SuperClasses.push_back(SuperName);
   InstanceLists[SuperName].push_back(Name);
diff --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp
index 597ccb7ca144b..4fe2b16cd516f 100644
--- a/llvm/lib/TableGen/Record.cpp
+++ b/llvm/lib/TableGen/Record.cpp
@@ -2395,7 +2395,9 @@ const DefInit *VarDefInit::instantiate() {
   NewRec->resolveReferences(R);
 
   // Add superclasses.
-  for (const auto &[SC, Loc] : Class->getSuperClasses())
+  SmallVector> SCs;
+  Class->getSuperClasses(SCs);
+  for (const auto &[SC, Loc] : SCs)
 NewRec->addSuperClass(SC, Loc);
 
   NewRec->addSuperClass(
@@ -2912,13 +2914,18 @@ void Record::setName(const Init *NewName) {
 // so we can step through the direct superclasses in reverse order.
 
 bool Record::hasDirectSuperClass(const Record *Superclass) const {
-  ArrayRef> SCs = getSuperClasses();
+  SmallVector> SCs;
+  getSuperClasses(SCs);
+
+  SmallVector> SSCs;
 
   for (int I = SCs.size() - 1; I >= 0; --I) {
 const Record *SC = SCs[I].first;
 if (SC == Superclass)
   return true;
-I -= SC->getSuperClasses().size();
+SC->getSuperClasses(SSCs);
+I -= SSCs.size();
+SSCs.clear();
   }
 
   return false;
@@ -2926,11 +2933,17 @@ bool Record::hasDirectSuperClass(const Record 
*Superclass) const {
 
 void Record::getDirectSuperClasses(
 SmallVectorImpl &Classes) const {
-  ArrayRef> SCs = getSuperClasses();
+  SmallVector> SCVec;
+  getSuperClasses(SCVec);
+  ArrayRef> SCs = SCVec;
+
+  SmallVector> SSCs;
 
   while (!SCs.empty()) {
 const Record *SC = SCs.back().first;
-SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
+SC->getSuperClasses(SSCs);
+SCs = SCs.drop_back(1 + SSCs.size());
+SSCs.clear();
 Classes.push_back(SC);
   }
 }
@@ -3008,7 +3021,8 @@ raw_ostream &llvm::operator<<(raw_ostream &OS, const 
Record &R) {
   }
 
   OS << " {";
-  ArrayRef> SC = R.getSuperClasses();
+  SmallVector> SC;
+  R.getSuperClasses(SC);
   if (!SC.empty()) {
 OS << "\t//";
 for (const auto &[SC, _] : SC)
diff --git a/llvm/lib/TableGen/SetTheory.cpp b/llvm/lib/TableGen/SetTheory.cpp
index ac7ae2cbaed57..b3a2b9d0d6fa7 100644
--- a/llvm/lib/TableGen/SetTheory.cpp
+++ b/llvm/lib/T

[clang] [clang][bytecode] Emit diagnostics from GetGlobalUnchecked (PR #137203)

2025-04-24 Thread Timm Baeder via cfe-commits

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

If the global is uninitialized.

>From 87377cd713004492ca9c989e1e7de806ba972ebf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 24 Apr 2025 17:46:49 +0200
Subject: [PATCH] [clang][bytecode] Emit diagnostics from GetGlobalUnchecked

If the global is uninitialized.
---
 clang/lib/AST/ByteCode/Interp.h   | 2 +-
 clang/test/AST/ByteCode/cxx11.cpp | 8 
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 99b032bee9e3d..01c955b8548d3 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1433,7 +1433,7 @@ bool GetGlobal(InterpState &S, CodePtr OpPC, uint32_t I) {
 template ::T>
 bool GetGlobalUnchecked(InterpState &S, CodePtr OpPC, uint32_t I) {
   const Pointer &Ptr = S.P.getPtrGlobal(I);
-  if (!Ptr.isInitialized())
+  if (!CheckInitialized(S, OpPC, Ptr, AK_Read))
 return false;
   S.Stk.push(Ptr.deref());
   return true;
diff --git a/clang/test/AST/ByteCode/cxx11.cpp 
b/clang/test/AST/ByteCode/cxx11.cpp
index 004f704145afd..5daf6adf08cf5 100644
--- a/clang/test/AST/ByteCode/cxx11.cpp
+++ b/clang/test/AST/ByteCode/cxx11.cpp
@@ -194,3 +194,11 @@ namespace DynamicCast {
 int g : (S*)(void*)(sptr) == sptr;
   };
 }
+
+namespace GlobalInitializer {
+  extern int &g; // both-note {{here}}
+  struct S {
+int G : g; // both-error {{constant expression}} \
+   // both-note {{initializer of 'g' is unknown}}
+  };
+}

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


[clang] Fix a crash in constant evaluation of ExtVectorElementExprs (PR #136771)

2025-04-24 Thread Akira Hatanaka via cfe-commits

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


[clang] feaa5aa - Fix a crash in constant evaluation of ExtVectorElementExprs (#136771)

2025-04-24 Thread via cfe-commits

Author: Akira Hatanaka
Date: 2025-04-24T08:47:29-07:00
New Revision: feaa5aa840dcda69bd4133536142be882f696114

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

LOG: Fix a crash in constant evaluation of ExtVectorElementExprs (#136771)

Handle the case where the base expression is a pointer to a vector type.

rdar://149223362

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constexpr-vectors-access-elements.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 7c933f47bf7f0..f2e49b9ea669e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -9202,7 +9202,10 @@ bool LValueExprEvaluator::VisitExtVectorElementExpr(
 
   if (Success) {
 Result.setFrom(Info.Ctx, Val);
-const auto *VT = E->getBase()->getType()->castAs();
+QualType BaseType = E->getBase()->getType();
+if (E->isArrow())
+  BaseType = BaseType->getPointeeType();
+const auto *VT = BaseType->castAs();
 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
   VT->getNumElements(), Indices[0]);
   }

diff  --git a/clang/test/SemaCXX/constexpr-vectors-access-elements.cpp 
b/clang/test/SemaCXX/constexpr-vectors-access-elements.cpp
index 08223e15feb72..58efcde414af2 100644
--- a/clang/test/SemaCXX/constexpr-vectors-access-elements.cpp
+++ b/clang/test/SemaCXX/constexpr-vectors-access-elements.cpp
@@ -43,4 +43,6 @@ static_assert(b.lo.lo == 1); // expected-error {{not an 
integral constant expres
 // make sure clang rejects taking address of a vector element
 static_assert(&b[1]); // expected-error {{address of vector element requested}}
 
+constexpr const FourIntsExtVec *p = &b;
+static_assert(p->x == 1);
 }



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


[clang] [clang] Implement address sanitizer on AIX (1/n) (PR #129925)

2025-04-24 Thread Jake Egan via cfe-commits

https://github.com/jakeegan updated 
https://github.com/llvm/llvm-project/pull/129925

>From 072f4eca3825729d69d423d774c8a3298cb624a8 Mon Sep 17 00:00:00 2001
From: Jake Egan 
Date: Wed, 5 Mar 2025 01:57:38 -0500
Subject: [PATCH 1/2] [clang] Implement address sanitizer on AIX (1/3)

The PR includes clang changes needed for the address sanitizer on AIX. Will 
also post llvm and
compiler-rt PRs following this.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |   2 +
 clang/include/clang/Driver/Options.td |   2 +-
 clang/lib/CodeGen/BackendUtil.cpp |   5 +-
 clang/lib/Driver/ToolChain.cpp|   2 +-
 clang/lib/Driver/ToolChains/AIX.cpp   |  45 
 clang/lib/Driver/ToolChains/AIX.h |   2 +
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  36 +-
 .../lib/aix/asan.link_with_main_exec.txt  |   0
 .../lib/aix/asan_cxx.link_with_main_exec.txt  |   0
 clang/test/Driver/sanitizer-ld.c  | 104 ++
 10 files changed, 189 insertions(+), 9 deletions(-)
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/aix/asan.link_with_main_exec.txt
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/aix/asan_cxx.link_with_main_exec.txt

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 8d599c96eb4fb..c44d364d244bc 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -257,6 +257,8 @@ def err_drv_malformed_sanitizer_metadata_ignorelist : Error<
   "malformed sanitizer metadata ignorelist: '%0'">;
 def err_drv_unsupported_static_sanitizer_darwin : Error<
   "static %0 runtime is not supported on darwin">;
+def err_drv_unsupported_shared_sanitizer_aix : Error<
+  "shared %0 runtime is not supported on AIX">;
 def err_drv_duplicate_config : Error<
   "no more than one option '--config' is allowed">;
 def err_drv_cannot_open_config_file : Error<
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0ab923fcdd583..66959279d3fcf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1542,7 +1542,7 @@ defm xl_pragma_pack : BoolFOption<"xl-pragma-pack",
   "Enable IBM XL #pragma pack handling">,
   NegFlag>;
 def shared_libsan : Flag<["-"], "shared-libsan">,
-  HelpText<"Dynamically link the sanitizer runtime">;
+  HelpText<"Dynamically link the sanitizer runtime (Not supported for ASan on 
AIX)">;
 def static_libsan : Flag<["-"], "static-libsan">,
   HelpText<"Statically link the sanitizer runtime (Not supported for ASan, 
TSan or UBSan on darwin)">;
 def : Flag<["-"], "shared-libasan">, Alias;
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 97e9bbccd61ef..b47aff95f2430 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -275,13 +275,14 @@ static bool asanUseGlobalsGC(const Triple &T, const 
CodeGenOptions &CGOpts) {
 return !CGOpts.DisableIntegratedAS;
   case Triple::GOFF:
 llvm::report_fatal_error("ASan not implemented for GOFF");
-  case Triple::XCOFF:
-llvm::report_fatal_error("ASan not implemented for XCOFF.");
   case Triple::Wasm:
   case Triple::DXContainer:
   case Triple::SPIRV:
   case Triple::UnknownObjectFormat:
 break;
+  case Triple::XCOFF:
+// FIXME: try to enable GC-friendly instrumentation for globals on AIX.
+return false;
   }
   return false;
 }
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index ebc982096595e..d4aa71d031ba9 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -749,7 +749,7 @@ std::string ToolChain::buildCompilerRTBasename(const 
llvm::opt::ArgList &Args,
   case ToolChain::FT_Shared:
 Suffix = TT.isOSWindows()
  ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
- : ".so";
+ : (TT.isOSAIX() ? ".a" : ".so");
 break;
   }
 
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 09a8dc2f4fa5d..30db6f45c7e81 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -20,6 +20,7 @@
 #include 
 
 using AIX = clang::driver::toolchains::AIX;
+using namespace clang;
 using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang::driver::toolchains;
@@ -233,6 +234,44 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   // Specify linker input file(s).
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
+  // Add sanitizer libraries.
+  const SanitizerArgs &Sanitize = ToolChain.getSanitizerArgs(Args);
+  const char *sanitizer = nullptr;
+  bool NeedsSanitizerDeps = false;
+  // For now, only support address sanitizer.
+  if (Sanitize.needsAsanRt())
+sanitizer = "AddressSanitizer";
+
+  if (sanitizer) {
+  

[clang] [clang][bytecode] Emit diagnostics from GetGlobalUnchecked (PR #137203)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

If the global is uninitialized.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.h (+1-1) 
- (modified) clang/test/AST/ByteCode/cxx11.cpp (+8) 


``diff
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 99b032bee9e3d..01c955b8548d3 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1433,7 +1433,7 @@ bool GetGlobal(InterpState &S, CodePtr OpPC, uint32_t I) {
 template ::T>
 bool GetGlobalUnchecked(InterpState &S, CodePtr OpPC, uint32_t I) {
   const Pointer &Ptr = S.P.getPtrGlobal(I);
-  if (!Ptr.isInitialized())
+  if (!CheckInitialized(S, OpPC, Ptr, AK_Read))
 return false;
   S.Stk.push(Ptr.deref());
   return true;
diff --git a/clang/test/AST/ByteCode/cxx11.cpp 
b/clang/test/AST/ByteCode/cxx11.cpp
index 004f704145afd..5daf6adf08cf5 100644
--- a/clang/test/AST/ByteCode/cxx11.cpp
+++ b/clang/test/AST/ByteCode/cxx11.cpp
@@ -194,3 +194,11 @@ namespace DynamicCast {
 int g : (S*)(void*)(sptr) == sptr;
   };
 }
+
+namespace GlobalInitializer {
+  extern int &g; // both-note {{here}}
+  struct S {
+int G : g; // both-error {{constant expression}} \
+   // both-note {{initializer of 'g' is unknown}}
+  };
+}

``




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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

@balazs-benics-sonarsource Unfortunately our current CI (which runs the static 
analyzer via CodeChecker) cannot provide file-level or entrypoint-level timing 
information, but I do have full analysis runtime measurements (which I'll edit 
into the table in my previous comment).

This comparison is between `legacy-inlining-prevention=false` (which is 
practically equivalent to the recent main revision 
a84a6f7dd68b218757e192fe21a806c80ef0b63d) and `legacy-inlining-prevention=true` 
(the default in this patch), but I can measure timing differences compared to 
other commits as well. I think the most natural comparison would be between
- this commit with its default `legacy-inlining-prevention=true` mode and
- reverting bb27d5e5c6b194a1440b8ac4e5ace68d0ee2a849 ("Don't assume third 
iteration") atop a84a6f7dd68b218757e192fe21a806c80ef0b63d (the parent of this 
commit)
because that way the comparison wouldn't be influenced by other commits that 
are merged in the last few months.

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


[clang] default clause replaced by otherwise clause for metadirective in OpenMP 5.2 (PR #128640)

2025-04-24 Thread Alexey Bataev via cfe-commits


@@ -1660,6 +1660,10 @@ def err_omp_expected_colon : Error<"missing ':' in %0">;
 def err_omp_missing_comma : Error< "missing ',' after %0">;
 def err_omp_expected_context_selector
 : Error<"expected valid context selector in %0">;
+def err_omp_unknown_clause
+: Error<"expected an OpenMP clause">;
+def warn_omp_default_deprecated : Warning<"'default' clause for"

alexey-bataev wrote:

Use err_omp_deprecate_old_syntax

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


[clang] default clause replaced by otherwise clause for metadirective in OpenMP 5.2 (PR #128640)

2025-04-24 Thread Alexey Bataev via cfe-commits


@@ -2785,6 +2797,13 @@ StmtResult 
Parser::ParseOpenMPDeclarativeOrExecutableDirective(
   return Directive;
 }
   }
+  if (CKind == OMPC_otherwise) {
+// Check for 'otherwise' keyword.
+if (Tok.is(tok::identifier) &&
+Tok.getIdentifierInfo()->getName() == "otherwise") {

alexey-bataev wrote:

Why need to double check here?

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


[clang] [clang-tools-extra] [flang] [lldb] [llvm] [mlir] [openmp] [polly] [Documentation] Always use SVG for dot-generated doxygen images. (PR #136843)

2025-04-24 Thread Aaron Ballman via cfe-commits


@@ -48,14 +48,6 @@ if (LLVM_ENABLE_DOXYGEN)
 set(bolt_doxygen_qhp_cust_filter_attrs "")
   endif()
 
-  option(LLVM_DOXYGEN_SVG

AaronBallman wrote:

Awesome, thanks!

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


[clang] [CIR] Cleanup support for C functions (PR #136854)

2025-04-24 Thread Iris Shi via cfe-commits


@@ -13,20 +13,76 @@
 
 #include "CIRGenCall.h"
 #include "CIRGenFunction.h"
+#include "CIRGenFunctionInfo.h"
 #include "clang/CIR/MissingFeatures.h"
 
 using namespace clang;
 using namespace clang::CIRGen;
 
-CIRGenFunctionInfo *CIRGenFunctionInfo::create(CanQualType resultType) {
-  void *buffer = operator new(totalSizeToAlloc(1));
+CIRGenFunctionInfo *
+CIRGenFunctionInfo::create(CanQualType resultType,
+   llvm::ArrayRef argTypes,
+   RequiredArgs required) {
+  void *buffer = operator new(totalSizeToAlloc(argTypes.size() + 1));
 
   CIRGenFunctionInfo *fi = new (buffer) CIRGenFunctionInfo();
+
+  fi->required = required;
+  fi->numArgs = argTypes.size();
   fi->getArgsBuffer()[0].type = resultType;
+  for (unsigned i = 0; i < argTypes.size(); ++i)
+fi->getArgsBuffer()[i + 1].type = argTypes[i];
 
   return fi;
 }
 
+cir::FuncType CIRGenTypes::getFunctionType(const CIRGenFunctionInfo &fi) {
+  bool inserted = functionsBeingProcessed.insert(&fi).second;
+  assert(inserted && "Recursively being processed?");
+
+  mlir::Type resultType = nullptr;
+  const cir::ABIArgInfo &retAI = fi.getReturnInfo();
+
+  switch (retAI.getKind()) {
+  case cir::ABIArgInfo::Ignore:
+// TODO(CIR): This should probably be the None type from the builtin
+// dialect.
+resultType = nullptr;
+break;
+
+  case cir::ABIArgInfo::Direct:
+resultType = retAI.getCoerceToType();
+break;
+
+  default:
+assert(false && "NYI");
+  }
+
+  SmallVector argTypes;
+  unsigned argNo = 0;
+  CIRGenFunctionInfo::const_arg_iterator it = fi.arg_begin(),
+ ie = it + fi.getNumRequiredArgs();
+  for (; it != ie; ++it, ++argNo) {
+const auto &argInfo = it->info;
+
+switch (argInfo.getKind()) {
+default:
+  llvm_unreachable("NYI");
+case cir::ABIArgInfo::Direct:
+  mlir::Type argType = argInfo.getCoerceToType();
+  argTypes.push_back(argType);
+  break;
+}
+  }
+
+  bool erased = functionsBeingProcessed.erase(&fi);
+  assert(erased && "Not in set?");

el-ev wrote:

Thank you! I wasn't aware of the purpose of that line before, and I understand 
its purpose now.

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


[clang] [Clang][CodeGen] Emit fake uses before musttail calls (PR #136867)

2025-04-24 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer updated 
https://github.com/llvm/llvm-project/pull/136867

>From 90c09c8326077a1ba6797519bbefd014f32b5beb Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Wed, 23 Apr 2025 14:24:50 +0100
Subject: [PATCH 1/3] [Clang] Emit Fake Uses before musttail calls

Fixes the issue reported following the merge of #118026.

When a valid `musttail` call is made, the function it is made from must
return immediately after the call; if there are any cleanups left in the
function, then an error is triggered. This is not necessary for fake uses
however - it is perfectly valid to simply emit the fake use "cleanup" code
before the tail call, and indeed LLVM will automatically move any fake uses
following a tail call to come before the tail call.

Therefore, this patch specifically choose to handle fake use cleanups when
a musttail call is present by simply emitting them immediately before the
call.
---
 clang/lib/CodeGen/CGCall.cpp| 12 +++-
 clang/test/CodeGenCXX/fake-use-musttail.cpp | 72 +
 2 files changed, 83 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenCXX/fake-use-musttail.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 8cb27420dd911..c8cddfc06fce7 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -6001,8 +6001,18 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
  ++it) {
   EHCleanupScope *Cleanup = dyn_cast(&*it);
-  if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
+  // Fake uses can be safely emitted immediately prior to the tail call; we
+  // choose to emit the fake use before the call rather than after, to 
avoid
+  // forcing variable values from every call on the "stack" to be preserved
+  // simultaneously.
+  if (Cleanup && Cleanup->isFakeUse()) {
+CGBuilderTy::InsertPointGuard IPG(Builder);
+Builder.SetInsertPoint(CI);
+Cleanup->getCleanup()->Emit(*this, EHScopeStack::Cleanup::Flags());
+  } else if (!(Cleanup &&
+   Cleanup->getCleanup()->isRedundantBeforeReturn())) {
 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
+  }
 }
 if (CI->getType()->isVoidTy())
   Builder.CreateRetVoid();
diff --git a/clang/test/CodeGenCXX/fake-use-musttail.cpp 
b/clang/test/CodeGenCXX/fake-use-musttail.cpp
new file mode 100644
index 0..7d1420ce5fdb6
--- /dev/null
+++ b/clang/test/CodeGenCXX/fake-use-musttail.cpp
@@ -0,0 +1,72 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -emit-llvm -fextend-variable-liveness -o - %s | FileCheck %s
+
+/// Tests that when we have fake uses in a function ending in a musttail call,
+/// we emit the fake uses and their corresponding loads immediately prior to 
the
+/// tail call.
+
+struct Class1 {
+  Class1(int);
+};
+
+class Class2 {
+  static const char *foo(int *, const char *, int *, Class1, const int *,
+ unsigned long);
+  template 
+  static char *bar(int *, const char *, int *, Class1, const int *, unsigned 
long);
+};
+
+// CHECK-LABEL: define dso_local noundef ptr 
@_ZN6Class23fooEPiPKcS0_6Class1PKim(
+// CHECK-SAME: ptr noundef [[E:%.*]], ptr noundef [[F:%.*]], ptr noundef 
[[G:%.*]], ptr noundef [[H:%.*]], i64 noundef [[I:%.*]]) #[[ATTR0:[0-9]+]] 
align 2 {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[TMP0:%.*]] = alloca [[STRUCT_CLASS1:%.*]], align 1
+// CHECK-NEXT:[[E_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[F_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[G_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[H_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:[[I_ADDR:%.*]] = alloca i64, align 8
+// CHECK-NEXT:[[AGG_TMP:%.*]] = alloca [[STRUCT_CLASS1]], align 1
+// CHECK-NEXT:store ptr [[E]], ptr [[E_ADDR]], align 8
+// CHECK-NEXT:store ptr [[F]], ptr [[F_ADDR]], align 8
+// CHECK-NEXT:store ptr [[G]], ptr [[G_ADDR]], align 8
+// CHECK-NEXT:store ptr [[H]], ptr [[H_ADDR]], align 8
+// CHECK-NEXT:store i64 [[I]], ptr [[I_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load ptr, ptr [[E_ADDR]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[F_ADDR]], align 8
+// CHECK-NEXT:[[TMP3:%.*]] = load ptr, ptr [[G_ADDR]], align 8
+// CHECK-NEXT:call void @_ZN6Class1C1Ei(ptr noundef nonnull align 1 
dereferenceable(1) [[AGG_TMP]], i32 noundef 0)
+// CHECK-NEXT:[[TMP4:%.*]] = load ptr, ptr [[H_ADDR]], align 8
+// CHECK-NEXT:[[TMP5:%.*]] = load i64, ptr [[I_ADDR]], align 8
+// CHECK-NEXT:[[FAKE_USE:%.*]] = load i64, ptr [[I_ADDR]], align 8
+// CHECK-NEXT:notail call void (...) @llvm.fake.use(i64 [[FAKE_USE]]) 
#[[ATTR3:[0-9]+]]
+// CHECK-NEXT:[[FAKE_USE1:%.*]] = load ptr, ptr [[H_ADDR]], align 8

[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/137163

From 99fa9a1f5fb74401c790871e6eb1ce473d048d74 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Thu, 24 Apr 2025 11:12:00 +0200
Subject: [PATCH] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs

Previously we would defer evaluation of CLEs until LValue to RValue
conversions, which would result in creating values within wrong scope
and triggering use-after-frees.

This patch instead eagerly evaluates CLEs, within the scope requiring
them. This requires storing an extra pointer for CLE expressions with
static storage.
---
 clang/include/clang/AST/Expr.h  | 12 
 clang/lib/AST/Expr.cpp  |  9 ++
 clang/lib/AST/ExprConstant.cpp  | 33 -
 clang/test/AST/static-compound-literals.cpp | 12 
 4 files changed, 58 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/AST/static-compound-literals.cpp

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index a83320a7ddec2..ed56522d107dd 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3489,6 +3489,11 @@ class CompoundLiteralExpr : public Expr {
   /// The int part of the pair stores whether this expr is file scope.
   llvm::PointerIntPair TInfoAndScope;
   Stmt *Init;
+
+  /// Value of constant literals with static storage duration. Used only for
+  /// constant folding as CompoundLiteralExpr is not an ICE.
+  mutable APValue *StaticValue = nullptr;
+
 public:
   CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
   QualType T, ExprValueKind VK, Expr *init, bool fileScope)
@@ -3518,6 +3523,13 @@ class CompoundLiteralExpr : public Expr {
 TInfoAndScope.setPointer(tinfo);
   }
 
+  bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
+  APValue *getOrCreateStaticValue(ASTContext &Ctx) const;
+  APValue &getStaticValue() const {
+assert(StaticValue);
+return *StaticValue;
+  }
+
   SourceLocation getBeginLoc() const LLVM_READONLY {
 // FIXME: Init should never be null.
 if (!Init)
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 59c0e47c7c195..442e85b892a51 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -5467,3 +5467,12 @@ ConvertVectorExpr *ConvertVectorExpr::Create(
   return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
  RParenLoc, FPFeatures);
 }
+
+APValue *CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {
+  assert(hasStaticStorage());
+  if (!StaticValue) {
+StaticValue = new (Ctx) APValue;
+Ctx.addDestruction(StaticValue);
+  }
+  return StaticValue;
+}
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 7c933f47bf7f0..2379e78c1631a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4596,10 +4596,6 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 return false;
   }
 
-  APValue Lit;
-  if (!Evaluate(Lit, Info, CLE->getInitializer()))
-return false;
-
   // According to GCC info page:
   //
   // 6.28 Compound Literals
@@ -4622,7 +4618,12 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 }
   }
 
-  CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
+  APValue *Lit =
+  CLE->hasStaticStorage()
+  ? &CLE->getStaticValue()
+  : Info.CurrentCall->getTemporary(Base, LVal.Base.getVersion());
+
+  CompleteObject LitObj(LVal.Base, Lit, Base->getType());
   return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
 } else if (isa(Base) || isa(Base)) {
   // Special-case character extraction so we don't have to construct an
@@ -9125,9 +9126,25 @@ bool
 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  "lvalue compound literal in c++?");
-  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
-  // only see this when folding in C, so there's no standard to follow here.
-  return Success(E);
+  APValue *Lit;
+  // If CompountLiteral has static storage, its value can be used outside
+  // this expression. So evaluate it once and store it in ASTContext.
+  if (E->hasStaticStorage()) {
+Lit = E->getOrCreateStaticValue(Info.Ctx);
+Result.set(E);
+// Reset any previously evaluated state, otherwise evaluation below might
+// fail.
+// FIXME: Should we just re-use the previously evaluated value instead?
+*Lit = APValue();
+  } else {
+Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
+ ScopeKind::FullExpression, 
Result);
+  }
+  if (!EvaluateInPlace(*Lit, 

[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet created 
https://github.com/llvm/llvm-project/pull/137163

Previously we would defer evaluation of CLEs until LValue to RValue
conversions, which would result in creating values within wrong scope
and triggering use-after-frees.

This patch instead eagerly evaluates CLEs, within the scope requiring
them. This requires storing an extra pointer for CLE expressions with
static storage.


From c3efccde2cfd9d108bb146a419c9e682047b7b09 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Thu, 24 Apr 2025 11:12:00 +0200
Subject: [PATCH] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs

Previously we would defer evaluation of CLEs until LValue to RValue
conversions, which would result in creating values within wrong scope
and triggering use-after-frees.

This patch instead eagerly evaluates CLEs, within the scope requiring
them. This requires storing an extra pointer for CLE expressions with
static storage.
---
 clang/include/clang/AST/Expr.h  | 12 
 clang/lib/AST/Expr.cpp  |  9 ++
 clang/lib/AST/ExprConstant.cpp  | 33 -
 clang/test/AST/static-compound-literals.cpp | 12 
 4 files changed, 58 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/AST/static-compound-literals.cpp

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index a83320a7ddec2..95c0f910c22f8 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3489,6 +3489,11 @@ class CompoundLiteralExpr : public Expr {
   /// The int part of the pair stores whether this expr is file scope.
   llvm::PointerIntPair TInfoAndScope;
   Stmt *Init;
+
+  /// Value of constant literals with static storage duration. Used only for
+  /// constant folding as CompoundLiteralExpr is not an ICE.
+  mutable APValue *StaticValue = nullptr;
+
 public:
   CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
   QualType T, ExprValueKind VK, Expr *init, bool fileScope)
@@ -3518,6 +3523,13 @@ class CompoundLiteralExpr : public Expr {
 TInfoAndScope.setPointer(tinfo);
   }
 
+  bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
+  APValue *getOrCreateStaticValue(ASTContext& Ctx) const;
+  APValue &getStaticValue() const {
+assert(StaticValue);
+return *StaticValue;
+  }
+
   SourceLocation getBeginLoc() const LLVM_READONLY {
 // FIXME: Init should never be null.
 if (!Init)
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 59c0e47c7c195..442e85b892a51 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -5467,3 +5467,12 @@ ConvertVectorExpr *ConvertVectorExpr::Create(
   return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
  RParenLoc, FPFeatures);
 }
+
+APValue *CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {
+  assert(hasStaticStorage());
+  if (!StaticValue) {
+StaticValue = new (Ctx) APValue;
+Ctx.addDestruction(StaticValue);
+  }
+  return StaticValue;
+}
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 7c933f47bf7f0..2379e78c1631a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4596,10 +4596,6 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 return false;
   }
 
-  APValue Lit;
-  if (!Evaluate(Lit, Info, CLE->getInitializer()))
-return false;
-
   // According to GCC info page:
   //
   // 6.28 Compound Literals
@@ -4622,7 +4618,12 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 }
   }
 
-  CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
+  APValue *Lit =
+  CLE->hasStaticStorage()
+  ? &CLE->getStaticValue()
+  : Info.CurrentCall->getTemporary(Base, LVal.Base.getVersion());
+
+  CompleteObject LitObj(LVal.Base, Lit, Base->getType());
   return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
 } else if (isa(Base) || isa(Base)) {
   // Special-case character extraction so we don't have to construct an
@@ -9125,9 +9126,25 @@ bool
 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  "lvalue compound literal in c++?");
-  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
-  // only see this when folding in C, so there's no standard to follow here.
-  return Success(E);
+  APValue *Lit;
+  // If CompountLiteral has static storage, its value can be used outside
+  // this expression. So evaluate it once and store it in ASTContext.
+  if (E->hasStaticStorage()) {
+Lit = E->getOrCreateStaticValue(Info.Ctx);
+Result.set(E);
+// Reset any previously evaluated state, otherwise evaluation below mi

[clang] [clang] Fix a use-after-free in expression evaluation (PR #118480)

2025-04-24 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

Put together a new fix based on the discussions here in 
https://github.com/llvm/llvm-project/pull/137163, PTAL.

@AaronBallman I am afraid this might no longer fix the crashes you're seeing 
internally though, as the new fix is focused on handling of 
`CompoundLiteralExpr`s, whereas the failures you mentioned seem to involve 
different C++ constructs.

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


[clang] [llvm] [RISCV] Add support for Ziccamoc (PR #136694)

2025-04-24 Thread via cfe-commits

https://github.com/T-Tie updated 
https://github.com/llvm/llvm-project/pull/136694

>From e98beadf0009fa05339b964780e4dfe7c444fdd9 Mon Sep 17 00:00:00 2001
From: Tie 
Date: Tue, 22 Apr 2025 12:25:32 +
Subject: [PATCH 1/2] Add Support for Ziccamoc

---
 clang/test/Preprocessor/riscv-target-features.c  | 10 ++
 llvm/docs/RISCVUsage.rst |  3 ++-
 llvm/lib/Target/RISCV/RISCVFeatures.td   |  3 +++
 llvm/test/CodeGen/RISCV/attributes.ll|  2 ++
 llvm/test/MC/RISCV/attribute-arch.s  |  3 +++
 llvm/unittests/TargetParser/RISCVISAInfoTest.cpp |  1 +
 6 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 03c291afe19bd..ea02643f5a21b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -125,6 +125,7 @@
 // CHECK-NOT: __riscv_zicbop {{.*$}}
 // CHECK-NOT: __riscv_zicboz {{.*$}}
 // CHECK-NOT: __riscv_ziccamoa {{.*$}}
+// CHECK-NOT: __riscv_ziccamoc {{.*$}}
 // CHECK-NOT: __riscv_ziccif {{.*$}}
 // CHECK-NOT: __riscv_zicclsm {{.*$}}
 // CHECK-NOT: __riscv_ziccrse {{.*$}}
@@ -1047,6 +1048,15 @@
 // RUN:   -o - | FileCheck --check-prefix=CHECK-ZICCAMOA-EXT %s
 // CHECK-ZICCAMOA-EXT: __riscv_ziccamoa 100{{$}}
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32iziccamoc -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-ZICCAMOC-EXT %s
+// CHECK-ZICCAMOC-EXT: __riscv_ziccamoc 100{{$}}
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64iziccamoc -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-ZICCAMOC-EXT %s
+// CHECK-ZICCAMOC-EXT: __riscv_ziccamoc 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32iziccif -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-ZICCIF-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 1ebe7b57abd7d..1aceb305d98af 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -197,6 +197,7 @@ on support follow.
  ``Zicbop``Supported
  ``Zicboz``Assembly Support
  ``Ziccamoa``  Supported (`See note 
<#riscv-profiles-extensions-note>`__)
+ ``Ziccamoc``  Supported (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Ziccif``Supported (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Zicclsm``   Supported (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Ziccrse``   Supported (`See note 
<#riscv-profiles-extensions-note>`__)
@@ -298,7 +299,7 @@ Supported
 
 .. _riscv-profiles-extensions-note:
 
-``Za128rs``, ``Za64rs``, ``Zama16b``, ``Zic64b``, ``Ziccamoa``, ``Ziccif``, 
``Zicclsm``, ``Ziccrse``, ``Shcounterenvw``, ``Shgatpa``, ``Shtvala``, 
``Shvsatpa``, ``Shvstvala``, ``Shvstvecd``, ``Ssccptr``, ``Sscounterenw``, 
``Ssstateen``, ``Ssstrict``, ``Sstvala``, ``Sstvecd``, ``Ssu64xl``, ``Svade``, 
``Svbare``
+``Za128rs``, ``Za64rs``, ``Zama16b``, ``Zic64b``, ``Ziccamoa``, ``Ziccamoc``, 
``Ziccif``, ``Zicclsm``, ``Ziccrse``, ``Shcounterenvw``, ``Shgatpa``, 
``Shtvala``, ``Shvsatpa``, ``Shvstvala``, ``Shvstvecd``, ``Ssccptr``, 
``Sscounterenw``, ``Ssstateen``, ``Ssstrict``, ``Sstvala``, ``Sstvecd``, 
``Ssu64xl``, ``Svade``, ``Svbare``
   These extensions are defined as part of the `RISC-V Profiles specification 
`__.  They do not 
introduce any new features themselves, but instead describe existing hardware 
features.
 
 .. _riscv-zacas-note:
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatures.td
index 87cab1dafc75b..5c4101f1e4bcd 100644
--- a/llvm/lib/Target/RISCV/RISCVFeatures.td
+++ b/llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -102,6 +102,9 @@ def HasStdExtZicboz : 
Predicate<"Subtarget->hasStdExtZicboz()">,
 def FeatureStdExtZiccamoa
 : RISCVExtension<1, 0, "Main Memory Supports All Atomics in A">;
 
+def FeatureStdExtZiccamoc
+: RISCVExtension<1, 0, "Main memory supports atomics in Zacas">;
+
 def FeatureStdExtZiccif
 : RISCVExtension<1, 0,
  "Main Memory Supports Instruction Fetch with Atomicity 
Requirement">;
diff --git a/llvm/test/CodeGen/RISCV/attributes.ll 
b/llvm/test/CodeGen/RISCV/attributes.ll
index b0dc65839559a..81bb1763966c1 100644
--- a/llvm/test/CodeGen/RISCV/attributes.ll
+++ b/llvm/test/CodeGen/RISCV/attributes.ll
@@ -265,6 +265,7 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+zcmp %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZCMP %s
 ; RUN: llc -mtriple=riscv64 -mattr=+zcmt %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZCMT %s
 ; RUN: llc -mtriple=riscv64 -mattr=+ziccamoa %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZICCAMOA %s
+; RUN: llc -mtriple=riscv64 -mattr=+ziccamoc %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZICCAMOC %s
 ; RUN: llc -mtriple=riscv64 -mattr=+ziccif 

[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman updated 
https://github.com/llvm/llvm-project/pull/137166

>From bb184fc38d13126f244615425cfefe7368ca71b8 Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Wed, 23 Apr 2025 13:40:44 -0400
Subject: [PATCH 1/6] Add -Wdefault-const-init

---
 clang/docs/ReleaseNotes.rst   |  3 ++
 clang/include/clang/Basic/DiagnosticGroups.td |  3 +-
 .../clang/Basic/DiagnosticSemaKinds.td|  6 +++
 clang/lib/Sema/Sema.cpp   | 10 
 clang/lib/Sema/SemaDecl.cpp   |  8 +++
 clang/lib/Sema/SemaInit.cpp   | 36 ++---
 clang/test/Sema/typedef-retain.c  |  3 +-
 clang/test/Sema/warn-default-const-init.c | 54 +++
 8 files changed, 115 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/Sema/warn-default-const-init.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bec670e573ca6..1885acec12bae 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -140,6 +140,9 @@ C Language Changes
 - Clang now allows an ``inline`` specifier on a typedef declaration of a
   function type in Microsoft compatibility mode. #GH124869
 - Clang now allows ``restrict`` qualifier for array types with pointer 
elements (#GH92847).
+- Clang now diagnoses ``const``-qualified object definitions without an
+  initializer, under the new warning ``-Wdefault-const-init`` (which is grouped
+  under ``-Wc++-compat``, as this construct is not compatible with C++). 
#GH19297
 
 C2y Feature Support
 ^^^
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 59036b695da85..3686e65c9102a 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -154,8 +154,9 @@ def BuiltinRequiresHeader : 
DiagGroup<"builtin-requires-header">;
 def C99Compat : DiagGroup<"c99-compat">;
 def C23Compat : DiagGroup<"c23-compat">;
 def : DiagGroup<"c2x-compat", [C23Compat]>;
+def DefaultConstInit : DiagGroup<"default-const-init">;
 
-def CXXCompat: DiagGroup<"c++-compat">;
+def CXXCompat: DiagGroup<"c++-compat", [DefaultConstInit]>;
 def ExternCCompat : DiagGroup<"extern-c-compat">;
 def KeywordCompat : DiagGroup<"keyword-compat">;
 def GNUCaseRange : DiagGroup<"gnu-case-range">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c562802efba57..d97b2feb1b379 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8197,6 +8197,12 @@ def err_address_space_qualified_new : Error<
 def err_address_space_qualified_delete : Error<
   "'delete' cannot delete objects of type %0 in address space '%1'">;
 
+def note_default_init_const_member : Note<
+  "member %0 declared 'const' here">;
+def warn_default_init_const : Warning<
+  "default initialization of an object of type %0%select{| with const member}1"
+  "%select{| leaves the object unitialized and}2 is incompatible with C++">,
+  InGroup;
 def err_default_init_const : Error<
   "default initialization of an object of const type %0"
   "%select{| without a user-provided default constructor}1">;
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 4039601612c62..d09f94d10b5e0 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1448,6 +1448,16 @@ void Sema::ActOnEndOfTranslationUnit() {
 // No initialization is performed for a tentative definition.
 CheckCompleteVariableDeclaration(VD);
 
+// In C, if the definition is const-qualified and has no initializer, it
+// is left uninitialized unless it has static or thread storage duration.
+QualType Type = VD->getType();
+if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
+Type.isConstQualified() && !VD->getAnyInitializer())
+  Diag(VD->getLocation(), diag::warn_default_init_const)
+  << Type << /*not a field*/0
+  << (VD->getStorageDuration() != SD_Static &&
+  VD->getStorageDuration() != SD_Thread);
+
 // Notify the consumer that we've completed a tentative definition.
 if (!VD->isInvalidDecl())
   Consumer.CompleteTentativeDefinition(VD);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d28a2107d58a9..747e9e6d9ac74 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -14333,6 +14333,14 @@ void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
   return;
 }
 
+// In C, if the definition is const-qualified and has no initializer, it
+// is left uninitialized unless it has static or thread storage duration.
+if (!getLangOpts().CPlusPlus && Type.isConstQualified())
+  Diag(Var->getLocation(), diag::warn_default_init_const)
+  << Type << /*not a field*/0
+  << (Var->getStorageDuration() != SD_Static &&
+  Var->getStorageDurat

[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/136404

>From 1f7205615f8d11c1b58e2a2760f85663f97767c5 Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Fri, 18 Apr 2025 18:45:00 +0530
Subject: [PATCH 1/4] Fix cuda flag with clang-repl

---
 clang/include/clang/Interpreter/Interpreter.h | 13 ++-
 clang/lib/Interpreter/DeviceOffload.cpp   | 43 +
 clang/lib/Interpreter/DeviceOffload.h |  4 +-
 clang/lib/Interpreter/Interpreter.cpp | 89 ---
 4 files changed, 88 insertions(+), 61 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b1b63aedf86ab..1b228e0917d02 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -95,6 +95,9 @@ class Interpreter {
   // An optional parser for CUDA offloading
   std::unique_ptr DeviceParser;
 
+  // An optional action for CUDA offloading
+  std::unique_ptr DeviceAct;
+
   /// List containing information about each incrementally parsed piece of 
code.
   std::list PTUs;
 
@@ -129,7 +132,8 @@ class Interpreter {
 public:
   virtual ~Interpreter();
   static llvm::Expected>
-  create(std::unique_ptr CI);
+  create(std::unique_ptr CI,
+ std::unique_ptr DeviceCI = nullptr);
   static llvm::Expected>
   createWithCUDA(std::unique_ptr CI,
  std::unique_ptr DCI);
@@ -175,10 +179,11 @@ class Interpreter {
   llvm::Expected ExtractValueFromExpr(Expr *E);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
-  CodeGenerator *getCodeGen() const;
-  std::unique_ptr GenModule();
+  CodeGenerator *getCodeGen(IncrementalAction *Action = nullptr) const;
+  std::unique_ptr GenModule(IncrementalAction *Action = nullptr);
   PartialTranslationUnit &RegisterPTU(TranslationUnitDecl *TU,
-  std::unique_ptr M = {});
+  std::unique_ptr M = {},
+  IncrementalAction *Action = nullptr);
 
   // A cache for the compiled destructors used to for de-allocation of managed
   // clang::Values.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp 
b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..6977d7fa674ab 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)
+llvm::Error &Err, std::list &PTUs)
 : IncrementalParser(*DeviceInstance, Err), PTUs(PTUs), VFS(FS),
   CodeGenOpts(HostInstance.getCodeGenOpts()),
-  TargetOpts(HostInstance.getTargetOpts()) {
+  TargetOpts(DeviceInstance->getTargetOpts()) {
   if (Err)
 return;
-  DeviceCI = std::move(DeviceInstance);
   StringRef Arch = TargetOpts.CPU;
   if (!Arch.starts_with("sm_") || Arch.substr(3).getAsInteger(10, SMVersion)) {
+DeviceInstance.release();
 Err = llvm::joinErrors(std::move(Err), llvm::make_error(
"Invalid CUDA architecture",

llvm::inconvertibleErrorCode()));
 return;
   }
+  DeviceCI = std::move(DeviceInstance);
 }
 
 llvm::Expected
@@ -50,25 +51,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();
-  if (!PTX)
-return PTX.takeError();
-
-  auto Err = GenerateFatbinary();
-  if (Err)
-return std::move(Err);
-
-  std::string FatbinFileName =
-  "/incr_module_" + std::to_string(PTUs.size()) + ".fatbin";
-  VFS->addFile(FatbinFileName, 0,
-   llvm::MemoryBuffer::getMemBuffer(
-   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
-   "", false));
-
-  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
-
-  FatbinContent.clear();
-
   return PTU;
 }
 
@@ -78,9 +60,11 @@ llvm::Expected 
IncrementalCUDADeviceParser::GeneratePTX() {
 
   const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
   PTU.TheModule->getTargetTriple(), Error);
-  if (!Target)
+  if (!Target) {
 return llvm::make_error(std::move(Error),
std::error_code());
+  }
+
   llvm::TargetOptions TO = llvm::TargetOptions();
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), TargetOpts.CPU, "", TO,
@@ -172,6 +156,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();
+
+  std::string FatbinFileName = "/" + PTU.TheModule->getName().str() + 
".fatbin";
+
+  VFS->addFile(FatbinFileName, 0,
+   llvm::MemoryBuffer::getMemBuffer(
+   llvm

[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 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 cpp,h -- 
clang/test/AST/static-compound-literals.cpp clang/include/clang/AST/Expr.h 
clang/lib/AST/Expr.cpp clang/lib/AST/ExprConstant.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 95c0f910c..ed56522d1 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3524,7 +3524,7 @@ public:
   }
 
   bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
-  APValue *getOrCreateStaticValue(ASTContext& Ctx) const;
+  APValue *getOrCreateStaticValue(ASTContext &Ctx) const;
   APValue &getStaticValue() const {
 assert(StaticValue);
 return *StaticValue;

``




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


[clang] [clang] Fix a use-after-free in expression evaluation (PR #118480)

2025-04-24 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

Thanks! You're right, it may not address the issue we were seeing. Some of our 
were also ending up with:
```
==3187048==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x1f73c115 in clang::APValue::operator=(clang::APValue&&) 
(/netbatch/donb2642835_00/runDir/dir/workspace/NIT/xmain/LX/xmainefi2linux_msan/ws/icsws/builds/xmainefi2linux_sprodusingprod/llvm/bin/clang-21+0x1f73c115)
```


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


[clang] [llvm] [RISCV] Allow `Zicsr`/`Zifencei` to duplicate with `g` (PR #136842)

2025-04-24 Thread Alex Bradbury via cfe-commits

asb wrote:

> If you're planning on backporting this, should the release notes be added in 
> a separate commit? I'm wondering if you'll end up with issues trying to 
> cherry-pick it otherwise

I think we'd typically land a change in the most logical way for the main 
branch and then handle unpicking the backport manually - it just means the 
tooling needs a little bit of help but it's not complex to manually drop the 
release note change. I don't feel strongly given what a minor detail it is, but 
that would be my default.

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

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


[clang-tools-extra] [clang-tidy] Add check 'bugprone-invalid-enum-default-initialization' (PR #136823)

2025-04-24 Thread Balázs Kéri via cfe-commits

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

From 4ce7497bb0dc89de3b9f139177c295291e7d3e9c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Thu, 17 Apr 2025 17:36:03 +0200
Subject: [PATCH 1/2] [clang-tidy] Add check
 'bugprone-invalid-enum-default-initialization'

---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 .../InvalidEnumDefaultInitializationCheck.cpp | 114 +
 .../InvalidEnumDefaultInitializationCheck.h   |  32 +
 .../invalid-enum-default-initialization.rst   |  50 
 .../invalid-enum-default-initialization.cpp   | 116 ++
 6 files changed, 316 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/invalid-enum-default-initialization.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/invalid-enum-default-initialization.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index b780a85bdf3fe..893dd140c92b0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -38,6 +38,7 @@
 #include "IncorrectRoundingsCheck.h"
 #include "InfiniteLoopCheck.h"
 #include "IntegerDivisionCheck.h"
+#include "InvalidEnumDefaultInitializationCheck.h"
 #include "LambdaFunctionNameCheck.h"
 #include "MacroParenthesesCheck.h"
 #include "MacroRepeatedSideEffectsCheck.h"
@@ -164,6 +165,8 @@ class BugproneModule : public ClangTidyModule {
 CheckFactories.registerCheck("bugprone-infinite-loop");
 CheckFactories.registerCheck(
 "bugprone-integer-division");
+CheckFactories.registerCheck(
+"bugprone-invalid-enum-default-initialization");
 CheckFactories.registerCheck(
 "bugprone-lambda-function-name");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index e310ea9c94543..bf142575becfb 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -30,6 +30,7 @@ add_clang_library(clangTidyBugproneModule STATIC
   InaccurateEraseCheck.cpp
   IncorrectEnableIfCheck.cpp
   IncorrectEnableSharedFromThisCheck.cpp
+  InvalidEnumDefaultInitializationCheck.cpp
   UnintendedCharOstreamOutputCheck.cpp
   ReturnConstRefFromParameterCheck.cpp
   SuspiciousStringviewDataUsageCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp
 
b/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp
new file mode 100644
index 0..152c2468cd121
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp
@@ -0,0 +1,114 @@
+//===--- InvalidEnumDefaultInitializationCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "InvalidEnumDefaultInitializationCheck.h"
+// #include "../utils/Matchers.h"
+// #include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER(EnumDecl, isCompleteAndHasNoZeroValue) {
+  const EnumDecl *Definition = Node.getDefinition();
+  return Definition && Node.isComplete() &&
+ std::none_of(Definition->enumerator_begin(),
+  Definition->enumerator_end(),
+  [](const EnumConstantDecl *Value) {
+return Value->getInitVal().isZero();
+  });
+}
+
+AST_MATCHER(Expr, isEmptyInit) {
+  if (isa(&Node))
+return true;
+  if (isa(&Node))
+return true;
+  if (const auto *Init = dyn_cast(&Node))
+return Init->getNumInits() == 0;
+  return false;
+}
+
+} // namespace
+
+InvalidEnumDefaultInitializationCheck::InvalidEnumDefaultInitializationCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {}
+
+bool InvalidEnumDefaultInitializationCheck::isLanguageVersionSupported(
+const LangOptions &LangOpts) const {
+  return LangOpts.CPlusPlus;
+}
+
+void InvalidEnumDefaultInitializationCheck::registerMatchers(
+MatchFinder *Finder) {
+  Finder->addMatcher(
+  expr(isEmptyInit(),
+   hasType(hasUnqualifiedDesugaredTyp

[clang] [clang] fix unresolved dependent template specialization mangling (PR #135111)

2025-04-24 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -399,3 +399,20 @@ namespace type_qualifier {
   // CHECK: @_ZN14type_qualifier1gIPiEEvDTcmcvv_ELi1EE
   template void g(int);
 }
+
+namespace unresolved_template_specialization_type {
+  template  struct enable_if {};
+  struct Foo {
+static const int value = true;
+  };
+  struct HashStateBase {
+template  using is_hashable = Foo;
+  };
+  template  struct raw_hash_set {
+template 
+static enable_if::value>
+AbslHashValue() {}
+  };
+  template enable_if raw_hash_set::AbslHashValue();
+  // CHECH: 
@_ZN39unresolved_template_specialization_type12raw_hash_setIiE13AbslHashValueINS_13HashStateBaseEEENS_9enable_ifIXsrNT_11is_hashableIiEE5valueEEEv

OCHyams wrote:

@mizvekov miss-spelled `CHECK`? (`CHECH` ). Looks like it's still [in 
tree](https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGenCXX/mangle-template.cpp#L417)
 atm.

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


[clang] [clang] Do not share ownership of `HeaderSearchOptions` (PR #132984)

2025-04-24 Thread Balazs Benics via cfe-commits

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

As for the Static Analyzer, if the tests pass, we should be good.
Unique_ptr > shared_ptr for sure!

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


[libclc] [libclc] Remove (vload|vstore)_half helpers (PR #137181)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-amdgpu

Author: Fraser Cormack (frasercrmck)


Changes

These were only being used when compiling with versions of clang older than 
clang 6. As such they were essentially unsuppored and untested.

This somewhat simplifies the codebase, producing fewer helper functions in the 
final builtins library. There's no change to any of the targets' bytecode other 
than removing these helper functions.

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


13 Files Affected:

- (removed) libclc/amdgpu/lib/SOURCES_3.9 (-2) 
- (removed) libclc/amdgpu/lib/SOURCES_4.0 (-2) 
- (removed) libclc/amdgpu/lib/SOURCES_5.0 (-2) 
- (removed) libclc/amdgpu/lib/shared/vload_half_helpers.ll (-31) 
- (removed) libclc/amdgpu/lib/shared/vstore_half_helpers.ll (-43) 
- (modified) libclc/generic/lib/shared/vload.cl (-11) 
- (modified) libclc/generic/lib/shared/vstore.cl (+30-52) 
- (modified) libclc/generic/lib/shared/vstore_half.inc (+21-9) 
- (removed) libclc/ptx/lib/SOURCES_3.9 (-2) 
- (removed) libclc/ptx/lib/SOURCES_4.0 (-2) 
- (removed) libclc/ptx/lib/SOURCES_5.0 (-2) 
- (removed) libclc/ptx/lib/shared/vload_half_helpers.ll (-31) 
- (removed) libclc/ptx/lib/shared/vstore_half_helpers.ll (-43) 


``diff
diff --git a/libclc/amdgpu/lib/SOURCES_3.9 b/libclc/amdgpu/lib/SOURCES_3.9
deleted file mode 100644
index 69c5e5ce9fbac..0
--- a/libclc/amdgpu/lib/SOURCES_3.9
+++ /dev/null
@@ -1,2 +0,0 @@
-shared/vload_half_helpers.ll
-shared/vstore_half_helpers.ll
diff --git a/libclc/amdgpu/lib/SOURCES_4.0 b/libclc/amdgpu/lib/SOURCES_4.0
deleted file mode 100644
index 69c5e5ce9fbac..0
--- a/libclc/amdgpu/lib/SOURCES_4.0
+++ /dev/null
@@ -1,2 +0,0 @@
-shared/vload_half_helpers.ll
-shared/vstore_half_helpers.ll
diff --git a/libclc/amdgpu/lib/SOURCES_5.0 b/libclc/amdgpu/lib/SOURCES_5.0
deleted file mode 100644
index 69c5e5ce9fbac..0
--- a/libclc/amdgpu/lib/SOURCES_5.0
+++ /dev/null
@@ -1,2 +0,0 @@
-shared/vload_half_helpers.ll
-shared/vstore_half_helpers.ll
diff --git a/libclc/amdgpu/lib/shared/vload_half_helpers.ll 
b/libclc/amdgpu/lib/shared/vload_half_helpers.ll
deleted file mode 100644
index bf7d544afbf55..0
--- a/libclc/amdgpu/lib/shared/vload_half_helpers.ll
+++ /dev/null
@@ -1,31 +0,0 @@
-;;===--===;;
-;
-; 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
-;
-;;===--===;;
-
-define float @__clc_vload_half_float_helper__private(half addrspace(0)* 
nocapture %ptr) nounwind alwaysinline {
-  %data = load half, half addrspace(0)* %ptr
-  %res = fpext half %data to float
-  ret float %res
-}
-
-define float @__clc_vload_half_float_helper__global(half addrspace(1)* 
nocapture %ptr) nounwind alwaysinline {
-  %data = load half, half addrspace(1)* %ptr
-  %res = fpext half %data to float
-  ret float %res
-}
-
-define float @__clc_vload_half_float_helper__local(half addrspace(3)* 
nocapture %ptr) nounwind alwaysinline {
-  %data = load half, half addrspace(3)* %ptr
-  %res = fpext half %data to float
-  ret float %res
-}
-
-define float @__clc_vload_half_float_helper__constant(half addrspace(2)* 
nocapture %ptr) nounwind alwaysinline {
-  %data = load half, half addrspace(2)* %ptr
-  %res = fpext half %data to float
-  ret float %res
-}
diff --git a/libclc/amdgpu/lib/shared/vstore_half_helpers.ll 
b/libclc/amdgpu/lib/shared/vstore_half_helpers.ll
deleted file mode 100644
index 5ec193d6d40a0..0
--- a/libclc/amdgpu/lib/shared/vstore_half_helpers.ll
+++ /dev/null
@@ -1,43 +0,0 @@
-;;===--===;;
-;
-; 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
-;
-;;===--===;;
-
-define void @__clc_vstore_half_float_helper__private(float %data, half 
addrspace(0)* nocapture %ptr) nounwind alwaysinline {
-  %res = fptrunc float %data to half
-  store half %res, half addrspace(0)* %ptr
-  ret void
-}
-
-define void @__clc_vstore_half_float_helper__global(float %data, half 
addrspace(1)* nocapture %ptr) nounwind alwaysinline {
-  %res = fptrunc float %data to half
-  store half %res, half addrspace(1)* %ptr
-  ret void
-}
-
-define void @__clc_vstore_half_float_helper__local(float %data, half 
addrspace(3)* nocapture %ptr) nounwind alwaysinline {
-  %res = fptrunc float %data to half
-  store half %res, half addrspace(3)* %ptr
-  ret void
-}
-
-define void @__clc_vstore_half_double_helper__private(double %data, half 
addrspace(0)* nocapture %ptr) nounwind alwaysinline {
-  %res 

[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Vassil Vassilev via cfe-commits


@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)

vgvassilev wrote:

Why removing the const?

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Vassil Vassilev via cfe-commits


@@ -172,6 +154,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();

vgvassilev wrote:

```suggestion
  const PartialTranslationUnit &PTU = PTUs.back();
```

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


[clang] [llvm] [clang][OpenMP][SPIR-V] Fix AS of globals and set the default AS to 4 (PR #135251)

2025-04-24 Thread Nick Sarnie via cfe-commits

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


[clang] [clang][SPIR-V] Fix OpenCL addrspace mapping when using non-zero default AS (PR #137187)

2025-04-24 Thread Nick Sarnie via cfe-commits

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


[clang] 72cc868 - [Clang][NFC] Move temp variable back into the source (#137095)

2025-04-24 Thread via cfe-commits

Author: Shafik Yaghmour
Date: 2025-04-24T08:15:25-07:00
New Revision: 72cc868c65b0641f23d1fb0518a8503c73ecdb5a

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

LOG: [Clang][NFC] Move temp variable back into the source (#137095)

Static analysis flagged this code b/c we are copying the temp variable
back in when we could move it instead.

Added: 


Modified: 
clang/lib/Serialization/ASTReader.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 70b54b7296882..f13a173ec933e 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -5980,7 +5980,7 @@ bool ASTReader::readASTFileControlBlock(
}
   }
 }
-Stream = SavedStream;
+Stream = std::move(SavedStream);
   }
 
   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.



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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits


@@ -760,8 +787,10 @@ std::unique_ptr Interpreter::GenModule() {
   return nullptr;
 }
 
-CodeGenerator *Interpreter::getCodeGen() const {
-  FrontendAction *WrappedAct = Act->getWrapped();
+CodeGenerator *Interpreter::getCodeGen(IncrementalAction *Action) const {
+  if (!Action)
+Action = Act.get();
+  FrontendAction *WrappedAct = Action->getWrapped();

anutosh491 wrote:

Yupp. Basically this comment 
https://github.com/llvm/llvm-project/pull/136404#discussion_r2058443908

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


[clang] [Clang][NFC] Move temp variable back into the source (PR #137095)

2025-04-24 Thread Shafik Yaghmour via cfe-commits

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


[clang] [clang][SPIR-V] Fix OpenCL addrspace mapping when using non-zero default AS (PR #137187)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nick Sarnie (sarnex)


Changes

Based on feedback from https://github.com/llvm/llvm-project/pull/136753, remove 
the dummy values for OpenCL and make them match the zero default AS map.

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


1 Files Affected:

- (modified) clang/lib/Basic/Targets/SPIR.h (+5-7) 


``diff
diff --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 310ef9f2df2c6..bf249e271a870 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -58,15 +58,13 @@ static const unsigned SPIRDefIsPrivMap[] = {
 // Used by both the SPIR and SPIR-V targets.
 static const unsigned SPIRDefIsGenMap[] = {
 4, // Default
-// Some OpenCL address space values for this map are dummy and they can't 
be
-// used
 1, // opencl_global
-0, // opencl_local
-0, // opencl_constant
+3, // opencl_local
+2, // opencl_constant
 0, // opencl_private
-0, // opencl_generic
-0, // opencl_global_device
-0, // opencl_global_host
+4, // opencl_generic
+5, // opencl_global_device
+6, // opencl_global_host
 // cuda_* address space mapping is intended for HIPSPV (HIP to SPIR-V
 // translation). This mapping is enabled when the language mode is HIP.
 1, // cuda_device

``




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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Gábor Horváth via cfe-commits


@@ -2523,6 +2523,20 @@ bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
   return true;
 }
 
+/// Return the innermost location context which is inlined at `Node`, unless
+/// it's the top-level (entry point) location context.
+static const LocationContext *getInlinedLocationContext(ExplodedNode *Node,
+ExplodedGraph &G) {
+  const LocationContext *CalleeLC = Node->getLocation().getLocationContext();
+  const LocationContext *RootLC =

Xazax-hun wrote:

Could we have multiple roots? What if we pick the wrong one?

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Gábor Horváth via cfe-commits


@@ -414,6 +414,20 @@ ANALYZER_OPTION(
 "any target.",
 true)
 
+ANALYZER_OPTION(
+bool, LegacyInliningPrevention, "legacy-inlining-prevention",
+"If enabled, the analyzer puts functions on a \"do not inline this\" list "
+"if it finds an execution path within that function that may potentially "
+"perform 'analyzer-max-loop' (= 4 by default) iterations in a loop. "
+"Note that functions that _definitely_ reach the loop limit on some "
+"execution path are currently marked as \"do not inline\" even if this "
+"option is disabled (but this may change in future versions). This option "
+"is a dumb and arbitrary restriction on inlining, but disabling it would "

Xazax-hun wrote:

Nit: I'd remove "dumb" from the user facing string. 

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Gábor Horváth via cfe-commits


@@ -2856,8 +2873,29 @@ void ExprEngine::processBranch(
   // conflicts with the widen-loop analysis option (which is off by
   // default). If we intend to support and stabilize the loop widening,
   // we must ensure that it 'plays nicely' with this logic.
-  if (!SkipTrueBranch || AMgr.options.ShouldWidenLoops)
+  if (!SkipTrueBranch || AMgr.options.ShouldWidenLoops) {
 Builder.generateNode(StTrue, true, PredN);
+  } else if (AMgr.options.LegacyInliningPrevention) {
+// FIXME: There is an ancient and very arbitrary heuristic in
+// `ExprEngine::processCFGBlockEntrance` which prevents all further
+// inlining of a function if it finds an execution path within that
+// function which reaches the `MaxBlockVisitOnPath` limit (a/k/a
+// `analyzer-max-loop`, by default four iterations in a loop). Adding
+// this "don't assume third iteration" logic significantly increased
+// the analysis runtime on some inputs because less functions were
+// arbitrarily excluded from being inlined, so more entrypoints used
+// up their full allocated budget. As a hacky compensation for this,
+// here we apply the "should not inline" mark in cases when the loop
+// could potentially reach the `MaxBlockVisitOnPath` limit without the
+// "don't assume third iteration" logic. This slightly overcompensates
+// (activates if the third iteration can be entered, and will not
+// recognize cases where the fourth iteration would't be completed), 
but
+// should be good enough for practical purposes.
+if (const LocationContext *LC = getInlinedLocationContext(Pred, G)) {
+  Engine.FunctionSummaries->markShouldNotInline(
+  LC->getStackFrame()->getDecl());
+}
+  }

Xazax-hun wrote:

Also I am not sure we should have legacy in the name of something that is 
enabled by default. 

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Gábor Horváth via cfe-commits


@@ -2570,21 +2584,24 @@ void ExprEngine::processCFGBlockEntrance(const 
BlockEdge &L,
 const ExplodedNode *Sink =
nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
 
-// Check if we stopped at the top level function or not.
-// Root node should have the location context of the top most function.
-const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
-const LocationContext *CalleeSF = CalleeLC->getStackFrame();
-const LocationContext *RootLC =
-(*G.roots_begin())->getLocation().getLocationContext();
-if (RootLC->getStackFrame() != CalleeSF) {
-  Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
+if (const LocationContext *LC = getInlinedLocationContext(Pred, G)) {
+  // FIXME: This will unconditionally prevent inlining this function (even
+  // from other entrypoints), which is not a reasonable heuristic: even if

Xazax-hun wrote:

Nit: I think entry points are two distinct  words. 

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/136404

>From 6c64e64c4a3b56f50808cae244b29da1231525f1 Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Fri, 18 Apr 2025 18:45:00 +0530
Subject: [PATCH 1/3] Fix cuda flag with clang-repl

---
 clang/include/clang/Interpreter/Interpreter.h | 13 ++--
 clang/lib/Interpreter/DeviceOffload.cpp   | 39 ++--
 clang/lib/Interpreter/DeviceOffload.h |  4 +-
 clang/lib/Interpreter/Interpreter.cpp | 59 ++-
 4 files changed, 72 insertions(+), 43 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b1b63aedf86ab..56213f88b9e30 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -41,6 +41,7 @@ class CXXRecordDecl;
 class Decl;
 class IncrementalExecutor;
 class IncrementalParser;
+class IncrementalCUDADeviceParser;
 
 /// Create a pre-configured \c CompilerInstance for incremental processing.
 class IncrementalCompilerBuilder {
@@ -93,7 +94,10 @@ class Interpreter {
   std::unique_ptr IncrExecutor;
 
   // An optional parser for CUDA offloading
-  std::unique_ptr DeviceParser;
+  std::unique_ptr DeviceParser;
+
+  // An optional action for CUDA offloading
+  std::unique_ptr DeviceAct;
 
   /// List containing information about each incrementally parsed piece of 
code.
   std::list PTUs;
@@ -175,10 +179,11 @@ class Interpreter {
   llvm::Expected ExtractValueFromExpr(Expr *E);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
-  CodeGenerator *getCodeGen() const;
-  std::unique_ptr GenModule();
+  CodeGenerator *getCodeGen(IncrementalAction *Action = nullptr) const;
+  std::unique_ptr GenModule(IncrementalAction *Action = nullptr);
   PartialTranslationUnit &RegisterPTU(TranslationUnitDecl *TU,
-  std::unique_ptr M = {});
+  std::unique_ptr M = {},
+  IncrementalAction *Action = nullptr);
 
   // A cache for the compiled destructors used to for de-allocation of managed
   // clang::Values.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp 
b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..d9b00787f038d 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)
+llvm::Error &Err, std::list &PTUs)
 : IncrementalParser(*DeviceInstance, Err), PTUs(PTUs), VFS(FS),
   CodeGenOpts(HostInstance.getCodeGenOpts()),
-  TargetOpts(HostInstance.getTargetOpts()) {
+  TargetOpts(DeviceInstance->getTargetOpts()) {
   if (Err)
 return;
-  DeviceCI = std::move(DeviceInstance);
   StringRef Arch = TargetOpts.CPU;
   if (!Arch.starts_with("sm_") || Arch.substr(3).getAsInteger(10, SMVersion)) {
+DeviceInstance.release();
 Err = llvm::joinErrors(std::move(Err), llvm::make_error(
"Invalid CUDA architecture",

llvm::inconvertibleErrorCode()));
 return;
   }
+  DeviceCI = std::move(DeviceInstance);
 }
 
 llvm::Expected
@@ -50,25 +51,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();
-  if (!PTX)
-return PTX.takeError();
-
-  auto Err = GenerateFatbinary();
-  if (Err)
-return std::move(Err);
-
-  std::string FatbinFileName =
-  "/incr_module_" + std::to_string(PTUs.size()) + ".fatbin";
-  VFS->addFile(FatbinFileName, 0,
-   llvm::MemoryBuffer::getMemBuffer(
-   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
-   "", false));
-
-  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
-
-  FatbinContent.clear();
-
   return PTU;
 }
 
@@ -172,6 +154,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();
+
+  std::string FatbinFileName = "/" + PTU.TheModule->getName().str() + 
".fatbin";
+
+  VFS->addFile(FatbinFileName, 0,
+   llvm::MemoryBuffer::getMemBuffer(
+   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
+   "", false));
+
+  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
+
+  FatbinContent.clear();
+
   return llvm::Error::success();
 }
 
diff --git a/clang/lib/Interpreter/DeviceOffload.h 
b/clang/lib/Interpreter/DeviceOffload.h
index b9a1acab004c3..23d89046c09e1 100644
--- a/clang/lib/Interpreter/DeviceOffload.h
+++ b/clang/lib/Interpreter/DeviceOffload.h
@@ -24,14 +24,14 @@ class CodeGenOptions;
 class TargetOptions;
 
 class IncrementalCUDA

[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits


@@ -414,6 +414,20 @@ ANALYZER_OPTION(
 "any target.",
 true)
 
+ANALYZER_OPTION(
+bool, LegacyInliningPrevention, "legacy-inlining-prevention",
+"If enabled, the analyzer puts functions on a \"do not inline this\" list "
+"if it finds an execution path within that function that may potentially "
+"perform 'analyzer-max-loop' (= 4 by default) iterations in a loop. "
+"Note that functions that _definitely_ reach the loop limit on some "
+"execution path are currently marked as \"do not inline\" even if this "
+"option is disabled (but this may change in future versions). This option "
+"is a dumb and arbitrary restriction on inlining, but disabling it would "

NagyDonat wrote:

Good point, I was annoyed by the situation when I wrote this description, but I 
was already planning to rewrite these before finalizing the commit.

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits


@@ -50,25 +50,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();

anutosh491 wrote:

Yes absolutely !

Sorry for overlooking this. Made the change.

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits


@@ -2570,21 +2584,24 @@ void ExprEngine::processCFGBlockEntrance(const 
BlockEdge &L,
 const ExplodedNode *Sink =
nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
 
-// Check if we stopped at the top level function or not.
-// Root node should have the location context of the top most function.
-const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
-const LocationContext *CalleeSF = CalleeLC->getStackFrame();
-const LocationContext *RootLC =
-(*G.roots_begin())->getLocation().getLocationContext();
-if (RootLC->getStackFrame() != CalleeSF) {
-  Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
+if (const LocationContext *LC = getInlinedLocationContext(Pred, G)) {
+  // FIXME: This will unconditionally prevent inlining this function (even
+  // from other entrypoints), which is not a reasonable heuristic: even if

NagyDonat wrote:

Thanks for spotting this! For some reason I tend to automatically write 
"entrypoint"; before uploading the PR I fixed it in many locations, but 
apparently I failed to catch this one...

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


[clang] [CIR] Cleanup support for C functions (PR #136854)

2025-04-24 Thread Iris Shi via cfe-commits

https://github.com/el-ev updated 
https://github.com/llvm/llvm-project/pull/136854

>From fd1d37ebf0f1c4a23f573444f30730b0f65630bf Mon Sep 17 00:00:00 2001
From: Iris Shi <0...@owo.li>
Date: Wed, 23 Apr 2025 20:23:09 +0800
Subject: [PATCH 1/2] [CIR] Cleanup support for C functions

---
 clang/lib/CIR/CodeGen/CIRGenCall.cpp   | 82 +++-
 clang/lib/CIR/CodeGen/CIRGenFunctionInfo.h | 90 +-
 clang/lib/CIR/CodeGen/CIRGenModule.cpp | 17 +++-
 clang/lib/CIR/CodeGen/CIRGenTypes.cpp  | 37 -
 clang/lib/CIR/CodeGen/CIRGenTypes.h| 12 ++-
 clang/lib/CIR/CodeGen/TargetInfo.cpp   | 10 ++-
 clang/test/CIR/CodeGen/basic.c | 13 
 7 files changed, 232 insertions(+), 29 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenCall.cpp 
b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
index 69266f79a88a5..b223bc494f928 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCall.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
@@ -13,20 +13,76 @@
 
 #include "CIRGenCall.h"
 #include "CIRGenFunction.h"
+#include "CIRGenFunctionInfo.h"
 #include "clang/CIR/MissingFeatures.h"
 
 using namespace clang;
 using namespace clang::CIRGen;
 
-CIRGenFunctionInfo *CIRGenFunctionInfo::create(CanQualType resultType) {
-  void *buffer = operator new(totalSizeToAlloc(1));
+CIRGenFunctionInfo *
+CIRGenFunctionInfo::create(CanQualType resultType,
+   llvm::ArrayRef argTypes,
+   RequiredArgs required) {
+  void *buffer = operator new(totalSizeToAlloc(argTypes.size() + 1));
 
   CIRGenFunctionInfo *fi = new (buffer) CIRGenFunctionInfo();
+
+  fi->required = required;
+  fi->numArgs = argTypes.size();
   fi->getArgsBuffer()[0].type = resultType;
+  for (unsigned i = 0; i < argTypes.size(); ++i)
+fi->getArgsBuffer()[i + 1].type = argTypes[i];
 
   return fi;
 }
 
+cir::FuncType CIRGenTypes::getFunctionType(const CIRGenFunctionInfo &fi) {
+  bool inserted = functionsBeingProcessed.insert(&fi).second;
+  assert(inserted && "Recursively being processed?");
+
+  mlir::Type resultType = nullptr;
+  const cir::ABIArgInfo &retAI = fi.getReturnInfo();
+
+  switch (retAI.getKind()) {
+  case cir::ABIArgInfo::Ignore:
+// TODO(CIR): This should probably be the None type from the builtin
+// dialect.
+resultType = nullptr;
+break;
+
+  case cir::ABIArgInfo::Direct:
+resultType = retAI.getCoerceToType();
+break;
+
+  default:
+assert(false && "NYI");
+  }
+
+  SmallVector argTypes;
+  unsigned argNo = 0;
+  CIRGenFunctionInfo::const_arg_iterator it = fi.arg_begin(),
+ ie = it + fi.getNumRequiredArgs();
+  for (; it != ie; ++it, ++argNo) {
+const auto &argInfo = it->info;
+
+switch (argInfo.getKind()) {
+default:
+  llvm_unreachable("NYI");
+case cir::ABIArgInfo::Direct:
+  mlir::Type argType = argInfo.getCoerceToType();
+  argTypes.push_back(argType);
+  break;
+}
+  }
+
+  bool erased = functionsBeingProcessed.erase(&fi);
+  assert(erased && "Not in set?");
+
+  return cir::FuncType::get(argTypes,
+(resultType ? resultType : builder.getVoidTy()),
+fi.isVariadic());
+}
+
 CIRGenCallee CIRGenCallee::prepareConcreteCallee(CIRGenFunction &cgf) const {
   assert(!cir::MissingFeatures::opCallVirtual());
   return *this;
@@ -35,6 +91,9 @@ CIRGenCallee 
CIRGenCallee::prepareConcreteCallee(CIRGenFunction &cgf) const {
 static const CIRGenFunctionInfo &
 arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule &cgm,
 const FunctionType *fnType) {
+
+  RequiredArgs required = RequiredArgs::All;
+
   if (const auto *proto = dyn_cast(fnType)) {
 if (proto->isVariadic())
   cgm.errorNYI("call to variadic function");
@@ -49,7 +108,7 @@ arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule 
&cgm,
   CanQualType retType = fnType->getReturnType()
 ->getCanonicalTypeUnqualified()
 .getUnqualifiedType();
-  return cgt.arrangeCIRFunctionInfo(retType);
+  return cgt.arrangeCIRFunctionInfo(retType, {}, required);
 }
 
 const CIRGenFunctionInfo &
@@ -71,6 +130,23 @@ static cir::CIRCallOpInterface 
emitCallLikeOp(CIRGenFunction &cgf,
   return builder.createCallOp(callLoc, directFuncOp);
 }
 
+const CIRGenFunctionInfo &
+CIRGenTypes::arrangeFreeFunctionType(CanQual fpt) {
+  SmallVector argTypes;
+  for (unsigned i = 0, e = fpt->getNumParams(); i != e; ++i)
+argTypes.push_back(fpt->getParamType(i));
+  RequiredArgs required = RequiredArgs::forPrototypePlus(fpt);
+
+  CanQualType resultType = fpt->getReturnType().getUnqualifiedType();
+  return arrangeCIRFunctionInfo(resultType, argTypes, required);
+}
+
+const CIRGenFunctionInfo &
+CIRGenTypes::arrangeFreeFunctionType(CanQual fnpt) {
+  CanQualType resultType = fnpt->getReturnType().getUnqualifiedType();
+  return arrangeCIRFunctionInfo(resultType, {}, RequiredArgs(0));

[clang] [clang-tools-extra] [flang] [lldb] [llvm] [mlir] [openmp] [polly] [Documentation] Always use SVG for dot-generated doxygen images. (PR #136843)

2025-04-24 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

I think the changes LG, but please wait for our CMake experts (@petrhosek and 
@Ericson2314) to review before landing.

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


[clang] [clang] Do not share ownership of `HeaderSearchOptions` (PR #132984)

2025-04-24 Thread Aaron Ballman via cfe-commits


@@ -569,7 +569,7 @@ 
CrossTranslationUnitContext::ASTLoader::loadFromDump(StringRef ASTDumpPath) {
   return ASTUnit::LoadFromASTFile(
   ASTDumpPath, CI.getPCHContainerOperations()->getRawReader(),
   ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(),
-  CI.getHeaderSearchOptsPtr());
+  CI.getHeaderSearchOpts());

AaronBallman wrote:

CC @haoNoQ @steakhal as well

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


[clang] [analyzer] Workaround for unintended slowdown (scope increase) (PR #136720)

2025-04-24 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,198 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-verify=expected,default %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-config legacy-inlining-prevention=false -verify=expected,disabled %s
+
+int getNum(void); // Get an opaque number.
+
+void clang_analyzer_numTimesReached(void);
+void clang_analyzer_dump(int arg);
+
+//-
+// Simple case: inlined function never reaches `analyzer-max-loop`.
+
+int inner_simple(void) {
+  clang_analyzer_numTimesReached(); // expected-warning {{2}}
+  return 42;
+}
+
+int outer_simple(void) {
+  int x = inner_simple();
+  int y = inner_simple();
+  return 53 / (x - y); // expected-warning {{Division by zero}}
+}
+
+//-
+// Inlined function always reaches `analyzer-max-loop`.
+
+int inner_fixed_loop_1(void) {
+  int i;
+  clang_analyzer_numTimesReached(); // expected-warning {{1}}
+  for (i = 0; i < 10; i++);
+  clang_analyzer_numTimesReached(); // no-warning

NagyDonat wrote:

IMO the situation is complex because:
- from the POV of the users this "analysis is stopped by long loops" behavior 
is obviously a bug that needs to be fixed;
- but from the  POV of the inlining prevention heuristic (which is tested here) 
this is a known feature (or at least "property") of the analyzer engine which 
is important for the correct delineation of the scope.

You're right that these deserve a FIXME, but I'll probably write a longer FIXME 
block that explains the full situation instead of short inline FIXME notes.

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


[clang] [llvm] [clang][OpenMP][SPIR-V] Fix AS of globals and set the default AS to 4 (PR #135251)

2025-04-24 Thread Alexander Kornienko via cfe-commits

alexfh wrote:

> I'm going to separate out the CUDA SPIRV regression fix as I need to fix some 
> problems with this PR, will add you as a reviewer.

Do you have a timeline? It would be nice to get this fixed soon.

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


[clang] [CIR] Cleanup support for C functions (PR #136854)

2025-04-24 Thread Iris Shi via cfe-commits

https://github.com/el-ev updated 
https://github.com/llvm/llvm-project/pull/136854

>From fd1d37ebf0f1c4a23f573444f30730b0f65630bf Mon Sep 17 00:00:00 2001
From: Iris Shi <0...@owo.li>
Date: Wed, 23 Apr 2025 20:23:09 +0800
Subject: [PATCH 1/2] [CIR] Cleanup support for C functions

---
 clang/lib/CIR/CodeGen/CIRGenCall.cpp   | 82 +++-
 clang/lib/CIR/CodeGen/CIRGenFunctionInfo.h | 90 +-
 clang/lib/CIR/CodeGen/CIRGenModule.cpp | 17 +++-
 clang/lib/CIR/CodeGen/CIRGenTypes.cpp  | 37 -
 clang/lib/CIR/CodeGen/CIRGenTypes.h| 12 ++-
 clang/lib/CIR/CodeGen/TargetInfo.cpp   | 10 ++-
 clang/test/CIR/CodeGen/basic.c | 13 
 7 files changed, 232 insertions(+), 29 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenCall.cpp 
b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
index 69266f79a88a5..b223bc494f928 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCall.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCall.cpp
@@ -13,20 +13,76 @@
 
 #include "CIRGenCall.h"
 #include "CIRGenFunction.h"
+#include "CIRGenFunctionInfo.h"
 #include "clang/CIR/MissingFeatures.h"
 
 using namespace clang;
 using namespace clang::CIRGen;
 
-CIRGenFunctionInfo *CIRGenFunctionInfo::create(CanQualType resultType) {
-  void *buffer = operator new(totalSizeToAlloc(1));
+CIRGenFunctionInfo *
+CIRGenFunctionInfo::create(CanQualType resultType,
+   llvm::ArrayRef argTypes,
+   RequiredArgs required) {
+  void *buffer = operator new(totalSizeToAlloc(argTypes.size() + 1));
 
   CIRGenFunctionInfo *fi = new (buffer) CIRGenFunctionInfo();
+
+  fi->required = required;
+  fi->numArgs = argTypes.size();
   fi->getArgsBuffer()[0].type = resultType;
+  for (unsigned i = 0; i < argTypes.size(); ++i)
+fi->getArgsBuffer()[i + 1].type = argTypes[i];
 
   return fi;
 }
 
+cir::FuncType CIRGenTypes::getFunctionType(const CIRGenFunctionInfo &fi) {
+  bool inserted = functionsBeingProcessed.insert(&fi).second;
+  assert(inserted && "Recursively being processed?");
+
+  mlir::Type resultType = nullptr;
+  const cir::ABIArgInfo &retAI = fi.getReturnInfo();
+
+  switch (retAI.getKind()) {
+  case cir::ABIArgInfo::Ignore:
+// TODO(CIR): This should probably be the None type from the builtin
+// dialect.
+resultType = nullptr;
+break;
+
+  case cir::ABIArgInfo::Direct:
+resultType = retAI.getCoerceToType();
+break;
+
+  default:
+assert(false && "NYI");
+  }
+
+  SmallVector argTypes;
+  unsigned argNo = 0;
+  CIRGenFunctionInfo::const_arg_iterator it = fi.arg_begin(),
+ ie = it + fi.getNumRequiredArgs();
+  for (; it != ie; ++it, ++argNo) {
+const auto &argInfo = it->info;
+
+switch (argInfo.getKind()) {
+default:
+  llvm_unreachable("NYI");
+case cir::ABIArgInfo::Direct:
+  mlir::Type argType = argInfo.getCoerceToType();
+  argTypes.push_back(argType);
+  break;
+}
+  }
+
+  bool erased = functionsBeingProcessed.erase(&fi);
+  assert(erased && "Not in set?");
+
+  return cir::FuncType::get(argTypes,
+(resultType ? resultType : builder.getVoidTy()),
+fi.isVariadic());
+}
+
 CIRGenCallee CIRGenCallee::prepareConcreteCallee(CIRGenFunction &cgf) const {
   assert(!cir::MissingFeatures::opCallVirtual());
   return *this;
@@ -35,6 +91,9 @@ CIRGenCallee 
CIRGenCallee::prepareConcreteCallee(CIRGenFunction &cgf) const {
 static const CIRGenFunctionInfo &
 arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule &cgm,
 const FunctionType *fnType) {
+
+  RequiredArgs required = RequiredArgs::All;
+
   if (const auto *proto = dyn_cast(fnType)) {
 if (proto->isVariadic())
   cgm.errorNYI("call to variadic function");
@@ -49,7 +108,7 @@ arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule 
&cgm,
   CanQualType retType = fnType->getReturnType()
 ->getCanonicalTypeUnqualified()
 .getUnqualifiedType();
-  return cgt.arrangeCIRFunctionInfo(retType);
+  return cgt.arrangeCIRFunctionInfo(retType, {}, required);
 }
 
 const CIRGenFunctionInfo &
@@ -71,6 +130,23 @@ static cir::CIRCallOpInterface 
emitCallLikeOp(CIRGenFunction &cgf,
   return builder.createCallOp(callLoc, directFuncOp);
 }
 
+const CIRGenFunctionInfo &
+CIRGenTypes::arrangeFreeFunctionType(CanQual fpt) {
+  SmallVector argTypes;
+  for (unsigned i = 0, e = fpt->getNumParams(); i != e; ++i)
+argTypes.push_back(fpt->getParamType(i));
+  RequiredArgs required = RequiredArgs::forPrototypePlus(fpt);
+
+  CanQualType resultType = fpt->getReturnType().getUnqualifiedType();
+  return arrangeCIRFunctionInfo(resultType, argTypes, required);
+}
+
+const CIRGenFunctionInfo &
+CIRGenTypes::arrangeFreeFunctionType(CanQual fnpt) {
+  CanQualType resultType = fnpt->getReturnType().getUnqualifiedType();
+  return arrangeCIRFunctionInfo(resultType, {}, RequiredArgs(0));

[clang] [CIR] Cleanup support for C functions (PR #136854)

2025-04-24 Thread Iris Shi via cfe-commits


@@ -233,6 +233,19 @@ int f8(int *p) {
 // OGCG:   %[[P2:.*]] = load ptr, ptr %[[P_PTR]], align 8
 // OGCG:   %[[STAR_P:.*]] = load i32, ptr %[[P2]], align 4
 
+
+void f9() {}

el-ev wrote:

 I'm actually unsure what kind of new tests would be appropriate. Do you have 
any suggestions on what I should add?

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


[clang] [clang][bytecode] Diagnose comparing pointers to fields... (PR #137159)

2025-04-24 Thread Timm Baeder via cfe-commits

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

... with different access specifiers.

>From a4c3afca1ef1d029aea8c70d83195100e48b39e3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 24 Apr 2025 13:19:25 +0200
Subject: [PATCH] [clang][bytecode] Diagnose comparing pointers to fields...

... with different access specifiers.
---
 clang/lib/AST/ByteCode/Interp.h | 13 +
 clang/lib/AST/ByteCode/Pointer.cpp  | 42 +
 clang/lib/AST/ByteCode/Pointer.h|  9 ++-
 clang/test/AST/ByteCode/records.cpp | 23 
 4 files changed, 86 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 99b032bee9e3d..0a52a64240c04 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1007,6 +1007,19 @@ inline bool CmpHelper(InterpState &S, CodePtr 
OpPC, CompareFn Fn) {
 return false;
   }
 
+  // Diagnose comparisons between fields with different access specifiers.
+  if (std::optional> Split =
+  Pointer::computeSplitPoint(LHS, RHS)) {
+const FieldDecl *LF = Split->first.getField();
+const FieldDecl *RF = Split->second.getField();
+if (LF && RF && !LF->getParent()->isUnion() &&
+LF->getAccess() != RF->getAccess()) {
+  S.CCEDiag(S.Current->getSource(OpPC),
+diag::note_constexpr_pointer_comparison_differing_access)
+  << LF << LF->getAccess() << RF << RF->getAccess() << LF->getParent();
+}
+  }
+
   unsigned VL = LHS.getByteOffset();
   unsigned VR = RHS.getByteOffset();
   S.Stk.push(BoolT::from(Fn(Compare(VL, VR;
diff --git a/clang/lib/AST/ByteCode/Pointer.cpp 
b/clang/lib/AST/ByteCode/Pointer.cpp
index 059503cae3561..8adfd7a1f98d8 100644
--- a/clang/lib/AST/ByteCode/Pointer.cpp
+++ b/clang/lib/AST/ByteCode/Pointer.cpp
@@ -571,6 +571,48 @@ bool Pointer::pointsToLiteral() const {
   return E && !isa(E);
 }
 
+std::optional>
+Pointer::computeSplitPoint(const Pointer &A, const Pointer &B) {
+  if (!A.isBlockPointer() || !B.isBlockPointer())
+return std::nullopt;
+
+  if (A.asBlockPointer().Pointee != B.asBlockPointer().Pointee)
+return std::nullopt;
+  if (A.isRoot() && B.isRoot())
+return std::nullopt;
+
+  if (A == B)
+return std::make_pair(A, B);
+
+  auto getBase = [](const Pointer &P) -> Pointer {
+if (P.isArrayElement())
+  return P.getArray();
+return P.getBase();
+  };
+
+  Pointer IterA = A;
+  Pointer IterB = B;
+  Pointer CurA = IterA;
+  Pointer CurB = IterB;
+  for (;;) {
+if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
+  CurA = IterA;
+  IterA = getBase(IterA);
+} else {
+  CurB = IterB;
+  IterB = getBase(IterB);
+}
+
+if (IterA == IterB)
+  return std::make_pair(CurA, CurB);
+
+if (IterA.isRoot() && IterB.isRoot())
+  return std::nullopt;
+  }
+
+  llvm_unreachable("The loop above should've returned.");
+}
+
 std::optional Pointer::toRValue(const Context &Ctx,
  QualType ResultType) const {
   const ASTContext &ASTCtx = Ctx.getASTContext();
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index 8ede706f2736f..e168154a55f58 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -492,7 +492,11 @@ class Pointer {
 return ElemDesc ? ElemDesc->ElemRecord : nullptr;
   }
   /// Returns the field information.
-  const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
+  const FieldDecl *getField() const {
+if (const Descriptor *FD = getFieldDesc())
+  return FD->asFieldDecl();
+return nullptr;
+  }
 
   /// Checks if the storage is extern.
   bool isExtern() const {
@@ -724,6 +728,9 @@ class Pointer {
   /// Checks if both given pointers point to the same block.
   static bool pointToSameBlock(const Pointer &A, const Pointer &B);
 
+  static std::optional>
+  computeSplitPoint(const Pointer &A, const Pointer &B);
+
   /// Whether this points to a block that's been created for a "literal 
lvalue",
   /// i.e. a non-MaterializeTemporaryExpr Expr.
   bool pointsToLiteral() const;
diff --git a/clang/test/AST/ByteCode/records.cpp 
b/clang/test/AST/ByteCode/records.cpp
index da851785323a5..b4059f009b887 100644
--- a/clang/test/AST/ByteCode/records.cpp
+++ b/clang/test/AST/ByteCode/records.cpp
@@ -1787,3 +1787,26 @@ namespace IntegralBaseCast {
 
   static_assert(f() == 0, "");
 }
+
+namespace AccessMismatch {
+  struct A {
+  public:
+constexpr A() : a(0), b(0) {}
+int a;
+constexpr bool cmp() const { return &a < &b; } // both-note {{comparison 
of address of fields 'a' and 'b' of 'A' with differing access specifiers 
(public vs private) has unspecified value}}
+  private:
+int b;
+  };
+  static_assert(A().cmp(), ""); // both-error {{constant expression}} \
+// both-note {{in call

[clang] [clang][CompundLiteralExpr] Don't defer evaluation for CLEs (PR #137163)

2025-04-24 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

Followup for https://github.com/llvm/llvm-project/pull/118480

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


[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 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 cl,c,cpp -- 
clang/test/Sema/warn-default-const-init.c clang/lib/Parse/ParseStmt.cpp 
clang/lib/Sema/Sema.cpp clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaInit.cpp 
clang/test/C/C23/n2607.c clang/test/C/drs/dr1xx.c clang/test/Parser/typeof.c 
clang/test/Sema/assign.c clang/test/Sema/atomic-ops.c 
clang/test/Sema/block-return.c clang/test/Sema/builtins-bpf.c 
clang/test/Sema/builtins-elementwise-math.c clang/test/Sema/builtins-overflow.c 
clang/test/Sema/enable_if.c clang/test/Sema/implicit-decl.c 
clang/test/Sema/overloadable.c clang/test/Sema/sizeless-1.c 
clang/test/Sema/typedef-retain.c clang/test/Sema/varargs-x86-64.c 
clang/test/Sema/warn-unused-function.c 
clang/test/SemaOpenCL/cl20-device-side-enqueue.cl 
clang/test/SemaOpenCL/invalid-block.cl 
clang/test/SemaOpenMP/atomic-capture-const-no-crash.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 87670fe19..4edcd3f94 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1460,7 +1460,6 @@ void Sema::ActOnEndOfTranslationUnit() {
   Diag(VD->getLocation(), DiagID) << Type << /*not a field*/ 0;
 }
 
-
 // Notify the consumer that we've completed a tentative definition.
 if (!VD->isInvalidDecl())
   Consumer.CompleteTentativeDefinition(VD);

``




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


[clang] [clang-repl] : Fix clang-repl crash with --cuda flag (PR #136404)

2025-04-24 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/136404

>From 1f7205615f8d11c1b58e2a2760f85663f97767c5 Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Fri, 18 Apr 2025 18:45:00 +0530
Subject: [PATCH 1/2] Fix cuda flag with clang-repl

---
 clang/include/clang/Interpreter/Interpreter.h | 13 ++-
 clang/lib/Interpreter/DeviceOffload.cpp   | 43 +
 clang/lib/Interpreter/DeviceOffload.h |  4 +-
 clang/lib/Interpreter/Interpreter.cpp | 89 ---
 4 files changed, 88 insertions(+), 61 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b1b63aedf86ab..1b228e0917d02 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -95,6 +95,9 @@ class Interpreter {
   // An optional parser for CUDA offloading
   std::unique_ptr DeviceParser;
 
+  // An optional action for CUDA offloading
+  std::unique_ptr DeviceAct;
+
   /// List containing information about each incrementally parsed piece of 
code.
   std::list PTUs;
 
@@ -129,7 +132,8 @@ class Interpreter {
 public:
   virtual ~Interpreter();
   static llvm::Expected>
-  create(std::unique_ptr CI);
+  create(std::unique_ptr CI,
+ std::unique_ptr DeviceCI = nullptr);
   static llvm::Expected>
   createWithCUDA(std::unique_ptr CI,
  std::unique_ptr DCI);
@@ -175,10 +179,11 @@ class Interpreter {
   llvm::Expected ExtractValueFromExpr(Expr *E);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
-  CodeGenerator *getCodeGen() const;
-  std::unique_ptr GenModule();
+  CodeGenerator *getCodeGen(IncrementalAction *Action = nullptr) const;
+  std::unique_ptr GenModule(IncrementalAction *Action = nullptr);
   PartialTranslationUnit &RegisterPTU(TranslationUnitDecl *TU,
-  std::unique_ptr M = {});
+  std::unique_ptr M = {},
+  IncrementalAction *Action = nullptr);
 
   // A cache for the compiled destructors used to for de-allocation of managed
   // clang::Values.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp 
b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..6977d7fa674ab 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -28,20 +28,21 @@ IncrementalCUDADeviceParser::IncrementalCUDADeviceParser(
 std::unique_ptr DeviceInstance,
 CompilerInstance &HostInstance,
 llvm::IntrusiveRefCntPtr FS,
-llvm::Error &Err, const std::list &PTUs)
+llvm::Error &Err, std::list &PTUs)
 : IncrementalParser(*DeviceInstance, Err), PTUs(PTUs), VFS(FS),
   CodeGenOpts(HostInstance.getCodeGenOpts()),
-  TargetOpts(HostInstance.getTargetOpts()) {
+  TargetOpts(DeviceInstance->getTargetOpts()) {
   if (Err)
 return;
-  DeviceCI = std::move(DeviceInstance);
   StringRef Arch = TargetOpts.CPU;
   if (!Arch.starts_with("sm_") || Arch.substr(3).getAsInteger(10, SMVersion)) {
+DeviceInstance.release();
 Err = llvm::joinErrors(std::move(Err), llvm::make_error(
"Invalid CUDA architecture",

llvm::inconvertibleErrorCode()));
 return;
   }
+  DeviceCI = std::move(DeviceInstance);
 }
 
 llvm::Expected
@@ -50,25 +51,6 @@ IncrementalCUDADeviceParser::Parse(llvm::StringRef Input) {
   if (!PTU)
 return PTU.takeError();
 
-  auto PTX = GeneratePTX();
-  if (!PTX)
-return PTX.takeError();
-
-  auto Err = GenerateFatbinary();
-  if (Err)
-return std::move(Err);
-
-  std::string FatbinFileName =
-  "/incr_module_" + std::to_string(PTUs.size()) + ".fatbin";
-  VFS->addFile(FatbinFileName, 0,
-   llvm::MemoryBuffer::getMemBuffer(
-   llvm::StringRef(FatbinContent.data(), FatbinContent.size()),
-   "", false));
-
-  CodeGenOpts.CudaGpuBinaryFileName = FatbinFileName;
-
-  FatbinContent.clear();
-
   return PTU;
 }
 
@@ -78,9 +60,11 @@ llvm::Expected 
IncrementalCUDADeviceParser::GeneratePTX() {
 
   const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
   PTU.TheModule->getTargetTriple(), Error);
-  if (!Target)
+  if (!Target) {
 return llvm::make_error(std::move(Error),
std::error_code());
+  }
+
   llvm::TargetOptions TO = llvm::TargetOptions();
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), TargetOpts.CPU, "", TO,
@@ -172,6 +156,19 @@ llvm::Error 
IncrementalCUDADeviceParser::GenerateFatbinary() {
 
   FatbinContent.append(PTXCode.begin(), PTXCode.end());
 
+  auto &PTU = PTUs.back();
+
+  std::string FatbinFileName = "/" + PTU.TheModule->getName().str() + 
".fatbin";
+
+  VFS->addFile(FatbinFileName, 0,
+   llvm::MemoryBuffer::getMemBuffer(
+   llvm

[clang] [clang][bytecode] Diagnose comparing pointers to fields... (PR #137159)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

... with different access specifiers.

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


4 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.h (+13) 
- (modified) clang/lib/AST/ByteCode/Pointer.cpp (+42) 
- (modified) clang/lib/AST/ByteCode/Pointer.h (+8-1) 
- (modified) clang/test/AST/ByteCode/records.cpp (+23) 


``diff
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 99b032bee9e3d..0a52a64240c04 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1007,6 +1007,19 @@ inline bool CmpHelper(InterpState &S, CodePtr 
OpPC, CompareFn Fn) {
 return false;
   }
 
+  // Diagnose comparisons between fields with different access specifiers.
+  if (std::optional> Split =
+  Pointer::computeSplitPoint(LHS, RHS)) {
+const FieldDecl *LF = Split->first.getField();
+const FieldDecl *RF = Split->second.getField();
+if (LF && RF && !LF->getParent()->isUnion() &&
+LF->getAccess() != RF->getAccess()) {
+  S.CCEDiag(S.Current->getSource(OpPC),
+diag::note_constexpr_pointer_comparison_differing_access)
+  << LF << LF->getAccess() << RF << RF->getAccess() << LF->getParent();
+}
+  }
+
   unsigned VL = LHS.getByteOffset();
   unsigned VR = RHS.getByteOffset();
   S.Stk.push(BoolT::from(Fn(Compare(VL, VR;
diff --git a/clang/lib/AST/ByteCode/Pointer.cpp 
b/clang/lib/AST/ByteCode/Pointer.cpp
index 059503cae3561..8adfd7a1f98d8 100644
--- a/clang/lib/AST/ByteCode/Pointer.cpp
+++ b/clang/lib/AST/ByteCode/Pointer.cpp
@@ -571,6 +571,48 @@ bool Pointer::pointsToLiteral() const {
   return E && !isa(E);
 }
 
+std::optional>
+Pointer::computeSplitPoint(const Pointer &A, const Pointer &B) {
+  if (!A.isBlockPointer() || !B.isBlockPointer())
+return std::nullopt;
+
+  if (A.asBlockPointer().Pointee != B.asBlockPointer().Pointee)
+return std::nullopt;
+  if (A.isRoot() && B.isRoot())
+return std::nullopt;
+
+  if (A == B)
+return std::make_pair(A, B);
+
+  auto getBase = [](const Pointer &P) -> Pointer {
+if (P.isArrayElement())
+  return P.getArray();
+return P.getBase();
+  };
+
+  Pointer IterA = A;
+  Pointer IterB = B;
+  Pointer CurA = IterA;
+  Pointer CurB = IterB;
+  for (;;) {
+if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
+  CurA = IterA;
+  IterA = getBase(IterA);
+} else {
+  CurB = IterB;
+  IterB = getBase(IterB);
+}
+
+if (IterA == IterB)
+  return std::make_pair(CurA, CurB);
+
+if (IterA.isRoot() && IterB.isRoot())
+  return std::nullopt;
+  }
+
+  llvm_unreachable("The loop above should've returned.");
+}
+
 std::optional Pointer::toRValue(const Context &Ctx,
  QualType ResultType) const {
   const ASTContext &ASTCtx = Ctx.getASTContext();
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index 8ede706f2736f..e168154a55f58 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -492,7 +492,11 @@ class Pointer {
 return ElemDesc ? ElemDesc->ElemRecord : nullptr;
   }
   /// Returns the field information.
-  const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
+  const FieldDecl *getField() const {
+if (const Descriptor *FD = getFieldDesc())
+  return FD->asFieldDecl();
+return nullptr;
+  }
 
   /// Checks if the storage is extern.
   bool isExtern() const {
@@ -724,6 +728,9 @@ class Pointer {
   /// Checks if both given pointers point to the same block.
   static bool pointToSameBlock(const Pointer &A, const Pointer &B);
 
+  static std::optional>
+  computeSplitPoint(const Pointer &A, const Pointer &B);
+
   /// Whether this points to a block that's been created for a "literal 
lvalue",
   /// i.e. a non-MaterializeTemporaryExpr Expr.
   bool pointsToLiteral() const;
diff --git a/clang/test/AST/ByteCode/records.cpp 
b/clang/test/AST/ByteCode/records.cpp
index da851785323a5..b4059f009b887 100644
--- a/clang/test/AST/ByteCode/records.cpp
+++ b/clang/test/AST/ByteCode/records.cpp
@@ -1787,3 +1787,26 @@ namespace IntegralBaseCast {
 
   static_assert(f() == 0, "");
 }
+
+namespace AccessMismatch {
+  struct A {
+  public:
+constexpr A() : a(0), b(0) {}
+int a;
+constexpr bool cmp() const { return &a < &b; } // both-note {{comparison 
of address of fields 'a' and 'b' of 'A' with differing access specifiers 
(public vs private) has unspecified value}}
+  private:
+int b;
+  };
+  static_assert(A().cmp(), ""); // both-error {{constant expression}} \
+// both-note {{in call}}
+
+  class B {
+  public:
+A a;
+constexpr bool cmp() const { return &a.a < &b.a; } // both-note 
{{comparison of address of fields 'a' and 'b' of 'B' with differing access 
specifiers (public vs protected) has un

[clang] [clang][analyzer][NFC] Add a helper for conjuring symbols at call events (PR #137182)

2025-04-24 Thread Fangyi Zhou via cfe-commits

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


[clang] [llvm] [clang][OpenMP][SPIR-V] Fix AS of globals and set the default AS to 4 (PR #135251)

2025-04-24 Thread Nick Sarnie via cfe-commits

sarnex wrote:

Thanks for the feedback, I'll work to address it.

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


[clang] 52a9649 - [clang][SPIR-V] Addrspace of opencl_global should always be 1 (#136753)

2025-04-24 Thread via cfe-commits

Author: Nick Sarnie
Date: 2025-04-24T14:20:13Z
New Revision: 52a96491e1e4e0d033e39fad87f49ccd871df41d

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

LOG: [clang][SPIR-V] Addrspace of opencl_global should always be 1 (#136753)

This fixes a CUDA SPIR-V regression introduced in
https://github.com/llvm/llvm-project/pull/134399.

-

Signed-off-by: Sarnie, Nick 

Added: 
clang/test/CodeGenCUDASPIRV/printf.cu

Modified: 
clang/lib/Basic/Targets/SPIR.h

Removed: 




diff  --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 4509748589b76..310ef9f2df2c6 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -58,8 +58,9 @@ static const unsigned SPIRDefIsPrivMap[] = {
 // Used by both the SPIR and SPIR-V targets.
 static const unsigned SPIRDefIsGenMap[] = {
 4, // Default
-// OpenCL address space values for this map are dummy and they can't be 
used
-0, // opencl_global
+// Some OpenCL address space values for this map are dummy and they can't 
be
+// used
+1, // opencl_global
 0, // opencl_local
 0, // opencl_constant
 0, // opencl_private

diff  --git a/clang/test/CodeGenCUDASPIRV/printf.cu 
b/clang/test/CodeGenCUDASPIRV/printf.cu
new file mode 100644
index 0..936e920f4a755
--- /dev/null
+++ b/clang/test/CodeGenCUDASPIRV/printf.cu
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fcuda-is-device -triple spirv32 -o - -emit-llvm -x cuda %s 
 | FileCheck --check-prefix=CHECK-SPIRV32 %s
+// RUN: %clang_cc1 -fcuda-is-device -triple spirv64 -o - -emit-llvm -x cuda %s 
 | FileCheck --check-prefix=CHECK-SPIRV64 %s
+
+// CHECK-SPIRV32: @.str = private unnamed_addr addrspace(4) constant [13 x i8] 
c"Hello World\0A\00", align 1
+// CHECK-SPIRV64: @.str = private unnamed_addr addrspace(1) constant [13 x i8] 
c"Hello World\0A\00", align 1
+
+extern "C" __attribute__((device)) int printf(const char* format, ...);
+
+__attribute__((global)) void printf_kernel() {
+  printf("Hello World\n");
+}



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


[clang] [llvm] [clang][OpenMP][SPIR-V] Fix AS of globals and set the default AS to 4 (PR #135251)

2025-04-24 Thread Nick Sarnie via cfe-commits

sarnex wrote:

@alexfh The regression is fixed in 
https://github.com/llvm/llvm-project/commit/52a96491e1e4e0d033e39fad87f49ccd871df41d

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


[clang] [clang][SPIR-V] Addrspace of opencl_global should always be 1 (PR #136753)

2025-04-24 Thread Nick Sarnie via cfe-commits

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


[clang] [clang][SPIR-V] Addrspace of opencl_global should always be 1 (PR #136753)

2025-04-24 Thread Nick Sarnie via cfe-commits

sarnex wrote:

Thanks for the review, and will do @AlexVlx!

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


[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Aaron Ballman via cfe-commits


@@ -8197,6 +8197,16 @@ def err_address_space_qualified_new : Error<
 def err_address_space_qualified_delete : Error<
   "'delete' cannot delete objects of type %0 in address space '%1'">;
 
+def note_default_init_const_member : Note<
+  "member %0 declared 'const' here">;
+def warn_default_init_const : Warning<
+  "default initialization of an object of type %0%select{| with const member}1 
"
+  "is incompatible with C++">,
+  InGroup, DefaultIgnore;
+def warn_default_init_const_unsafe : Warning<

AaronBallman wrote:

No, one is `DefaultIgnore` and the other is not, and they're in different 
diagnostic groups.

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


[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Erich Keane via cfe-commits


@@ -6496,6 +6496,17 @@ static bool canPerformArrayCopy(const InitializedEntity 
&Entity) {
   return false;
 }
 
+static const FieldDecl *GetConstField(const RecordDecl *RD) {

erichkeane wrote:

Ah, I see!  Would love an assert to that effect.

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


[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Erich Keane via cfe-commits

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

1 spelling nit, 1 request for an assert, else LGTM.

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


[clang] [clang][analyzer][NFC] Add a helper for conjuring symbols at call events (PR #137182)

2025-04-24 Thread Fangyi Zhou via cfe-commits

https://github.com/fangyi-zhou created 
https://github.com/llvm/llvm-project/pull/137182

Per suggestion in
https://github.com/llvm/llvm-project/pull/128251#discussion_r2055916229, adding 
a new helper function in `SValBuilder` to conjure a symbol when given a 
`CallEvent`.

Tested manually (with assertions) that the `LocationContext *` obtained from 
the `CallEvent` are identical to those passed in the original argument.

>From 79e5875e75d46edcf15c5df536ac8f1d93e13a16 Mon Sep 17 00:00:00 2001
From: Fangyi Zhou 
Date: Thu, 24 Apr 2025 15:12:12 +0100
Subject: [PATCH] [clang][analyzer][NFC] Add a helper for conjuring symbols at
 call events

Per suggestion in
https://github.com/llvm/llvm-project/pull/128251#discussion_r2055916229,
adding a new helper function in `SValBuilder` to conjure a symbol when
given a `CallEvent`.

Tested manually (with assertions) that the `LocationContext *` obtained
from the `CallEvent` are identical to those passed in the original
argument.
---
 .../Core/PathSensitive/SValBuilder.h  |  8 -
 .../Checkers/CStringChecker.cpp   | 32 +++
 .../Checkers/ErrnoTesterChecker.cpp   |  3 +-
 .../RetainCountChecker/RetainCountChecker.cpp |  3 +-
 .../Checkers/SmartPtrModeling.cpp |  2 +-
 .../Checkers/StdLibraryFunctionsChecker.cpp   | 10 +++---
 .../Checkers/cert/InvalidPtrChecker.cpp   |  4 +--
 clang/lib/StaticAnalyzer/Core/SValBuilder.cpp | 25 +--
 8 files changed, 42 insertions(+), 45 deletions(-)

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index 54430d426a82a..3f3e6bdb9ff3d 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -46,10 +46,10 @@ class Stmt;
 
 namespace ento {
 
+class CallEvent;
 class ConditionTruthVal;
 class ProgramStateManager;
 class StoreRef;
-
 class SValBuilder {
   virtual void anchor();
 
@@ -209,6 +209,12 @@ class SValBuilder {
 const LocationContext *LCtx,
 QualType type,
 unsigned visitCount);
+  DefinedOrUnknownSVal conjureSymbolVal(const CallEvent &call, QualType type,
+unsigned visitCount,
+const void *symbolTag = nullptr);
+  DefinedOrUnknownSVal conjureSymbolVal(const CallEvent &call,
+unsigned visitCount,
+const void *symbolTag = nullptr);
 
   /// Conjure a symbol representing heap allocated memory region.
   ///
diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 39dcaf02dbe25..9d3eda8f7f982 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -1514,8 +1514,7 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, 
const CallEvent &Call,
   // If we don't know how much we copied, we can at least
   // conjure a return value for later.
   if (lastElement.isUnknown())
-lastElement = C.getSValBuilder().conjureSymbolVal(
-nullptr, Call.getOriginExpr(), LCtx, C.blockCount());
+lastElement = C.getSValBuilder().conjureSymbolVal(Call, 
C.blockCount());
 
   // The byte after the last byte copied is the return value.
   state = state->BindExpr(Call.getOriginExpr(), LCtx, lastElement);
@@ -1665,8 +1664,7 @@ void CStringChecker::evalMemcmp(CheckerContext &C, const 
CallEvent &Call,
 State = CheckBufferAccess(C, State, Left, Size, AccessKind::read, CK);
 if (State) {
   // The return value is the comparison result, which we don't know.
-  SVal CmpV = Builder.conjureSymbolVal(nullptr, Call.getOriginExpr(), LCtx,
-   C.blockCount());
+  SVal CmpV = Builder.conjureSymbolVal(Call, C.blockCount());
   State = State->BindExpr(Call.getOriginExpr(), LCtx, CmpV);
   C.addTransition(State);
 }
@@ -1769,8 +1767,7 @@ void CStringChecker::evalstrLengthCommon(CheckerContext 
&C,
   // no guarantee the full string length will actually be returned.
   // All we know is the return value is the min of the string length
   // and the limit. This is better than nothing.
-  result = C.getSValBuilder().conjureSymbolVal(
-  nullptr, Call.getOriginExpr(), LCtx, C.blockCount());
+  result = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
   NonLoc resultNL = result.castAs();
 
   if (strLengthNL) {
@@ -1793,8 +1790,7 @@ void CStringChecker::evalstrLengthCommon(CheckerContext 
&C,
 // If we don't know the length of the string, conjure a return
 // value, so it can be used in constraints, at least.
 if (

[clang] [clang][analyzer][NFC] Add a helper for conjuring symbols at call events (PR #137182)

2025-04-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Fangyi Zhou (fangyi-zhou)


Changes

Per suggestion in
https://github.com/llvm/llvm-project/pull/128251#discussion_r2055916229, adding 
a new helper function in `SValBuilder` to conjure a symbol when given a 
`CallEvent`.

Tested manually (with assertions) that the `LocationContext *` obtained from 
the `CallEvent` are identical to those passed in the original argument.

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


8 Files Affected:

- (modified) 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h (+7-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (+11-21) 
- (modified) clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp (+1-2) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(+1-2) 
- (modified) clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
(+4-6) 
- (modified) clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp 
(+2-2) 
- (modified) clang/lib/StaticAnalyzer/Core/SValBuilder.cpp (+15-10) 


``diff
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index 54430d426a82a..3f3e6bdb9ff3d 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -46,10 +46,10 @@ class Stmt;
 
 namespace ento {
 
+class CallEvent;
 class ConditionTruthVal;
 class ProgramStateManager;
 class StoreRef;
-
 class SValBuilder {
   virtual void anchor();
 
@@ -209,6 +209,12 @@ class SValBuilder {
 const LocationContext *LCtx,
 QualType type,
 unsigned visitCount);
+  DefinedOrUnknownSVal conjureSymbolVal(const CallEvent &call, QualType type,
+unsigned visitCount,
+const void *symbolTag = nullptr);
+  DefinedOrUnknownSVal conjureSymbolVal(const CallEvent &call,
+unsigned visitCount,
+const void *symbolTag = nullptr);
 
   /// Conjure a symbol representing heap allocated memory region.
   ///
diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 39dcaf02dbe25..9d3eda8f7f982 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -1514,8 +1514,7 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, 
const CallEvent &Call,
   // If we don't know how much we copied, we can at least
   // conjure a return value for later.
   if (lastElement.isUnknown())
-lastElement = C.getSValBuilder().conjureSymbolVal(
-nullptr, Call.getOriginExpr(), LCtx, C.blockCount());
+lastElement = C.getSValBuilder().conjureSymbolVal(Call, 
C.blockCount());
 
   // The byte after the last byte copied is the return value.
   state = state->BindExpr(Call.getOriginExpr(), LCtx, lastElement);
@@ -1665,8 +1664,7 @@ void CStringChecker::evalMemcmp(CheckerContext &C, const 
CallEvent &Call,
 State = CheckBufferAccess(C, State, Left, Size, AccessKind::read, CK);
 if (State) {
   // The return value is the comparison result, which we don't know.
-  SVal CmpV = Builder.conjureSymbolVal(nullptr, Call.getOriginExpr(), LCtx,
-   C.blockCount());
+  SVal CmpV = Builder.conjureSymbolVal(Call, C.blockCount());
   State = State->BindExpr(Call.getOriginExpr(), LCtx, CmpV);
   C.addTransition(State);
 }
@@ -1769,8 +1767,7 @@ void CStringChecker::evalstrLengthCommon(CheckerContext 
&C,
   // no guarantee the full string length will actually be returned.
   // All we know is the return value is the min of the string length
   // and the limit. This is better than nothing.
-  result = C.getSValBuilder().conjureSymbolVal(
-  nullptr, Call.getOriginExpr(), LCtx, C.blockCount());
+  result = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
   NonLoc resultNL = result.castAs();
 
   if (strLengthNL) {
@@ -1793,8 +1790,7 @@ void CStringChecker::evalstrLengthCommon(CheckerContext 
&C,
 // If we don't know the length of the string, conjure a return
 // value, so it can be used in constraints, at least.
 if (result.isUnknown()) {
-  result = C.getSValBuilder().conjureSymbolVal(
-  nullptr, Call.getOriginExpr(), LCtx, C.blockCount());
+  result = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
 }
   }
 
@@ -2261,8 +2257,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext 

[clang] [C] Warn on uninitialized const objects (PR #137166)

2025-04-24 Thread Erich Keane via cfe-commits


@@ -8197,6 +8197,16 @@ def err_address_space_qualified_new : Error<
 def err_address_space_qualified_delete : Error<
   "'delete' cannot delete objects of type %0 in address space '%1'">;
 
+def note_default_init_const_member : Note<
+  "member %0 declared 'const' here">;
+def warn_default_init_const : Warning<
+  "default initialization of an object of type %0%select{| with const member}1 
"
+  "is incompatible with C++">,
+  InGroup, DefaultIgnore;
+def warn_default_init_const_unsafe : Warning<

erichkeane wrote:

Ah, missed that, thanks!

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


[clang] Thread Safety Analysis: Support reentrant capabilities (PR #137133)

2025-04-24 Thread Aaron Ballman via cfe-commits


@@ -139,22 +141,41 @@ class FactEntry : public CapabilityExpr {
   bool declared() const { return Source == Declared; }
   bool managed() const { return Source == Managed; }
 
-  virtual void
-  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
-SourceLocation JoinLoc, LockErrorKind LEK,
-ThreadSafetyHandler &Handler) const = 0;
+  virtual void handleRemovalFromIntersection(FactSet &FSet,
+ FactManager &FactMan,
+ SourceLocation JoinLoc,
+ LockErrorKind LEK,
+ ThreadSafetyHandler &Handler) = 0;
   virtual void handleLock(FactSet &FSet, FactManager &FactMan,
   const FactEntry &entry,
-  ThreadSafetyHandler &Handler) const = 0;
+  ThreadSafetyHandler &Handler) = 0;
   virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
-bool FullyRemove,
-ThreadSafetyHandler &Handler) const = 0;
+bool FullyRemove, ThreadSafetyHandler &Handler) = 
0;
 
   // Return true if LKind >= LK, where exclusive > shared
   bool isAtLeast(LockKind LK) const {
 return  (LKind == LK_Exclusive) || (LK == LK_Shared);
   }
+
+  // Return true if we can acquire a capability reentrant.
+  [[nodiscard]] bool tryReenter(LockKind ReenterKind) {
+if (!reentrant())
+  return false;
+if (kind() != ReenterKind)
+  return false;
+if (++ReentrancyCount == 0)
+  llvm::report_fatal_error("Maximum reentrancy reached");

AaronBallman wrote:

This should use a real diagnostic rather than reporting a fatal error, though I 
expect no user will ever run into the diagnostic in practice.

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


[clang] [llvm] [clang][OpenMP][SPIR-V] Fix AS of globals and set the default AS to 4 (PR #135251)

2025-04-24 Thread Nick Sarnie via cfe-commits


@@ -1217,11 +1217,13 @@ void 
CGOpenMPRuntimeGPU::emitParallelCall(CodeGenFunction &CGF,
 CGBuilderTy &Bld = CGF.Builder;
 llvm::Value *NumThreadsVal = NumThreads;
 llvm::Function *WFn = WrapperFunctionsMap[OutlinedFn];
+llvm::FunctionCallee RuntimeFn = OMPBuilder.getOrCreateRuntimeFunction(
+CGM.getModule(), OMPRTL___kmpc_parallel_51);
 llvm::Value *ID = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
 if (WFn)
   ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
-llvm::Value *FnPtr = Bld.CreateBitOrPointerCast(OutlinedFn, CGM.Int8PtrTy);
-
+llvm::Value *FnPtr = Bld.CreateAddrSpaceCast(OutlinedFn, CGM.Int8PtrTy);
+FnPtr = Bld.CreateBitOrPointerCast(FnPtr, CGM.Int8PtrTy);

sarnex wrote:

Yeah this one is annoying, so we are trying to cast a fcn ptr to int8 ptr (both 
just opaque now as you said), but the int8 ptr type is addrspace 4, and the 
function is addrspace 0, so we can't cast the function to the ptr in a single 
cast because we need to deal with the addrspace

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


  1   2   3   4   5   6   >