[libclc] [libclc] Make library output directories explicit (PR #146833)

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


@@ -120,14 +120,15 @@ function(link_bc)
   endif()
 
   add_custom_command(
-OUTPUT ${ARG_TARGET}.bc
-COMMAND ${llvm-link_exe} ${link_flags} -o ${ARG_TARGET}.bc 
${LINK_INPUT_ARG}
+OUTPUT ${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc
+COMMAND ${llvm-link_exe} ${link_flags} -o 
${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc ${LINK_INPUT_ARG}
 DEPENDS ${llvm-link_target} ${ARG_DEPENDENCIES} ${ARG_INPUTS} ${RSP_FILE}
+WORKING_DIRECTORY ${LIBCLC_ARCH_OBJFILE_DIR}

frasercrmck wrote:

We probably don't need both - I believe I can remove `WORKING_DIRECTORY`.

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits


@@ -2223,16 +2223,81 @@ void CStringChecker::evalStrcpyCommon(CheckerContext 
&C, const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
+  SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
+
+  // Protect against misdeclared strncpy().
+  lenVal =
+  svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
+
+  std::optional lenValNL = lenVal.getAs();
+
+  auto CouldAccessOutOfBoundForSVal = [&](NonLoc Val) -> bool {
+return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
+  Dst.Expression->getType(), Val,
+  C.getASTContext().getSizeType());
+  };
+
+  if (strLengthNL) {
+CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*strLengthNL);
+  }
+
+  if (CouldAccessOutOfBound && lenValNL) {
+switch (appendK) {
+case ConcatFnKind::none:
+case ConcatFnKind::strcat: {
+  CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*lenValNL);
+  break;
+}
+case ConcatFnKind::strlcat: {

flovent wrote:

I think that make sense, now it use `size` for all `ConcatFnKind`'s check.

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


[clang] [analyzer] Add support for consteval in ConditionBRVisitor::VisitTerminator (PR #146859)

2025-07-03 Thread Imad Aldij via cfe-commits

https://github.com/imdj updated https://github.com/llvm/llvm-project/pull/146859

>From 1077e164158965e824097542dc4c3ecc8821d6dc Mon Sep 17 00:00:00 2001
From: Imad Aldij 
Date: Thu, 3 Jul 2025 13:50:55 +0300
Subject: [PATCH 1/3] Add support for consteval if in ConditionBRVisitor

---
 clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 3686bd4488877..d81a3f5a2858b 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2794,6 +2794,9 @@ PathDiagnosticPieceRef 
ConditionBRVisitor::VisitTerminator(
   default:
 return nullptr;
   case Stmt::IfStmtClass:
+// Handle if consteval which doesn't have a traditional condition
+if (cast(Term)->isConsteval())
+  return nullptr;
 Cond = cast(Term)->getCond();
 break;
   case Stmt::ConditionalOperatorClass:

>From 27b793fcf2347d631991f9f83df7ef5787df17d6 Mon Sep 17 00:00:00 2001
From: Imad Aldij 
Date: Thu, 3 Jul 2025 15:52:35 +0300
Subject: [PATCH 2/3] add test case for consteval and ConditionBRVisitor

---
 clang/test/Analysis/consteval-if.cpp | 8 
 1 file changed, 8 insertions(+)
 create mode 100644 clang/test/Analysis/consteval-if.cpp

diff --git a/clang/test/Analysis/consteval-if.cpp 
b/clang/test/Analysis/consteval-if.cpp
new file mode 100644
index 0..2ce9a69067951
--- /dev/null
+++ b/clang/test/Analysis/consteval-if.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_analyze_cc1 -std=c++23 -analyzer-checker=core -verify %s
+
+void test_consteval() {
+  if consteval {
+int *ptr = nullptr;
+*ptr = 42; // expected-warning{{Dereference of null pointer (loaded from 
variable 'ptr')}}
+  }
+}
\ No newline at end of file

>From 90a235dfff9c6eaaa47f62d542de03868154a806 Mon Sep 17 00:00:00 2001
From: Imad Aldij 
Date: Thu, 3 Jul 2025 16:30:32 +0300
Subject: [PATCH 3/3] Update test formatting

Co-authored-by: Balazs Benics 
---
 clang/test/Analysis/consteval-if.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Analysis/consteval-if.cpp 
b/clang/test/Analysis/consteval-if.cpp
index 2ce9a69067951..b7eae9db6a239 100644
--- a/clang/test/Analysis/consteval-if.cpp
+++ b/clang/test/Analysis/consteval-if.cpp
@@ -5,4 +5,4 @@ void test_consteval() {
 int *ptr = nullptr;
 *ptr = 42; // expected-warning{{Dereference of null pointer (loaded from 
variable 'ptr')}}
   }
-}
\ No newline at end of file
+}

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits

https://github.com/flovent updated 
https://github.com/llvm/llvm-project/pull/146212

>From 9da53c788fc01cd3fc2dd4c178b836035b5d380b Mon Sep 17 00:00:00 2001
From: flovent 
Date: Sat, 28 Jun 2025 20:58:43 +0800
Subject: [PATCH 1/6] [analyzer] Avoid unnecessary super region invalidation in
 `CStringChecker`

---
 .../Checkers/CStringChecker.cpp   |  77 -
 .../cstring-should-not-invalidate.cpp | 107 ++
 2 files changed, 178 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/Analysis/cstring-should-not-invalidate.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 4d12fdcec1f1a..433fd2ce5f292 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -272,7 +272,8 @@ class CStringChecker : public Checker< eval::Call,
   static ProgramStateRef
   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
 const Expr *BufE, ConstCFGElementRef Elem,
-SVal BufV, SVal SizeV, QualType SizeTy);
+SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound = true);
 
   /// Operation never overflows, do not invalidate the super region.
   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
@@ -1211,14 +1212,17 @@ bool CStringChecker::isFirstBufInBound(CheckerContext 
&C, ProgramStateRef State,
 
 ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
 CheckerContext &C, ProgramStateRef S, const Expr *BufE,
-ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) {
+ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound) {
   auto InvalidationTraitOperations =
-  [&C, S, BufTy = BufE->getType(), BufV, SizeV,
-   SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) 
{
+  [&C, S, BufTy = BufE->getType(), BufV, SizeV, SizeTy,
+   CouldAccessOutOfBound](RegionAndSymbolInvalidationTraits &ITraits,
+  const MemRegion *R) {
 // If destination buffer is a field region and access is in bound, do
 // not invalidate its super region.
 if (MemRegion::FieldRegionKind == R->getKind() &&
-isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
+(!CouldAccessOutOfBound ||
+ isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy))) {
   ITraits.setTrait(
   R,
   
RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
@@ -2223,6 +2227,67 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, 
const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
+  SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
+
+  // Protect against misdeclared strncpy().
+  lenVal =
+  svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
+
+  std::optional lenValNL = lenVal.getAs();
+
+  auto CouldAccessOutOfBoundForSVal = [&](NonLoc Val) -> bool {
+return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
+  Dst.Expression->getType(), Val,
+  C.getASTContext().getSizeType());
+  };
+
+  if (strLengthNL) {
+CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*strLengthNL);
+  }
+
+  if (CouldAccessOutOfBound && lenValNL) {
+switch (appendK) {
+case ConcatFnKind::none:
+case ConcatFnKind::strcat: {
+  CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*lenValNL);
+  break;
+}
+case ConcatFnKind::strlcat: {
+  if (!dstStrLengthNL)
+break;
+
+  SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
+   *dstStrLengthNL, sizeTy);
+  if (!isa(freeSpace))
+break;
+
+  freeSpace =
+  svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
+svalBuilder.makeIntVal(1, sizeTy), sizeTy);
+  std::optional fre

[clang] d805707 - [clang][test] Correct UNSUPPORTED syntax in print-ranges.cpp

2025-07-03 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2025-07-03T13:36:30Z
New Revision: d805707ee435fbe83440ceaf0eb515bf1d536f01

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

LOG: [clang][test] Correct UNSUPPORTED syntax in print-ranges.cpp

Without the ":" it doesn't work.

Added: 


Modified: 
clang/test/Analysis/print-ranges.cpp

Removed: 




diff  --git a/clang/test/Analysis/print-ranges.cpp 
b/clang/test/Analysis/print-ranges.cpp
index 89a4249ebfaa5..8964f68dbfee9 100644
--- a/clang/test/Analysis/print-ranges.cpp
+++ b/clang/test/Analysis/print-ranges.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-config eagerly-assume=false -verify %s
-// UNSUPPORTED z3
+// UNSUPPORTED: z3
 
 template 
 void clang_analyzer_value(T x);



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


[libclc] [libclc] Make library output directories explicit (PR #146833)

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

https://github.com/frasercrmck updated 
https://github.com/llvm/llvm-project/pull/146833

>From 27ede3bfae2776deef2dfce803a5f500bf0c7278 Mon Sep 17 00:00:00 2001
From: Fraser Cormack 
Date: Thu, 3 Jul 2025 09:24:59 +0100
Subject: [PATCH 1/2] [libclc] Make library output directories explicit

These changes were split off from #146503.

This commit makes the output directories of libclc artefacts explicit.
It creates a variable for the final output directory -
LIBCLC_OUTPUT_LIBRARY_DIR - which has not changed. This allows future
changes to alter the output directory more simply, such as by pointing
it to somewhere inside clang's resource directory.

This commit also changes the output directory of each target's
intermediate builtins.*.bc files. They are now placed into each
respective libclc target's object directory, rather than the top-level
libclc binary directory. This should help keep the binary directory a
bit tidier.
---
 libclc/CMakeLists.txt|  3 ++
 libclc/cmake/modules/AddLibclc.cmake | 59 +---
 2 files changed, 40 insertions(+), 22 deletions(-)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index c98e2043464d9..e2871d1b01a16 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -84,6 +84,9 @@ else()
   endif()
 endif()
 
+# Setup the paths where libclc runtimes should be stored.
+set( LIBCLC_OUTPUT_LIBRARY_DIR ${CMAKE_CURRENT_BINARY_DIR} )
+
 if( EXISTS ${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR} )
   message( WARNING "Using custom LLVM tools to build libclc: "
 "${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR}, "
diff --git a/libclc/cmake/modules/AddLibclc.cmake 
b/libclc/cmake/modules/AddLibclc.cmake
index c521ea1589484..c4434c34a7fd7 100644
--- a/libclc/cmake/modules/AddLibclc.cmake
+++ b/libclc/cmake/modules/AddLibclc.cmake
@@ -120,14 +120,15 @@ function(link_bc)
   endif()
 
   add_custom_command(
-OUTPUT ${ARG_TARGET}.bc
-COMMAND ${llvm-link_exe} ${link_flags} -o ${ARG_TARGET}.bc 
${LINK_INPUT_ARG}
+OUTPUT ${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc
+COMMAND ${llvm-link_exe} ${link_flags} -o 
${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc ${LINK_INPUT_ARG}
 DEPENDS ${llvm-link_target} ${ARG_DEPENDENCIES} ${ARG_INPUTS} ${RSP_FILE}
+WORKING_DIRECTORY ${LIBCLC_ARCH_OBJFILE_DIR}
   )
 
-  add_custom_target( ${ARG_TARGET} ALL DEPENDS ${ARG_TARGET}.bc )
+  add_custom_target( ${ARG_TARGET} ALL DEPENDS 
${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc )
   set_target_properties( ${ARG_TARGET} PROPERTIES
-TARGET_FILE ${CMAKE_CURRENT_BINARY_DIR}/${ARG_TARGET}.bc
+TARGET_FILE ${LIBCLC_ARCH_OBJFILE_DIR}/${ARG_TARGET}.bc
 FOLDER "libclc/Device IR/Linking"
   )
 endfunction()
@@ -360,33 +361,39 @@ function(add_libclc_builtin_set)
   # llvm-spirv tool.
   if( ARG_ARCH STREQUAL spirv OR ARG_ARCH STREQUAL spirv64 )
 set( obj_suffix ${ARG_ARCH_SUFFIX}.spv )
-add_custom_command( OUTPUT ${obj_suffix}
-  COMMAND ${llvm-spirv_exe} ${spvflags} -o ${obj_suffix} 
${builtins_link_lib}
+set( libclc_builtins_lib ${LIBCLC_OUTPUT_LIBRARY_DIR}/${obj_suffix} )
+add_custom_command( OUTPUT ${libclc_builtins_lib}
+  COMMAND ${llvm-spirv_exe} ${spvflags} -o ${libclc_builtins_lib} 
${builtins_link_lib}
   DEPENDS ${llvm-spirv_target} ${builtins_link_lib} 
${builtins_link_lib_tgt}
+  WORKING_DIRECTORY ${LIBCLC_OUTPUT_LIBRARY_DIR}
 )
   else()
 # Non-SPIR-V targets add an extra step to optimize the bytecode
 set( builtins_opt_lib_tgt builtins.opt.${ARG_ARCH_SUFFIX} )
 
-add_custom_command( OUTPUT ${builtins_opt_lib_tgt}.bc
-  COMMAND ${opt_exe} ${ARG_OPT_FLAGS} -o ${builtins_opt_lib_tgt}.bc
+add_custom_command( OUTPUT 
${LIBCLC_ARCH_OBJFILE_DIR}/${builtins_opt_lib_tgt}.bc
+  COMMAND ${opt_exe} ${ARG_OPT_FLAGS} -o 
${LIBCLC_ARCH_OBJFILE_DIR}/${builtins_opt_lib_tgt}.bc
 ${builtins_link_lib}
   DEPENDS ${opt_target} ${builtins_link_lib} ${builtins_link_lib_tgt}
+  WORKING_DIRECTORY ${LIBCLC_ARCH_OBJFILE_DIR}
 )
 add_custom_target( ${builtins_opt_lib_tgt}
-  ALL DEPENDS ${builtins_opt_lib_tgt}.bc
+  ALL DEPENDS ${LIBCLC_ARCH_OBJFILE_DIR}/${builtins_opt_lib_tgt}.bc
 )
 set_target_properties( ${builtins_opt_lib_tgt} PROPERTIES
-  TARGET_FILE ${CMAKE_CURRENT_BINARY_DIR}/${builtins_opt_lib_tgt}.bc
+  TARGET_FILE ${LIBCLC_ARCH_OBJFILE_DIR}/${builtins_opt_lib_tgt}.bc
   FOLDER "libclc/Device IR/Opt"
 )
 
 set( builtins_opt_lib 
$ )
 
 set( obj_suffix ${ARG_ARCH_SUFFIX}.bc )
-add_custom_command( OUTPUT ${obj_suffix}
-  COMMAND ${prepare_builtins_exe} -o ${obj_suffix} ${builtins_opt_lib}
-  DEPENDS ${builtins_opt_lib} ${builtins_opt_lib_tgt} 
${prepare_builtins_target} )
+set( libclc_builtins_lib ${LIBCLC_OUTPUT_LIBRARY_DIR}/${obj_suffix} )
+add_custom_command( OUTPUT ${libclc_builtins_lib}
+  COMMAND ${prepare_builtins_exe} -o ${libclc_builtins_lib} 
${builtins_opt_lib}
+  DEPENDS ${builtins_opt_lib} ${builtin

[clang] [llvm] [HIPSTDPAR] Add support for globals (PR #146813)

2025-07-03 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/146813

>From d98e3785a144ada9881cdbe24c86f273850eca20 Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Thu, 3 Jul 2025 02:02:04 +0100
Subject: [PATCH 1/4] Add support for true globals.

---
 llvm/lib/Transforms/HipStdPar/HipStdPar.cpp   | 220 +-
 ...al-var-indirection-wrong-table-member-0.ll |  15 ++
 ...al-var-indirection-wrong-table-member-1.ll |  15 ++
 ...al-var-indirection-wrong-table-member-2.ll |  15 ++
 ...ar-indirection-wrong-table-member-count.ll |  14 ++
 ...global-var-indirection-wrong-table-type.ll |  13 ++
 .../HipStdPar/global-var-indirection.ll   |  87 +++
 llvm/test/Transforms/HipStdPar/global-var.ll  |   4 +-
 8 files changed, 371 insertions(+), 12 deletions(-)
 create mode 100644 
llvm/test/Transforms/HipStdPar/global-var-indirection-wrong-table-member-0.ll
 create mode 100644 
llvm/test/Transforms/HipStdPar/global-var-indirection-wrong-table-member-1.ll
 create mode 100644 
llvm/test/Transforms/HipStdPar/global-var-indirection-wrong-table-member-2.ll
 create mode 100644 
llvm/test/Transforms/HipStdPar/global-var-indirection-wrong-table-member-count.ll
 create mode 100644 
llvm/test/Transforms/HipStdPar/global-var-indirection-wrong-table-type.ll
 create mode 100644 llvm/test/Transforms/HipStdPar/global-var-indirection.ll

diff --git a/llvm/lib/Transforms/HipStdPar/HipStdPar.cpp 
b/llvm/lib/Transforms/HipStdPar/HipStdPar.cpp
index 5a87cf8c83d79..87fbcd40be431 100644
--- a/llvm/lib/Transforms/HipStdPar/HipStdPar.cpp
+++ b/llvm/lib/Transforms/HipStdPar/HipStdPar.cpp
@@ -48,6 +48,7 @@
 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
 
@@ -114,24 +115,223 @@ static inline void clearModule(Module &M) { // TODO: 
simplify.
 eraseFromModule(*M.ifuncs().begin());
 }
 
+static inline SmallVector> collectIndirectableUses(
+  GlobalVariable *G) {
+  // We are interested only in use chains that end in an Instruction.
+  SmallVector> Uses;
+
+  SmallVector> Tmp(G->use_begin(), G->use_end());
+  while (!Tmp.empty()) {
+Use &U = Tmp.back();
+Tmp.pop_back();
+if (isa(U.getUser()))
+  Uses.emplace_back(U);
+else
+  transform(U.getUser()->uses(), std::back_inserter(Tmp), [](auto &&U) {
+return std::ref(U);
+  });
+  }
+
+  return Uses;
+}
+
+static inline GlobalVariable *getGlobalForName(GlobalVariable *G) {
+  // Create an anonymous global which stores the variable's name, which will be
+  // used by the HIPSTDPAR runtime to look up the program-wide symbol.
+  LLVMContext &Ctx = G->getContext();
+  auto *CDS = ConstantDataArray::getString(Ctx, G->getName());
+
+  GlobalVariable *N = G->getParent()->getOrInsertGlobal("", CDS->getType());
+  N->setInitializer(CDS);
+  N->setLinkage(GlobalValue::LinkageTypes::PrivateLinkage);
+  N->setConstant(true);
+
+  return N;
+}
+
+static inline GlobalVariable *getIndirectionGlobal(Module *M) {
+  // Create an anonymous global which stores a pointer to a pointer, which will
+  // be externally initialised by the HIPSTDPAR runtime with the address of the
+  // program-wide symbol.
+  Type *PtrTy =
+  PointerType::get(M->getContext(),
+   M->getDataLayout().getDefaultGlobalsAddressSpace());
+  GlobalVariable *NewG = M->getOrInsertGlobal("", PtrTy);
+
+  NewG->setInitializer(PoisonValue::get(NewG->getValueType()));
+  NewG->setLinkage(GlobalValue::LinkageTypes::PrivateLinkage);
+  NewG->setConstant(true);
+  NewG->setExternallyInitialized(true);
+
+  return NewG;
+}
+
+static inline Constant *appendIndirectedGlobal(
+const GlobalVariable *IndirectionTable,
+SmallVector &SymbolIndirections,
+GlobalVariable *ToIndirect) {
+  Module *M = ToIndirect->getParent();
+
+  auto *InitTy = cast(IndirectionTable->getValueType());
+  auto *SymbolListTy = cast(InitTy->getStructElementType(2));
+  Type *NameTy = SymbolListTy->getElementType(0);
+  Type *IndirectTy = SymbolListTy->getElementType(1);
+
+  Constant *NameG = getGlobalForName(ToIndirect);
+  Constant *IndirectG = getIndirectionGlobal(M);
+  Constant *Entry = ConstantStruct::get(
+  SymbolListTy, {ConstantExpr::getAddrSpaceCast(NameG, NameTy),
+ ConstantExpr::getAddrSpaceCast(IndirectG, IndirectTy)});
+  SymbolIndirections.push_back(Entry);
+
+  return IndirectG;
+}
+
+static void fillIndirectionTable(GlobalVariable *IndirectionTable,
+ SmallVector Indirections) {
+  Module *M = IndirectionTable->getParent();
+  size_t SymCnt = Indirections.size();
+
+  auto *InitTy = cast(IndirectionTable->getValueType());
+  Type *SymbolListTy = InitTy->getStructElementType(1);
+  auto *SymbolTy = cast(InitTy->getStructElementType(2));
+
+  Constant *Count = ConstantInt::get(InitTy->getStructElementType(0), SymCnt);
+  M->removeGlobalV

[clang] [clang] Refactor `CodeGenOptions` to specify AST effect as X macro arg (PR #146910)

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

https://github.com/jansvoboda11 updated 
https://github.com/llvm/llvm-project/pull/146910

>From 12825e992f8e7c8c9d50e7738e94f7d3770fd356 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Thu, 3 Jul 2025 07:31:00 -0700
Subject: [PATCH 1/2] [clang] Refactor `CodeGenOptions` to specify AST effect
 as X macro arg

---
 clang/include/clang/Basic/CodeGenOptions.def | 640 +--
 clang/include/clang/Basic/CodeGenOptions.h   |  27 +-
 clang/include/clang/Basic/DebugOptions.def   | 139 ++--
 clang/lib/Basic/CodeGenOptions.cpp   |  48 +-
 clang/lib/Frontend/CompilerInvocation.cpp|  18 +-
 5 files changed, 428 insertions(+), 444 deletions(-)

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index e5566a540dc65..0eba77398a22d 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -12,481 +12,473 @@
 // that have enumeration type and VALUE_CODEGENOPT is a code
 // generation option that describes a value rather than a flag.
 //
-// AFFECTING_VALUE_CODEGENOPT is used for code generation options that can
-// affect the AST.
-//
 
//===--===//
 #ifndef CODEGENOPT
-#  error Define the CODEGENOPT macro to handle language options
+#  error Define the CODEGENOPT macro to handle codegen options
 #endif
 
 #ifndef VALUE_CODEGENOPT
-#  define VALUE_CODEGENOPT(Name, Bits, Default) \
-CODEGENOPT(Name, Bits, Default)
+#  define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
+CODEGENOPT(Name, Bits, Default, Compatibility)
 #endif
 
 #ifndef ENUM_CODEGENOPT
-#  define ENUM_CODEGENOPT(Name, Type, Bits, Default) \
-CODEGENOPT(Name, Bits, Default)
-#endif
-
-#ifndef AFFECTING_VALUE_CODEGENOPT
-#  define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default) \
-VALUE_CODEGENOPT(Name, Bits, Default)
+#  define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
+CODEGENOPT(Name, Bits, Default, Compatibility)
 #endif
 
-CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
-CODEGENOPT(Crel, 1, 0) ///< -Wa,--crel
-CODEGENOPT(ImplicitMapSyms, 1, 0) ///< -Wa,-mmapsyms=implicit
-CODEGENOPT(AsmVerbose, 1, 0) ///< -dA, -fverbose-asm.
-CODEGENOPT(PreserveAsmComments, 1, 1) ///< -dA, -fno-preserve-as-comments.
-CODEGENOPT(AssumeSaneOperatorNew , 1, 1) ///< implicit __attribute__((malloc)) 
operator new
-CODEGENOPT(AssumeUniqueVTables , 1, 1) ///< Assume a class has only one vtable.
-CODEGENOPT(Autolink  , 1, 1) ///< -fno-autolink
-CODEGENOPT(AutoImport, 1, 1) ///< -fno-auto-import
-CODEGENOPT(ObjCAutoRefCountExceptions , 1, 0) ///< Whether ARC should be 
EH-safe.
-CODEGENOPT(Backchain , 1, 0) ///< -mbackchain
-CODEGENOPT(ControlFlowGuardNoChecks  , 1, 0) ///< -cfguard-no-checks
-CODEGENOPT(ControlFlowGuard  , 1, 0) ///< -cfguard
-CODEGENOPT(EHContGuard   , 1, 0) ///< -ehcontguard
-CODEGENOPT(CXAAtExit , 1, 1) ///< Use __cxa_atexit for calling 
destructors.
-CODEGENOPT(RegisterGlobalDtorsWithAtExit, 1, 1) ///< Use atexit or 
__cxa_atexit to register global destructors.
-CODEGENOPT(CXXCtorDtorAliases, 1, 0) ///< Emit complete ctors/dtors as linker
+CODEGENOPT(DisableIntegratedAS, 1, 0, Benign) ///< -no-integrated-as
+CODEGENOPT(Crel, 1, 0, Benign) ///< -Wa,--crel
+CODEGENOPT(ImplicitMapSyms, 1, 0, Benign) ///< -Wa,-mmapsyms=implicit
+CODEGENOPT(AsmVerbose, 1, 0, Benign) ///< -dA, -fverbose-asm.
+CODEGENOPT(PreserveAsmComments, 1, 1, Benign) ///< -dA, 
-fno-preserve-as-comments.
+CODEGENOPT(AssumeSaneOperatorNew , 1, 1, Benign) ///< implicit 
__attribute__((malloc)) operator new
+CODEGENOPT(AssumeUniqueVTables , 1, 1, Benign) ///< Assume a class has only 
one vtable.
+CODEGENOPT(Autolink  , 1, 1, Benign) ///< -fno-autolink
+CODEGENOPT(AutoImport, 1, 1, Benign) ///< -fno-auto-import
+CODEGENOPT(ObjCAutoRefCountExceptions , 1, 0, Benign) ///< Whether ARC should 
be EH-safe.
+CODEGENOPT(Backchain , 1, 0, Benign) ///< -mbackchain
+CODEGENOPT(ControlFlowGuardNoChecks  , 1, 0, Benign) ///< -cfguard-no-checks
+CODEGENOPT(ControlFlowGuard  , 1, 0, Benign) ///< -cfguard
+CODEGENOPT(EHContGuard   , 1, 0, Benign) ///< -ehcontguard
+CODEGENOPT(CXAAtExit , 1, 1, Benign) ///< Use __cxa_atexit for calling 
destructors.
+CODEGENOPT(RegisterGlobalDtorsWithAtExit, 1, 1, Benign) ///< Use atexit or 
__cxa_atexit to register global destructors.
+CODEGENOPT(CXXCtorDtorAliases, 1, 0, Benign) ///< Emit complete ctors/dtors as 
linker
  ///< aliases to base ctors when possible.
-CODEGENOPT(DataSections  , 1, 0) ///< Set when -fdata-sections is enabled.
-CODEGENOPT(UniqueSectionNames, 1, 1) ///< Set for -funique-section-names.
-CODEGENOPT(UniqueBasicBlockSectionNames, 1, 1) ///< Set for 
-funique-basic-block-section-names,
+CODEGENOPT(DataSections  , 1, 0, Benign) ///< Set when -fdata-sections is 
enabled.
+CODEGENOPT(UniqueS

[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

2025-07-03 Thread Sander de Smalen via cfe-commits

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


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


[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

2025-07-03 Thread Sander de Smalen via cfe-commits


@@ -2261,6 +2261,23 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
 }
   }
 }
+
+if (auto *VT = Ty->getAs();
+VT && FD &&
+(VT->getVectorKind() == VectorKind::SveFixedLengthData ||
+ VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
+(LangOpts.VScaleMin != LangOpts.VScaleStreamingMin ||
+ LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) {
+  if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
+Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function) << Ty << 0;
+  } else if (const auto *FTy = FD->getType()->getAs()) {
+if (FTy->getAArch64SMEAttributes() &
+FunctionType::SME_PStateSMCompatibleMask) {
+  Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
+  << Ty << 1;

sdesmalen-arm wrote:

nit: 
```suggestion
  << Ty << /*StreamingCompatible*/ 1;
```

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


[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

2025-07-03 Thread Sander de Smalen via cfe-commits


@@ -2261,6 +2261,21 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
 }
   }
 }
+
+if (auto *VT = Ty->getAs();
+VT && FD &&
+(VT->getVectorKind() == VectorKind::SveFixedLengthData ||
+ VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)) {
+  if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
+Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function) << Ty << 0;
+  } else if (const auto *FTy = FD->getType()->getAs()) {
+if (FTy->getAArch64SMEAttributes() &
+FunctionType::SME_PStateSMCompatibleMask) {
+  Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)

sdesmalen-arm wrote:

> Your last two testcases are the same: the conversion happens in the caller, 
> so the first case reduces to the second.

Yes, I agree. I just wasn't sure if it would somehow take a slightly different 
path in clang somehow.

> Which is an issue, I guess, but not directly related to this patch

This patch adds extra information that proves this conversion is not valid, 
whereas before the compiler could not prove it and assumed the user knew what 
they were doing. I'm happy for it to be done as a follow-up though.

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


[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

2025-07-03 Thread Sander de Smalen via cfe-commits


@@ -2261,6 +2261,23 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
 }
   }
 }
+
+if (auto *VT = Ty->getAs();
+VT && FD &&
+(VT->getVectorKind() == VectorKind::SveFixedLengthData ||
+ VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
+(LangOpts.VScaleMin != LangOpts.VScaleStreamingMin ||
+ LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) {
+  if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
+Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function) << Ty << 0;

sdesmalen-arm wrote:

nit:
```suggestion
Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function) << Ty << 
/*Streaming*/ 0;
```

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


[clang] [clang-tools-extra] [clang-tidy] EndSourceFile() for preprocessor before diagnostic client (PR #145784)

2025-07-03 Thread Dave Bartolomeo via cfe-commits

https://github.com/dbartol updated 
https://github.com/llvm/llvm-project/pull/145784

>From 0be65986e1e2adf973a032936afa9cf48841055b Mon Sep 17 00:00:00 2001
From: Dave Bartolomeo 
Date: Wed, 25 Jun 2025 17:45:50 -0400
Subject: [PATCH 1/4] EndSourceFile() for preprocessor before diagnostic client

The comment for `DiagnosticConsumer::BeginSourceFile()` states that 
"diagnostics with source range information are required to only be emitted in 
between BeginSourceFile() and EndSourceFile().". While working on some upcoming 
changes to the static analyzer, we hit some crashes when diagnostics were 
reported from the `EndOfMainFile` callback in the preprocessor. This turned out 
to be because `FrontEndAction::EndSourceFile()` notifies the diagnostic clients 
of the end of the source file before it notifies the preprocessor. Thus, the 
diagnostics from the preprocessor callback are reported when the diagnostic 
client is no longer expecting any diagnostics.

The fix is to swap the order of the `EndSourceFile()` calls so that the 
preprocessor is notified first.

I've added asserts to the `ClangTidyDiagnosticConsumer` to catch unexpected 
diagnostics outside of a source file. Before swapping the order of the calls as 
described above, this causes several failures in the clang-tidy regression 
tests. With the swap, there are no failures in `check-all`.
---
 .../clang-tidy/ClangTidyDiagnosticConsumer.cpp   |  6 ++
 .../clang-tidy/ClangTidyDiagnosticConsumer.h | 16 
 clang/lib/Frontend/FrontendAction.cpp|  8 +---
 3 files changed, 27 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index a71813a103df3..fbb93ff67ac83 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -360,6 +360,12 @@ getFixIt(const tooling::Diagnostic &Diagnostic, bool 
AnyFix) {
 
 void ClangTidyDiagnosticConsumer::HandleDiagnostic(
 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
+  assert(InSourceFile ||
+ Info.getLocation()
+ .isInvalid()); // A diagnostic should not be reported outside of a
+// BeginSourceFile()/EndSourceFile() pair if it has
+// a source location.
+
   if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note)
 return;
 
diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
index a8851e794f24b..2832711ab2441 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
@@ -292,6 +292,21 @@ class ClangTidyDiagnosticConsumer : public 
DiagnosticConsumer {
   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
 const Diagnostic &Info) override;
 
+  void BeginSourceFile(const LangOptions &LangOpts,
+   const Preprocessor *PP = nullptr) override {
+DiagnosticConsumer::BeginSourceFile(LangOpts, PP);
+
+assert(!InSourceFile);
+InSourceFile = true;
+  }
+
+  void EndSourceFile() override {
+assert(InSourceFile);
+InSourceFile = false;
+
+DiagnosticConsumer::EndSourceFile();
+  }
+
   // Retrieve the diagnostics that were captured.
   std::vector take();
 
@@ -326,6 +341,7 @@ class ClangTidyDiagnosticConsumer : public 
DiagnosticConsumer {
   bool LastErrorRelatesToUserCode = false;
   bool LastErrorPassesLineFilter = false;
   bool LastErrorWasIgnored = false;
+  bool InSourceFile = false;
 };
 
 } // end namespace tidy
diff --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index ef7ae27a2694a..f5996a8e1e88b 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -1243,13 +1243,15 @@ llvm::Error FrontendAction::Execute() {
 void FrontendAction::EndSourceFile() {
   CompilerInstance &CI = getCompilerInstance();
 
-  // Inform the diagnostic client we are done with this source file.
-  CI.getDiagnosticClient().EndSourceFile();
-
   // Inform the preprocessor we are done.
   if (CI.hasPreprocessor())
 CI.getPreprocessor().EndSourceFile();
 
+  // Inform the diagnostic client we are done with this source file.
+  // Do this after notifying the preprocessor, so that end-of-file preprocessor
+  // callbacks can report diagnostics.
+  CI.getDiagnosticClient().EndSourceFile();
+
   // Finalize the action.
   EndSourceFileAction();
 

>From 911217c8a54eeffa1033a5f3b5ef0d7c288b2228 Mon Sep 17 00:00:00 2001
From: Dave Bartolomeo 
Date: Thu, 26 Jun 2025 08:57:08 -0400
Subject: [PATCH 2/4] Fix formatting

---
 .../clang-tidy/ClangTidyDiagnosticConsumer.cpp| 8 +++-
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosti

[clang] [CIR] Upstream UnaryDeref support for ComplexType (PR #146757)

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

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

>From 255b4ee2e630d446351244934b06733e5a3e9358 Mon Sep 17 00:00:00 2001
From: AmrDeveloper 
Date: Wed, 2 Jul 2025 20:48:36 +0200
Subject: [PATCH] [CIR] Upstream UnaryDeref support for ComplexType

---
 clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp |  5 
 clang/test/CIR/CodeGen/complex.cpp  | 28 +
 2 files changed, 33 insertions(+)

diff --git a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
index c5679fcaad0a7..c000b225f31f3 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
@@ -52,6 +52,7 @@ class ComplexExprEmitter : public 
StmtVisitor {
   mlir::Value VisitParenExpr(ParenExpr *e);
   mlir::Value
   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e);
+  mlir::Value VisitUnaryDeref(const Expr *e);
 };
 } // namespace
 
@@ -238,6 +239,10 @@ mlir::Value 
ComplexExprEmitter::VisitSubstNonTypeTemplateParmExpr(
   return Visit(e->getReplacement());
 }
 
+mlir::Value ComplexExprEmitter::VisitUnaryDeref(const Expr *e) {
+  return emitLoadOfLValue(e);
+}
+
 LValue CIRGenFunction::emitComplexAssignmentLValue(const BinaryOperator *e) {
   assert(e->getOpcode() == BO_Assign && "Expected assign op");
 
diff --git a/clang/test/CIR/CodeGen/complex.cpp 
b/clang/test/CIR/CodeGen/complex.cpp
index b0d8b879c88c9..09e0ca03aa540 100644
--- a/clang/test/CIR/CodeGen/complex.cpp
+++ b/clang/test/CIR/CodeGen/complex.cpp
@@ -626,3 +626,31 @@ void foo25() {
 // OGCG: %[[INIT_IMAG_PTR:.*]] = getelementptr inbounds nuw { double, double 
}, ptr %[[INIT]], i32 0, i32 1
 // OGCG: store double 1.00e+00, ptr %[[INIT_REAL_PTR]], align 8
 // OGCG: store double 2.00e+00, ptr %[[INIT_IMAG_PTR]], align 8
+
+void foo26(int _Complex* a) {
+  int _Complex b = *a;
+}
+
+// CIR: %[[COMPLEX_A_PTR:.*]] = cir.alloca !cir.ptr>, 
!cir.ptr>>, ["a", init]
+// CIR: %[[COMPLEX_B:.*]] = cir.alloca !cir.complex, 
!cir.ptr>, ["b", init]
+// CIR: %[[COMPLEX_A:.*]] = cir.load deref {{.*}} %[[COMPLEX_A_PTR]] : 
!cir.ptr>>, !cir.ptr>
+// CIR: %[[TMP:.*]] = cir.load{{.*}} %[[COMPLEX_A]] : 
!cir.ptr>, !cir.complex
+// CIR: cir.store{{.*}} %[[TMP]], %[[COMPLEX_B]] : !cir.complex, 
!cir.ptr>
+
+// LLVM: %[[COMPLEX_A_PTR:.*]] = alloca ptr, i64 1, align 8
+// LLVM: %[[COMPLEX_B:.*]] = alloca { i32, i32 }, i64 1, align 4
+// LLVM: %[[COMPLEX_A:.*]] = load ptr, ptr %[[COMPLEX_A_PTR]], align 8
+// LLVM: %[[TMP:.*]] = load { i32, i32 }, ptr %[[COMPLEX_A]], align 4
+// LLVM: store { i32, i32 } %[[TMP]], ptr %[[COMPLEX_B]], align 4
+
+// OGCG: %[[COMPLEX_A_PTR:.*]] = alloca ptr, align 8
+// OGCG: %[[COMPLEX_B:.*]] = alloca { i32, i32 }, align 4
+// OGCG: %[[COMPLEX_A:.*]] = load ptr, ptr %[[COMPLEX_A_PTR]], align 8
+// OGCG: %[[A_REAL_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, ptr 
%[[COMPLEX_A]], i32 0, i32 0
+// OGCG: %[[A_REAL:.*]] = load i32, ptr %[[A_REAL_PTR]], align 4
+// OGCG: %[[A_IMAG_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, ptr 
%[[COMPLEX_A]], i32 0, i32 1
+// OGCG: %[[A_IMAG:.*]] = load i32, ptr %[[A_IMAG_PTR]], align 4
+// OGCG: %[[B_REAL_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, ptr 
%[[COMPLEX_B]], i32 0, i32 0
+// OGCG: %[[B_IMAG_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, ptr 
%[[COMPLEX_B]], i32 0, i32 1
+// OGCG: store i32 %[[A_REAL]], ptr %[[B_REAL_PTR]], align 4
+// OGCG: store i32 %[[A_IMAG]], ptr %[[B_IMAG_PTR]], align 4

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


[clang] [llvm] [win][aarch64] Always reserve frame pointers for Arm64 Windows (PR #146582)

2025-07-03 Thread Daniel Paoliello via cfe-commits


@@ -518,6 +518,27 @@ bool AArch64FrameLowering::hasFPImpl(const MachineFunction 
&MF) const {
   return false;
 }
 
+/// Should the Frame Pointer be reserved for the current function?
+bool AArch64FrameLowering::isFPReserved(const MachineFunction &MF) const {
+  const TargetMachine &TM = MF.getTarget();
+  const Triple &TT = TM.getTargetTriple();
+
+  // These OSes require the frame chain is valid, even if the current frame 
does
+  // not use a frame pointer.
+  if (TT.isOSDarwin() || TT.isOSWindows())

dpaoliello wrote:

I'm not familiar with how flang works, but if it's going to scrape(?) the 
command line args from clang, then it needs to be able to handle all the same 
command line arguments that clang does.

This is not a bug in clang: this is a bug in flang and would be hit if anyone 
tried building Arm32 code in flang.

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


[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Abhinav Gaba (abhinavgaba)


Changes

The refactored code would allow creating multiple member-of maps for the same 
captured var, which would be useful for changes like 
https://github.com/llvm/llvm-project/pull/145454.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGOpenMPRuntime.cpp (+86-42) 


``diff
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 8ccc37ef98a74..a5f2f0efa2c3b 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6801,6 +6801,11 @@ class MappableExprsHandler {
   llvm::OpenMPIRBuilder::MapNonContiguousArrayTy;
   using MapExprsArrayTy = SmallVector;
   using MapValueDeclsArrayTy = SmallVector;
+  using MapData =
+  std::tuple,
+ bool /*IsImplicit*/, const ValueDecl *, const Expr *>;
+  using MapDataArrayTy = SmallVector;
 
   /// This structure contains combined information generated for mappable
   /// clauses, including base pointers, pointers, sizes, map types, 
user-defined
@@ -8496,6 +8501,7 @@ class MappableExprsHandler {
  const StructRangeInfoTy &PartialStruct, bool 
IsMapThis,
  llvm::OpenMPIRBuilder &OMPBuilder,
  const ValueDecl *VD = nullptr,
+ unsigned OffsetForMemberOfFlag = 0,
  bool NotTargetParams = true) const {
 if (CurTypes.size() == 1 &&
 ((CurTypes.back() & OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) !=
@@ -8583,8 +8589,8 @@ class MappableExprsHandler {
 // All other current entries will be MEMBER_OF the combined entry
 // (except for PTR_AND_OBJ entries which do not have a placeholder value
 // 0x in the MEMBER_OF field).
-OpenMPOffloadMappingFlags MemberOfFlag =
-OMPBuilder.getMemberOfFlag(CombinedInfo.BasePointers.size() - 1);
+OpenMPOffloadMappingFlags MemberOfFlag = OMPBuilder.getMemberOfFlag(
+OffsetForMemberOfFlag + CombinedInfo.BasePointers.size() - 1);
 for (auto &M : CurTypes)
   OMPBuilder.setCorrectMemberOfFlag(M, MemberOfFlag);
   }
@@ -8727,11 +8733,13 @@ class MappableExprsHandler {
 }
   }
 
-  /// Generate the base pointers, section pointers, sizes, map types, and
-  /// mappers associated to a given capture (all included in \a CombinedInfo).
-  void generateInfoForCapture(const CapturedStmt::Capture *Cap,
-  llvm::Value *Arg, MapCombinedInfoTy 
&CombinedInfo,
-  StructRangeInfoTy &PartialStruct) const {
+  /// For a capture that has an associated clause, generate the base pointers,
+  /// section pointers, sizes, map types, and mappers (all included in
+  /// \a CurCaptureVarInfo).
+  void generateInfoForCaptureFromClauseInfo(
+  const CapturedStmt::Capture *Cap, llvm::Value *Arg,
+  MapCombinedInfoTy &CurCaptureVarInfo, llvm::OpenMPIRBuilder &OMPBuilder,
+  unsigned OffsetForMemberOfFlag) const {
 assert(!Cap->capturesVariableArrayType() &&
"Not expecting to generate map info for a variable array type!");
 
@@ -8749,26 +8757,22 @@ class MappableExprsHandler {
 // pass the pointer by value. If it is a reference to a declaration, we 
just
 // pass its value.
 if (VD && (DevPointersMap.count(VD) || HasDevAddrsMap.count(VD))) {
-  CombinedInfo.Exprs.push_back(VD);
-  CombinedInfo.BasePointers.emplace_back(Arg);
-  CombinedInfo.DevicePtrDecls.emplace_back(VD);
-  CombinedInfo.DevicePointers.emplace_back(DeviceInfoTy::Pointer);
-  CombinedInfo.Pointers.push_back(Arg);
-  CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
+  CurCaptureVarInfo.Exprs.push_back(VD);
+  CurCaptureVarInfo.BasePointers.emplace_back(Arg);
+  CurCaptureVarInfo.DevicePtrDecls.emplace_back(VD);
+  CurCaptureVarInfo.DevicePointers.emplace_back(DeviceInfoTy::Pointer);
+  CurCaptureVarInfo.Pointers.push_back(Arg);
+  CurCaptureVarInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
   CGF.getTypeSize(CGF.getContext().VoidPtrTy), CGF.Int64Ty,
   /*isSigned=*/true));
-  CombinedInfo.Types.push_back(
+  CurCaptureVarInfo.Types.push_back(
   OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
   OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM);
-  CombinedInfo.Mappers.push_back(nullptr);
+  CurCaptureVarInfo.Mappers.push_back(nullptr);
   return;
 }
 
-using MapData =
-std::tuple, bool,
-   const ValueDecl *, const Expr *>;
-SmallVector DeclComponentLists;
+MapDataArrayTy DeclComponentLists;
 // For member fields list in is_device_ptr, store it in
 // DeclComponentLists for generating components info.
 static const OpenMPMapModifierKind Unknown = OMPC_MAP_MODIFIER_unknown;
@@ -8826,6 +8830,51 @@ class MappableExpr

[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Abhinav Gaba (abhinavgaba)


Changes

The refactored code would allow creating multiple member-of maps for the same 
captured var, which would be useful for changes like 
https://github.com/llvm/llvm-project/pull/145454.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGOpenMPRuntime.cpp (+86-42) 


``diff
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 8ccc37ef98a74..a5f2f0efa2c3b 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6801,6 +6801,11 @@ class MappableExprsHandler {
   llvm::OpenMPIRBuilder::MapNonContiguousArrayTy;
   using MapExprsArrayTy = SmallVector;
   using MapValueDeclsArrayTy = SmallVector;
+  using MapData =
+  std::tuple,
+ bool /*IsImplicit*/, const ValueDecl *, const Expr *>;
+  using MapDataArrayTy = SmallVector;
 
   /// This structure contains combined information generated for mappable
   /// clauses, including base pointers, pointers, sizes, map types, 
user-defined
@@ -8496,6 +8501,7 @@ class MappableExprsHandler {
  const StructRangeInfoTy &PartialStruct, bool 
IsMapThis,
  llvm::OpenMPIRBuilder &OMPBuilder,
  const ValueDecl *VD = nullptr,
+ unsigned OffsetForMemberOfFlag = 0,
  bool NotTargetParams = true) const {
 if (CurTypes.size() == 1 &&
 ((CurTypes.back() & OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) !=
@@ -8583,8 +8589,8 @@ class MappableExprsHandler {
 // All other current entries will be MEMBER_OF the combined entry
 // (except for PTR_AND_OBJ entries which do not have a placeholder value
 // 0x in the MEMBER_OF field).
-OpenMPOffloadMappingFlags MemberOfFlag =
-OMPBuilder.getMemberOfFlag(CombinedInfo.BasePointers.size() - 1);
+OpenMPOffloadMappingFlags MemberOfFlag = OMPBuilder.getMemberOfFlag(
+OffsetForMemberOfFlag + CombinedInfo.BasePointers.size() - 1);
 for (auto &M : CurTypes)
   OMPBuilder.setCorrectMemberOfFlag(M, MemberOfFlag);
   }
@@ -8727,11 +8733,13 @@ class MappableExprsHandler {
 }
   }
 
-  /// Generate the base pointers, section pointers, sizes, map types, and
-  /// mappers associated to a given capture (all included in \a CombinedInfo).
-  void generateInfoForCapture(const CapturedStmt::Capture *Cap,
-  llvm::Value *Arg, MapCombinedInfoTy 
&CombinedInfo,
-  StructRangeInfoTy &PartialStruct) const {
+  /// For a capture that has an associated clause, generate the base pointers,
+  /// section pointers, sizes, map types, and mappers (all included in
+  /// \a CurCaptureVarInfo).
+  void generateInfoForCaptureFromClauseInfo(
+  const CapturedStmt::Capture *Cap, llvm::Value *Arg,
+  MapCombinedInfoTy &CurCaptureVarInfo, llvm::OpenMPIRBuilder &OMPBuilder,
+  unsigned OffsetForMemberOfFlag) const {
 assert(!Cap->capturesVariableArrayType() &&
"Not expecting to generate map info for a variable array type!");
 
@@ -8749,26 +8757,22 @@ class MappableExprsHandler {
 // pass the pointer by value. If it is a reference to a declaration, we 
just
 // pass its value.
 if (VD && (DevPointersMap.count(VD) || HasDevAddrsMap.count(VD))) {
-  CombinedInfo.Exprs.push_back(VD);
-  CombinedInfo.BasePointers.emplace_back(Arg);
-  CombinedInfo.DevicePtrDecls.emplace_back(VD);
-  CombinedInfo.DevicePointers.emplace_back(DeviceInfoTy::Pointer);
-  CombinedInfo.Pointers.push_back(Arg);
-  CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
+  CurCaptureVarInfo.Exprs.push_back(VD);
+  CurCaptureVarInfo.BasePointers.emplace_back(Arg);
+  CurCaptureVarInfo.DevicePtrDecls.emplace_back(VD);
+  CurCaptureVarInfo.DevicePointers.emplace_back(DeviceInfoTy::Pointer);
+  CurCaptureVarInfo.Pointers.push_back(Arg);
+  CurCaptureVarInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
   CGF.getTypeSize(CGF.getContext().VoidPtrTy), CGF.Int64Ty,
   /*isSigned=*/true));
-  CombinedInfo.Types.push_back(
+  CurCaptureVarInfo.Types.push_back(
   OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
   OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM);
-  CombinedInfo.Mappers.push_back(nullptr);
+  CurCaptureVarInfo.Mappers.push_back(nullptr);
   return;
 }
 
-using MapData =
-std::tuple, bool,
-   const ValueDecl *, const Expr *>;
-SmallVector DeclComponentLists;
+MapDataArrayTy DeclComponentLists;
 // For member fields list in is_device_ptr, store it in
 // DeclComponentLists for generating components info.
 static const OpenMPMapModifierKind Unknown = OMPC_MAP_MODIFIER_unknown;
@@ -8826,6 +8830,51 @@ class Mapp

[clang] e93a346 - [CIR] Upstream SubstNonTypeTemplateParmExpr support for ComplexType (#146755)

2025-07-03 Thread via cfe-commits

Author: Amr Hesham
Date: 2025-07-03T17:50:21+02:00
New Revision: e93a34662f1471c17f2afa7461ec71bf7913b984

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

LOG: [CIR] Upstream SubstNonTypeTemplateParmExpr support for ComplexType 
(#146755)

Upstream SubstNonTypeTemplateParmExpr support for ComplexType

https://github.com/llvm/llvm-project/issues/141365

Added: 


Modified: 
clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
clang/test/CIR/CodeGen/complex.cpp

Removed: 




diff  --git a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
index 3dc47dd205244..c5679fcaad0a7 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
@@ -50,6 +50,8 @@ class ComplexExprEmitter : public 
StmtVisitor {
   mlir::Value VisitInitListExpr(const InitListExpr *e);
   mlir::Value VisitImaginaryLiteral(const ImaginaryLiteral *il);
   mlir::Value VisitParenExpr(ParenExpr *e);
+  mlir::Value
+  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e);
 };
 } // namespace
 
@@ -231,6 +233,11 @@ mlir::Value ComplexExprEmitter::VisitParenExpr(ParenExpr 
*e) {
   return Visit(e->getSubExpr());
 }
 
+mlir::Value ComplexExprEmitter::VisitSubstNonTypeTemplateParmExpr(
+SubstNonTypeTemplateParmExpr *e) {
+  return Visit(e->getReplacement());
+}
+
 LValue CIRGenFunction::emitComplexAssignmentLValue(const BinaryOperator *e) {
   assert(e->getOpcode() == BO_Assign && "Expected assign op");
 

diff  --git a/clang/test/CIR/CodeGen/complex.cpp 
b/clang/test/CIR/CodeGen/complex.cpp
index 78d7a2024490b..b0d8b879c88c9 100644
--- a/clang/test/CIR/CodeGen/complex.cpp
+++ b/clang/test/CIR/CodeGen/complex.cpp
@@ -1,8 +1,8 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-fclangir -emit-cir %s -o %t.cir
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu 
-Wno-unused-value -fclangir -emit-cir %s -o %t.cir
 // RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu 
-Wno-unused-value -fclangir -emit-llvm %s -o %t-cir.ll
 // RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-emit-llvm %s -o %t.ll
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu 
-Wno-unused-value -emit-llvm %s -o %t.ll
 // RUN: FileCheck --input-file=%t.ll %s -check-prefix=OGCG
 
 int _Complex ci;
@@ -607,3 +607,22 @@ void foo24() {
 // OGCG: %[[RESULT_IMAG_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, 
ptr %[[RESULT]], i32 0, i32 1
 // OGCG: store i32 %[[ELEM_REAL]], ptr %[[RESULT_REAL_PTR]], align 4
 // OGCG: store i32 %[[ELEM_IMAG]], ptr %[[RESULT_IMAG_PTR]], align 4
+
+template  void template_foo() { double _Complex C = N; }
+
+void foo25() {
+  template_foo<__builtin_complex(1.0, 2.0)>();
+}
+
+// CIR: %[[INIT:.*]] = cir.alloca !cir.complex, 
!cir.ptr>, ["C", init]
+// CIR: %[[COMPLEX:.*]] = cir.const #cir.const_complex<#cir.fp<1.00e+00> : 
!cir.double, #cir.fp<2.00e+00> : !cir.double> : !cir.complex
+// CIR: cir.store{{.*}} %[[COMPLEX]], %[[INIT]] : !cir.complex, 
!cir.ptr>
+
+// LLVM: %[[INIT:.*]] = alloca { double, double }, i64 1, align 8
+// LLVM: store { double, double } { double 1.00e+00, double 2.00e+00 
}, ptr %[[INIT]], align 8
+
+// OGCG: %[[INIT:.*]] = alloca { double, double }, align 8
+// OGCG: %[[INIT_REAL_PTR:.*]] = getelementptr inbounds nuw { double, double 
}, ptr %[[INIT]], i32 0, i32 0
+// OGCG: %[[INIT_IMAG_PTR:.*]] = getelementptr inbounds nuw { double, double 
}, ptr %[[INIT]], i32 0, i32 1
+// OGCG: store double 1.00e+00, ptr %[[INIT_REAL_PTR]], align 8
+// OGCG: store double 2.00e+00, ptr %[[INIT_IMAG_PTR]], align 8



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


[clang] [CIR] Upstream SubstNonTypeTemplateParmExpr support for ComplexType (PR #146755)

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

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits

https://github.com/flovent updated 
https://github.com/llvm/llvm-project/pull/146212

>From 9da53c788fc01cd3fc2dd4c178b836035b5d380b Mon Sep 17 00:00:00 2001
From: flovent 
Date: Sat, 28 Jun 2025 20:58:43 +0800
Subject: [PATCH 01/10] [analyzer] Avoid unnecessary super region invalidation
 in `CStringChecker`

---
 .../Checkers/CStringChecker.cpp   |  77 -
 .../cstring-should-not-invalidate.cpp | 107 ++
 2 files changed, 178 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/Analysis/cstring-should-not-invalidate.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 4d12fdcec1f1a..433fd2ce5f292 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -272,7 +272,8 @@ class CStringChecker : public Checker< eval::Call,
   static ProgramStateRef
   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
 const Expr *BufE, ConstCFGElementRef Elem,
-SVal BufV, SVal SizeV, QualType SizeTy);
+SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound = true);
 
   /// Operation never overflows, do not invalidate the super region.
   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
@@ -1211,14 +1212,17 @@ bool CStringChecker::isFirstBufInBound(CheckerContext 
&C, ProgramStateRef State,
 
 ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
 CheckerContext &C, ProgramStateRef S, const Expr *BufE,
-ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) {
+ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound) {
   auto InvalidationTraitOperations =
-  [&C, S, BufTy = BufE->getType(), BufV, SizeV,
-   SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) 
{
+  [&C, S, BufTy = BufE->getType(), BufV, SizeV, SizeTy,
+   CouldAccessOutOfBound](RegionAndSymbolInvalidationTraits &ITraits,
+  const MemRegion *R) {
 // If destination buffer is a field region and access is in bound, do
 // not invalidate its super region.
 if (MemRegion::FieldRegionKind == R->getKind() &&
-isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
+(!CouldAccessOutOfBound ||
+ isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy))) {
   ITraits.setTrait(
   R,
   
RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
@@ -2223,6 +2227,67 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, 
const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
+  SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
+
+  // Protect against misdeclared strncpy().
+  lenVal =
+  svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
+
+  std::optional lenValNL = lenVal.getAs();
+
+  auto CouldAccessOutOfBoundForSVal = [&](NonLoc Val) -> bool {
+return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
+  Dst.Expression->getType(), Val,
+  C.getASTContext().getSizeType());
+  };
+
+  if (strLengthNL) {
+CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*strLengthNL);
+  }
+
+  if (CouldAccessOutOfBound && lenValNL) {
+switch (appendK) {
+case ConcatFnKind::none:
+case ConcatFnKind::strcat: {
+  CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*lenValNL);
+  break;
+}
+case ConcatFnKind::strlcat: {
+  if (!dstStrLengthNL)
+break;
+
+  SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
+   *dstStrLengthNL, sizeTy);
+  if (!isa(freeSpace))
+break;
+
+  freeSpace =
+  svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
+svalBuilder.makeIntVal(1, sizeTy), sizeTy);
+  std::optional f

[clang] 59d641a - [CIR] Upstream support for SubstNonTypeTemplateParmExpr (#146751)

2025-07-03 Thread via cfe-commits

Author: Amr Hesham
Date: 2025-07-03T17:50:00+02:00
New Revision: 59d641a2dab475f6ab0ab1308b1d6dd641dccb6a

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

LOG: [CIR] Upstream support for SubstNonTypeTemplateParmExpr (#146751)

Upstream support for SubstNonTypeTemplateParmExpr

Added: 
clang/test/CIR/CodeGen/non-type-template-param.cpp

Modified: 
clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp

Removed: 




diff  --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index b76b703a79fe8..10c485c85e22a 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -371,6 +371,11 @@ class ScalarExprEmitter : public 
StmtVisitor {
 return builder.create(src.getLoc(), fullDstTy, *castKind, 
src);
   }
 
+  mlir::Value
+  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e) {
+return Visit(e->getReplacement());
+  }
+
   mlir::Value VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *e);
   mlir::Value
   VisitAbstractConditionalOperator(const AbstractConditionalOperator *e);

diff  --git a/clang/test/CIR/CodeGen/non-type-template-param.cpp 
b/clang/test/CIR/CodeGen/non-type-template-param.cpp
new file mode 100644
index 0..8ef1d5785c700
--- /dev/null
+++ b/clang/test/CIR/CodeGen/non-type-template-param.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-fclangir -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s -check-prefix=OGCG
+
+template 
+void template_foo() {
+  int a = N + 5;
+}
+
+// CIR: %[[INIT:.*]] = cir.alloca !s32i, !cir.ptr, ["a", init]
+// CIR: %[[CONST_1:.*]] = cir.const #cir.int<1> : !s32i
+// CIR: %[[CONST_2:.*]] = cir.const #cir.int<5> : !s32i
+// CIR: %[[ADD:.*]] = cir.binop(add, %[[CONST_1]], %[[CONST_2]]) nsw : !s32i
+// CIR: cir.store{{.*}} %[[ADD]], %[[INIT]] : !s32i, !cir.ptr
+
+// LLVM: %[[INIT:.*]] = alloca i32, i64 1, align 4
+// LLVM: store i32 6, ptr %[[INIT]], align 4
+
+// OGCG: %[[INIT:.*]] = alloca i32, align 4
+// OGCG: store i32 6, ptr %[[INIT]], align 4
+
+void foo() {
+  template_foo<1>();
+}



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


[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread Abhinav Gaba via cfe-commits

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


[clang] [CIR] Upstream support for SubstNonTypeTemplateParmExpr (PR #146751)

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

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


[clang] [P3074] Partial implementation of support for trivial unions (PR #146815)

2025-07-03 Thread Barry Revzin via cfe-commits

https://github.com/brevzin updated 
https://github.com/llvm/llvm-project/pull/146815

>From 40290a957b6f349a9b670193c8bc699d8eb7d373 Mon Sep 17 00:00:00 2001
From: Barry Revzin 
Date: Fri, 27 Jun 2025 17:29:45 -0500
Subject: [PATCH 1/6] [P3074] Implementing part of trivial unions

---
 clang/lib/AST/DeclCXX.cpp   |  9 --
 clang/lib/Sema/SemaDeclCXX.cpp  | 16 +-
 clang/test/CXX/drs/cwg6xx.cpp   |  4 +--
 clang/test/CXX/special/class.ctor/p5-0x.cpp | 15 +-
 clang/test/CXX/special/class.ctor/p6-0x.cpp | 28 +
 clang/test/CXX/special/class.dtor/p5-0x.cpp | 33 +++--
 6 files changed, 63 insertions(+), 42 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index ccb308e103253..49adbdf1c393d 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1217,6 +1217,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 // those because they are always unnamed.
 bool IsZeroSize = Field->isZeroSize(Context);
 
+// P3074
+const bool TrivialUnion = Context.getLangOpts().CPlusPlus26 && isUnion();
+
 if (const auto *RecordTy = T->getAs()) {
   auto *FieldRec = cast(RecordTy->getDecl());
   if (FieldRec->getDefinition()) {
@@ -1277,7 +1280,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
 //-- for all the non-static data members of its class that are of
 //   class type (or array thereof), each such class has a trivial
 //   default constructor.
-if (!FieldRec->hasTrivialDefaultConstructor())
+if (!FieldRec->hasTrivialDefaultConstructor() && !TrivialUnion)
   data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
 
 // C++0x [class.copy]p13:
@@ -1315,9 +1318,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 if (!FieldRec->hasTrivialMoveAssignment())
   data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
 
-if (!FieldRec->hasTrivialDestructor())
+if (!FieldRec->hasTrivialDestructor() && !TrivialUnion)
   data().HasTrivialSpecialMembers &= ~SMF_Destructor;
-if (!FieldRec->hasTrivialDestructorForCall())
+if (!FieldRec->hasTrivialDestructorForCall() && !TrivialUnion)
   data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
 if (!FieldRec->hasIrrelevantDestructor())
   data().HasIrrelevantDestructor = false;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index e8c65025bfe6d..225409a69df53 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9511,6 +9511,15 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
   CXXMethodDecl *Decl = SMOR.getMethod();
   FieldDecl *Field = Subobj.dyn_cast();
 
+  // P3074: default ctor and dtor for unions are not deleted, regardless of
+  // whether the underlying fields have non-trivial or deleted versions of 
those
+  // members
+  if (S.Context.getLangOpts().CPlusPlus26)
+if (Field && Field->getParent()->isUnion() &&
+(CSM == CXXSpecialMemberKind::DefaultConstructor ||
+ CSM == CXXSpecialMemberKind::Destructor))
+  return false;
+
   int DiagKind = -1;
 
   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
@@ -9774,7 +9783,8 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
 
   // At least one member in each anonymous union must be non-const
   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
-  AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
+  AllVariantFieldsAreConst && !FieldRecord->field_empty() &&
+  !S.Context.getLangOpts().CPlusPlus26) {
 if (Diagnose)
   S.Diag(FieldRecord->getLocation(),
  diag::note_deleted_default_ctor_all_const)
@@ -9804,6 +9814,10 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
   // default constructor. Don't do that.
   if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
   AllFieldsAreConst) {
+
+if (S.Context.getLangOpts().CPlusPlus26)
+  return false;
+
 bool AnyFields = false;
 for (auto *F : MD->getParent()->fields())
   if ((AnyFields = !F->isUnnamedBitField()))
diff --git a/clang/test/CXX/drs/cwg6xx.cpp b/clang/test/CXX/drs/cwg6xx.cpp
index e2eb009508b52..dd54bb5295b56 100644
--- a/clang/test/CXX/drs/cwg6xx.cpp
+++ b/clang/test/CXX/drs/cwg6xx.cpp
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,cxx11-20,cxx98-17,cxx11-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
 // RUN: %clang_cc1 -std=c++20 %s -verify=expected,cxx11-20,since-cxx11 
-fexceptions -fcxx-exceptions -pedantic-errors
 // RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++2c %s -verify=expected,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc

[clang] [P3074] Partial implementation of support for trivial unions (PR #146815)

2025-07-03 Thread Barry Revzin via cfe-commits

https://github.com/brevzin updated 
https://github.com/llvm/llvm-project/pull/146815

>From 40290a957b6f349a9b670193c8bc699d8eb7d373 Mon Sep 17 00:00:00 2001
From: Barry Revzin 
Date: Fri, 27 Jun 2025 17:29:45 -0500
Subject: [PATCH 1/7] [P3074] Implementing part of trivial unions

---
 clang/lib/AST/DeclCXX.cpp   |  9 --
 clang/lib/Sema/SemaDeclCXX.cpp  | 16 +-
 clang/test/CXX/drs/cwg6xx.cpp   |  4 +--
 clang/test/CXX/special/class.ctor/p5-0x.cpp | 15 +-
 clang/test/CXX/special/class.ctor/p6-0x.cpp | 28 +
 clang/test/CXX/special/class.dtor/p5-0x.cpp | 33 +++--
 6 files changed, 63 insertions(+), 42 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index ccb308e103253..49adbdf1c393d 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1217,6 +1217,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 // those because they are always unnamed.
 bool IsZeroSize = Field->isZeroSize(Context);
 
+// P3074
+const bool TrivialUnion = Context.getLangOpts().CPlusPlus26 && isUnion();
+
 if (const auto *RecordTy = T->getAs()) {
   auto *FieldRec = cast(RecordTy->getDecl());
   if (FieldRec->getDefinition()) {
@@ -1277,7 +1280,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
 //-- for all the non-static data members of its class that are of
 //   class type (or array thereof), each such class has a trivial
 //   default constructor.
-if (!FieldRec->hasTrivialDefaultConstructor())
+if (!FieldRec->hasTrivialDefaultConstructor() && !TrivialUnion)
   data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
 
 // C++0x [class.copy]p13:
@@ -1315,9 +1318,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 if (!FieldRec->hasTrivialMoveAssignment())
   data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
 
-if (!FieldRec->hasTrivialDestructor())
+if (!FieldRec->hasTrivialDestructor() && !TrivialUnion)
   data().HasTrivialSpecialMembers &= ~SMF_Destructor;
-if (!FieldRec->hasTrivialDestructorForCall())
+if (!FieldRec->hasTrivialDestructorForCall() && !TrivialUnion)
   data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
 if (!FieldRec->hasIrrelevantDestructor())
   data().HasIrrelevantDestructor = false;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index e8c65025bfe6d..225409a69df53 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9511,6 +9511,15 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
   CXXMethodDecl *Decl = SMOR.getMethod();
   FieldDecl *Field = Subobj.dyn_cast();
 
+  // P3074: default ctor and dtor for unions are not deleted, regardless of
+  // whether the underlying fields have non-trivial or deleted versions of 
those
+  // members
+  if (S.Context.getLangOpts().CPlusPlus26)
+if (Field && Field->getParent()->isUnion() &&
+(CSM == CXXSpecialMemberKind::DefaultConstructor ||
+ CSM == CXXSpecialMemberKind::Destructor))
+  return false;
+
   int DiagKind = -1;
 
   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
@@ -9774,7 +9783,8 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
 
   // At least one member in each anonymous union must be non-const
   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
-  AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
+  AllVariantFieldsAreConst && !FieldRecord->field_empty() &&
+  !S.Context.getLangOpts().CPlusPlus26) {
 if (Diagnose)
   S.Diag(FieldRecord->getLocation(),
  diag::note_deleted_default_ctor_all_const)
@@ -9804,6 +9814,10 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
   // default constructor. Don't do that.
   if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
   AllFieldsAreConst) {
+
+if (S.Context.getLangOpts().CPlusPlus26)
+  return false;
+
 bool AnyFields = false;
 for (auto *F : MD->getParent()->fields())
   if ((AnyFields = !F->isUnnamedBitField()))
diff --git a/clang/test/CXX/drs/cwg6xx.cpp b/clang/test/CXX/drs/cwg6xx.cpp
index e2eb009508b52..dd54bb5295b56 100644
--- a/clang/test/CXX/drs/cwg6xx.cpp
+++ b/clang/test/CXX/drs/cwg6xx.cpp
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,cxx11-20,cxx98-17,cxx11-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
 // RUN: %clang_cc1 -std=c++20 %s -verify=expected,cxx11-20,since-cxx11 
-fexceptions -fcxx-exceptions -pedantic-errors
 // RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++2c %s -verify=expected,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc

[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits


@@ -0,0 +1,106 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s

flovent wrote:


> Added `alpha.unix.cstring` and `unix.cstring` to testcase, 
> `alpha.unix.cstring` makes a difference, in line 66, if `size` is equal to 
> `dest`'s size, `alpha.unix.cstring.OutOfBounds` will be reported, that's 
> before we check `size` or `srcLen`.

I added the version before i changed in 
02ad1b9a3356ccf3d2816a5087f905183a5e4668 back, make it produce 
`alpha.unix.cstring.OutOfBounds`.


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


[clang] [Clang][AArch64] Remove redundant tune args to the backend (PR #146896)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-aarch64

Author: Tomer Shafir (tomershafir)


Changes

This change removes unnecessary tune args to the AArch64 backend. The AArch64 
backend automatically handles `tune-cpu` and adds the necessar
y features based on the models from TableGen.

It follows this fix: https://github.com/llvm/llvm-project/pull/146260 where 
updating a subtarget feature didn't fail the frontend test because both the 
toolchain and the test suffered from a coordinated error.

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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Arch/AArch64.cpp (-11) 
- (modified) clang/test/Preprocessor/aarch64-target-features.c (+8-8) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 343a18b9ca2ea..4f45c369c83db 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -163,17 +163,6 @@ getAArch64MicroArchFeaturesFromMtune(const Driver &D, 
StringRef Mtune,
   if (!DecodeAArch64Mcpu(D, MtuneLowerCase, Tune, Extensions))
 return false;
 
-  // Handle CPU name is 'native'.
-  if (MtuneLowerCase == "native")
-MtuneLowerCase = std::string(llvm::sys::getHostCPUName());
-
-  // 'cyclone' and later have zero-cycle register moves and zeroing.
-  if (MtuneLowerCase == "cyclone" ||
-  StringRef(MtuneLowerCase).starts_with("apple")) {
-Features.push_back("+zcm-gpr64");
-Features.push_back("+zcz");
-  }
-
   return true;
 }
 
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 6700153b79795..d7201207db572 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -316,7 +316,7 @@
 
 // == Check whether -mtune accepts mixed-case features.
 // RUN: %clang -target aarch64 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MTUNE-CYCLONE %s
-// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" "+v8a"
+// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a"
 
 // RUN: %clang -target aarch64 -mcpu=apple-a7 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
 // RUN: %clang -target aarch64 -mcpu=apple-a8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
@@ -342,12 +342,12 @@
 // RUN: %clang -target aarch64 -mcpu=thunderx2t99 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-THUNDERX2T99 %s
 // RUN: %clang -target aarch64 -mcpu=a64fx -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-A64FX %s
 // RUN: %clang -target aarch64 -mcpu=carmel -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-CARMEL %s
-// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+crc" "-target-feature" 
"+fp-armv8" "-target-feature" "+lor" "-target-feature" "+neon" 
"-target-feature" "+pan" "-target-feature" "+perfmon" "-target-feature" "+rdm" 
"-target-feature" "+sha2" "-target-feature" "+vh"
-// CHECK-MCPU-APPLE-A11: "-cc1"{{.*}} "-triple" 
"aarch64{{.*}}"{{.*}}"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" 
"-target-feature" "+v8.2a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+fullfp16" "-target-feature" 
"+lse" "-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" 
"+ras" "-target-feature" "+rdm" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A12: "-cc1"{{.*}} "-triple" "aarch64"{{.*}} 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8.3a" "-target-feature" "+aes" "-target-feature" "+complxnum" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+fullfp16" "-target-feature" "+jsconv" "-target-feature" "+lse" 
"-target-feature" "+neon" "-target-feature" "+pauth" "-target-feature" 
"+perfmon" "-target-feature" "+ras" "-target-feature" "+rcpc" "-target-feature" 
"+rdm" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+lor" "-target-feature" 
"+neon" "-target-feature"

[clang] [Clang][AArch64] Remove redundant tune args to the backend (PR #146896)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Tomer Shafir (tomershafir)


Changes

This change removes unnecessary tune args to the AArch64 backend. The AArch64 
backend automatically handles `tune-cpu` and adds the necessar
y features based on the models from TableGen.

It follows this fix: https://github.com/llvm/llvm-project/pull/146260 where 
updating a subtarget feature didn't fail the frontend test because both the 
toolchain and the test suffered from a coordinated error.

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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Arch/AArch64.cpp (-11) 
- (modified) clang/test/Preprocessor/aarch64-target-features.c (+8-8) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 343a18b9ca2ea..4f45c369c83db 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -163,17 +163,6 @@ getAArch64MicroArchFeaturesFromMtune(const Driver &D, 
StringRef Mtune,
   if (!DecodeAArch64Mcpu(D, MtuneLowerCase, Tune, Extensions))
 return false;
 
-  // Handle CPU name is 'native'.
-  if (MtuneLowerCase == "native")
-MtuneLowerCase = std::string(llvm::sys::getHostCPUName());
-
-  // 'cyclone' and later have zero-cycle register moves and zeroing.
-  if (MtuneLowerCase == "cyclone" ||
-  StringRef(MtuneLowerCase).starts_with("apple")) {
-Features.push_back("+zcm-gpr64");
-Features.push_back("+zcz");
-  }
-
   return true;
 }
 
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 6700153b79795..d7201207db572 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -316,7 +316,7 @@
 
 // == Check whether -mtune accepts mixed-case features.
 // RUN: %clang -target aarch64 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MTUNE-CYCLONE %s
-// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" "+v8a"
+// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a"
 
 // RUN: %clang -target aarch64 -mcpu=apple-a7 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
 // RUN: %clang -target aarch64 -mcpu=apple-a8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
@@ -342,12 +342,12 @@
 // RUN: %clang -target aarch64 -mcpu=thunderx2t99 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-THUNDERX2T99 %s
 // RUN: %clang -target aarch64 -mcpu=a64fx -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-A64FX %s
 // RUN: %clang -target aarch64 -mcpu=carmel -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-CARMEL %s
-// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+crc" "-target-feature" 
"+fp-armv8" "-target-feature" "+lor" "-target-feature" "+neon" 
"-target-feature" "+pan" "-target-feature" "+perfmon" "-target-feature" "+rdm" 
"-target-feature" "+sha2" "-target-feature" "+vh"
-// CHECK-MCPU-APPLE-A11: "-cc1"{{.*}} "-triple" 
"aarch64{{.*}}"{{.*}}"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" 
"-target-feature" "+v8.2a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+fullfp16" "-target-feature" 
"+lse" "-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" 
"+ras" "-target-feature" "+rdm" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A12: "-cc1"{{.*}} "-triple" "aarch64"{{.*}} 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8.3a" "-target-feature" "+aes" "-target-feature" "+complxnum" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+fullfp16" "-target-feature" "+jsconv" "-target-feature" "+lse" 
"-target-feature" "+neon" "-target-feature" "+pauth" "-target-feature" 
"+perfmon" "-target-feature" "+ras" "-target-feature" "+rcpc" "-target-feature" 
"+rdm" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+lor" "-target-feature" 
"+neon" "-target-feature" "+

[clang] [Clang][AArch64] Remove redundant tune args to the backend (PR #146896)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Tomer Shafir (tomershafir)


Changes

This change removes unnecessary tune args to the AArch64 backend. The AArch64 
backend automatically handles `tune-cpu` and adds the necessar
y features based on the models from TableGen.

It follows this fix: https://github.com/llvm/llvm-project/pull/146260 where 
updating a subtarget feature didn't fail the frontend test because both the 
toolchain and the test suffered from a coordinated error.

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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Arch/AArch64.cpp (-11) 
- (modified) clang/test/Preprocessor/aarch64-target-features.c (+8-8) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 343a18b9ca2ea..4f45c369c83db 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -163,17 +163,6 @@ getAArch64MicroArchFeaturesFromMtune(const Driver &D, 
StringRef Mtune,
   if (!DecodeAArch64Mcpu(D, MtuneLowerCase, Tune, Extensions))
 return false;
 
-  // Handle CPU name is 'native'.
-  if (MtuneLowerCase == "native")
-MtuneLowerCase = std::string(llvm::sys::getHostCPUName());
-
-  // 'cyclone' and later have zero-cycle register moves and zeroing.
-  if (MtuneLowerCase == "cyclone" ||
-  StringRef(MtuneLowerCase).starts_with("apple")) {
-Features.push_back("+zcm-gpr64");
-Features.push_back("+zcz");
-  }
-
   return true;
 }
 
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 6700153b79795..d7201207db572 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -316,7 +316,7 @@
 
 // == Check whether -mtune accepts mixed-case features.
 // RUN: %clang -target aarch64 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MTUNE-CYCLONE %s
-// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" "+v8a"
+// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a"
 
 // RUN: %clang -target aarch64 -mcpu=apple-a7 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
 // RUN: %clang -target aarch64 -mcpu=apple-a8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
@@ -342,12 +342,12 @@
 // RUN: %clang -target aarch64 -mcpu=thunderx2t99 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-THUNDERX2T99 %s
 // RUN: %clang -target aarch64 -mcpu=a64fx -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-A64FX %s
 // RUN: %clang -target aarch64 -mcpu=carmel -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-CARMEL %s
-// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+crc" "-target-feature" 
"+fp-armv8" "-target-feature" "+lor" "-target-feature" "+neon" 
"-target-feature" "+pan" "-target-feature" "+perfmon" "-target-feature" "+rdm" 
"-target-feature" "+sha2" "-target-feature" "+vh"
-// CHECK-MCPU-APPLE-A11: "-cc1"{{.*}} "-triple" 
"aarch64{{.*}}"{{.*}}"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" 
"-target-feature" "+v8.2a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+fullfp16" "-target-feature" 
"+lse" "-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" 
"+ras" "-target-feature" "+rdm" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A12: "-cc1"{{.*}} "-triple" "aarch64"{{.*}} 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8.3a" "-target-feature" "+aes" "-target-feature" "+complxnum" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+fullfp16" "-target-feature" "+jsconv" "-target-feature" "+lse" 
"-target-feature" "+neon" "-target-feature" "+pauth" "-target-feature" 
"+perfmon" "-target-feature" "+ras" "-target-feature" "+rcpc" "-target-feature" 
"+rdm" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+lor" "-target-feature" 
"+neon" "-target-feature" "+pan" "-

[clang] [Clang][AArch64] Remove redundant tune args to the backend (PR #146896)

2025-07-03 Thread Tomer Shafir via cfe-commits

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


[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff HEAD~1 HEAD --extensions cpp -- 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 1964f9179..a5f2f0efa 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -9563,7 +9563,6 @@ static void genMapInfoForCaptures(
CurInfo.BasePointers.size() == CurInfo.Mappers.size() &&
"Inconsistent map information sizes!");
 
-
 // We need to append the results of this capture to what we already have.
 CombinedInfo.append(CurInfo);
   }

``




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


[clang] [llvm] [win][aarch64] Always reserve frame pointers for Arm64 Windows (PR #146582)

2025-07-03 Thread David Spickett via cfe-commits

DavidSpickett wrote:

The actual error is the same as seen elsewhere:
```
$ /home/david.spickett/build-llvm-aarch64/bin/flang 
--target=aarch64-pc-windows-msvc -Werror 
../llvm-project/flang/test/Semantics/windows.f90
flang-21: warning: unable to find a Visual Studio installation; try running 
Clang from a developer command prompt [-Wmsvc-not-found]
error: invalid value 'reserved' in '-mframe-pointer=reserved'
```
It was obscured by this test running the compiler via a Python script.

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


[clang] [clang] SourceManager: Cache offsets for LastFileIDLookup to speed up getFileID (PR #146782)

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


@@ -832,13 +835,11 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
   unsigned LessIndex = 0;
   // upper bound of the search range.
   unsigned GreaterIndex = LocalSLocEntryTable.size();
-  if (LastFileIDLookup.ID >= 0) {
-// Use the LastFileIDLookup to prune the search space.
-if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
-  LessIndex = LastFileIDLookup.ID;
-else
-  GreaterIndex = LastFileIDLookup.ID;
-  }
+  // Use the LastFileIDLookup to prune the search space.
+  if (LastLookupStartOffset < SLocOffset)
+LessIndex = LastFileIDLookup.ID;

hokein wrote:

Yes, exactly the old code `LastFileIDLookup.ID >= 0` is always true, it is 
always executed. 

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


[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread Abhinav Gaba via cfe-commits


@@ -8727,11 +8733,13 @@ class MappableExprsHandler {
 }
   }
 
-  /// Generate the base pointers, section pointers, sizes, map types, and
-  /// mappers associated to a given capture (all included in \a CombinedInfo).
-  void generateInfoForCapture(const CapturedStmt::Capture *Cap,
-  llvm::Value *Arg, MapCombinedInfoTy 
&CombinedInfo,
-  StructRangeInfoTy &PartialStruct) const {
+  /// For a capture that has an associated clause, generate the base pointers,
+  /// section pointers, sizes, map types, and mappers (all included in
+  /// \a CurCaptureVarInfo).
+  void generateInfoForCaptureFromClauseInfo(

abhinavgaba wrote:

The original function is now split into two. The first one here creates the 
DeclComponentLists, and the second one handles these DeclComponentLists.

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


[clang] [NFC][Clang][OpenMP] Refactor mapinfo generation for captured vars (PR #146891)

2025-07-03 Thread Abhinav Gaba via cfe-commits


@@ -8826,6 +8830,51 @@ class MappableExprsHandler {
   return (HasPresent && !HasPresentR) || (HasAllocs && !HasAllocsR);
 });
 
+auto GenerateInfoForComponentLists =
+[&](ArrayRef DeclComponentLists,
+bool IsEligibleForTargetParamFlag) {
+  MapCombinedInfoTy CurInfoForComponentLists;
+  StructRangeInfoTy PartialStruct;

abhinavgaba wrote:

Moving PartialStruct here allows us to make it local to each set of 
DeclComponentLists, so when GenerateInfoForComponentLists is called multiple 
times with different lists, we'll get different combined entries and member-of 
flags for each of those lists.

For now, this is called only once with the full set of DeclComponentLists from 
line 8867.

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


[clang] [clang][dataflow] Handle when `this` refers to a different location (PR #146900)

2025-07-03 Thread Jan Voung via cfe-commits

https://github.com/jvoung created 
https://github.com/llvm/llvm-project/pull/146900

When `this` is under a CXXDefaultInitExpr. E.g.,
struct S {
  int x;
  int y = this->x;
};
struct R {
  int foo() {
// `this` for `a` refers to an R, but `this`
// for `x` refers to an S.
return S{this->a}.y;
  }
  int a;
};

Prepares for https://github.com/llvm/llvm-project/issues/128068


>From 7cadb15cacf77231d63bb98846346f819d644fa7 Mon Sep 17 00:00:00 2001
From: Jan Voung 
Date: Thu, 3 Jul 2025 13:37:18 +
Subject: [PATCH] [clang][dataflow] Handle when `this` refers to a different
 location

When `this` is under a CXXDefaultInitExpr. E.g.,
struct S {
  int x;
  int y = this->x;
};
struct R {
  int foo() {
// `this` for `a` refers to an R, but `this`
// for `x` refers to an S.
return S{this->a}.y;
  }
  int a;
};

Prepares for https://github.com/llvm/llvm-project/issues/128068
---
 .../FlowSensitive/DataflowEnvironment.h   |  41 
 .../FlowSensitive/DataflowEnvironment.cpp | 134 +++
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   2 +-
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 222 ++
 .../UncheckedOptionalAccessModelTest.cpp  |  21 ++
 5 files changed, 419 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 097ff2bdfe7ad..e9b85093d8e3e 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/Type.h"
 #include "clang/Analysis/FlowSensitive/ASTOps.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
@@ -351,10 +352,34 @@ class Environment {
   /// Returns the storage location assigned to the `this` pointee in the
   /// environment or null if the `this` pointee has no assigned storage 
location
   /// in the environment.
+  /// If you want to look up the storage location for a specific `CXXThisExpr`,
+  /// use the overload that takes a `CXXThisExpr`.
   RecordStorageLocation *getThisPointeeStorageLocation() const {
 return ThisPointeeLoc;
   }
 
+  /// Returns the storage location assigned to the `this` pointee in the
+  /// environment given a specific `CXXThisExpr`. Returns null if the `this`
+  /// pointee has no assigned storage location in the environment.
+  /// Note that `this` can be used in a non-member context, e.g.:
+  ///
+  /// \code
+  ///   struct S {
+  /// int x;
+  /// int y = this->x;
+  ///   };
+  ///   int foo() {
+  /// return S{10}.y;  // will have a `this` for initializing `S::y`.
+  ///   }
+  /// \endcode
+  RecordStorageLocation *
+  getThisPointeeStorageLocation(const CXXThisExpr &ThisExpr) const {
+auto It = ThisExprOverrides->find(&ThisExpr);
+if (It == ThisExprOverrides->end())
+  return ThisPointeeLoc;
+return It->second;
+  }
+
   /// Sets the storage location assigned to the `this` pointee in the
   /// environment.
   void setThisPointeeStorageLocation(RecordStorageLocation &Loc) {
@@ -684,6 +709,8 @@ class Environment {
 private:
   using PrValueToResultObject =
   llvm::DenseMap;
+  using ThisExprOverridesMap =
+  llvm::DenseMap;
 
   // The copy-constructor is for use in fork() only.
   Environment(const Environment &) = default;
@@ -747,6 +774,15 @@ class Environment {
RecordStorageLocation *ThisPointeeLoc,
RecordStorageLocation *LocForRecordReturnVal);
 
+  static ThisExprOverridesMap
+  buildThisExprOverridesMap(const FunctionDecl *FuncDecl,
+RecordStorageLocation *ThisPointeeLoc,
+const PrValueToResultObject &ResultObjectMap);
+
+  static ThisExprOverridesMap
+  buildThisExprOverridesMap(Stmt *S, RecordStorageLocation *ThisPointeeLoc,
+const PrValueToResultObject &ResultObjectMap);
+
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;
 
@@ -793,6 +829,11 @@ class Environment {
   // analysis target is not a method.
   RecordStorageLocation *ThisPointeeLoc = nullptr;
 
+  // Maps from `CXXThisExpr`s to their storage locations, if it should be
+  // different from `ThisPointeeLoc` (for example, CXXThisExpr that are
+  // under a CXXDefaultInitExpr under an InitListExpr).
+  std::shared_ptr ThisExprOverrides;
+
   // Maps from declarations and glvalue expression to storage locations that 
are
   // assigned to them. Unlike the maps in `DataflowAnalysisContext`, these
   // include only storage locations that are in scope for a particular basic
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 256ea18284189..9c6d40d3e1525 

[clang] [Clang] Correctly handle allocations in the condition of a `if constexpr` (PR #146890)

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

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/146890

>From c138801c212f69f4dee83c7516e0e77eb876a9f0 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 3 Jul 2025 14:26:59 +0200
Subject: [PATCH 1/2] [Clang] Correctly handle allocations in the condition of
 a `if constexpr`

Deal with the following scenario

```cpp
struct S {
char* c = new char;
constexpr ~S() {
delete c;
}
};
if constexpr((S{}, true)){};
```

There were two issues
 - We need to produce a full expressions _before_ evaluating the condition
   (otherwise automatic variables are neber destroyed)
 - We need to preserve the evaluation context of the condition while doing
   the semantics analysis for it (lest it is evaluated in a non constant
   evaluated context)

Fixes #120197
Fixes #134820
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Sema/Sema.h   |  6 ++--
 clang/lib/Parse/ParseExprCXX.cpp  | 16 -
 clang/lib/Sema/SemaExpr.cpp   | 11 ---
 clang/lib/Sema/SemaExprCXX.cpp|  9 -
 .../test/SemaCXX/cxx2a-constexpr-dynalloc.cpp | 33 +++
 6 files changed, 58 insertions(+), 18 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3d893e0aa8e2c..9f9fc84b53104 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -896,6 +896,7 @@ Bug Fixes to C++ Support
 - Fixed a crash when constant evaluating some explicit object member 
assignment operators. (#GH142835)
 - Fixed an access checking bug when substituting into concepts (#GH115838)
 - Fix a bug where private access specifier of overloaded function not 
respected. (#GH107629)
+- Correctly handle allocations in the condition of a ``if 
constexpr``.(#GH120197) (#GH134820)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3fe26f950ad51..b281b1cfef96a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7723,12 +7723,12 @@ class Sema final : public SemaBase {
 
   class ConditionResult {
 Decl *ConditionVar;
-FullExprArg Condition;
+ExprResult Condition;
 bool Invalid;
 std::optional KnownValue;
 
 friend class Sema;
-ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
+ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
 bool IsConstexpr)
 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
   if (IsConstexpr && Condition.get()) {
@@ -7739,7 +7739,7 @@ class Sema final : public SemaBase {
   }
 }
 explicit ConditionResult(bool Invalid)
-: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
+: ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
   KnownValue(std::nullopt) {}
 
   public:
diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index 1ea0cf52933f6..9f36c3ade5e74 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -1931,15 +1931,13 @@ Parser::ParseCXXCondition(StmtResult *InitStmt, 
SourceLocation Loc,
   return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
 }
 
-ExprResult Expr = [&] {
-  EnterExpressionEvaluationContext Eval(
-  Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
-  /*LambdaContextDecl=*/nullptr,
-  /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other,
-  /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf);
-  // Parse the expression.
-  return ParseExpression(); // expression
-}();
+EnterExpressionEvaluationContext Eval(
+Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
+/*LambdaContextDecl=*/nullptr,
+/*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other,
+/*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf);
+
+ExprResult Expr = ParseExpression();
 
 if (Expr.isInvalid())
   return Sema::ConditionError();
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 437df742d572b..7c65489cc6234 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -20629,6 +20629,9 @@ Sema::ConditionResult Sema::ActOnCondition(Scope *S, 
SourceLocation Loc,
 
   case ConditionKind::ConstexprIf:
 Cond = CheckBooleanCondition(Loc, SubExpr, true);
+assert(isa(Cond.get()) &&
+   "we should have converted this expression to a FullExpr before "
+   "evaluating it");
 break;
 
   case ConditionKind::Switch:
@@ -20641,12 +20644,10 @@ Sema::ConditionResult Sema::ActOnCondition(Scope *S, 
SourceLocation Loc,
 if (!Cond.get())
   return ConditionError();
   }
-  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
-  FullExprArg FullExpr = MakeFullExpr(C

[clang] [Clang] Correctly handle allocations in the condition of a `if constexpr` (PR #146890)

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


@@ -20629,6 +20629,9 @@ Sema::ConditionResult Sema::ActOnCondition(Scope *S, 
SourceLocation Loc,
 
   case ConditionKind::ConstexprIf:
 Cond = CheckBooleanCondition(Loc, SubExpr, true);
+assert(isa(Cond.get()) &&

cor3ntin wrote:

Actually the assert was incorrect, I removed it

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


[clang] [Clang] Correctly handle allocations in the condition of a `if constexpr` (PR #146890)

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


@@ -1931,15 +1931,13 @@ Parser::ParseCXXCondition(StmtResult *InitStmt, 
SourceLocation Loc,
   return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
 }
 
-ExprResult Expr = [&] {
-  EnterExpressionEvaluationContext Eval(
-  Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
-  /*LambdaContextDecl=*/nullptr,
-  /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other,
-  /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf);
-  // Parse the expression.
-  return ParseExpression(); // expression
-}();
+EnterExpressionEvaluationContext Eval(

cor3ntin wrote:

No (because they are both constant evaluated and completely nested) - I added 
tests

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


[clang] [Clang] Correctly handle allocations in the condition of a `if constexpr` (PR #146890)

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


@@ -20643,10 +20641,12 @@ Sema::ConditionResult Sema::ActOnCondition(Scope *S, 
SourceLocation Loc,
   {SubExpr}, PreferredConditionType(CK));
 if (!Cond.get())
   return ConditionError();
-  }
-  if (!isa(Cond.get()))
+  } else if (Cond.isUsable() && !isa(Cond.get()))
 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
 
+  if (Cond.isInvalid())

erichkeane wrote:

```suggestion
  if (!Cond.isUsable())
```
Unless there is a reason that `ConditionResult` would be ok with a 'null' expr?

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

According to the CI Checks, one of your testcases is failing:
https://github.com/llvm/llvm-project/actions/runs/16055061425?pr=146212
> error: 'expected-warning' diagnostics expected but not seen: 
  File 
/home/gha/actions-runner/_work/llvm-project/llvm-project/clang/test/Analysis/cstring-should-not-invalidate.cpp
 Line 106: TRUE
1 error generated.

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


[clang] [C23] Fix typeof handling in enum declarations (PR #146394)

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

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

>From 94cd71d65fe27cdde0c39416a0e2e709af98ed0c Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Mon, 30 Jun 2025 13:26:57 -0400
Subject: [PATCH 1/7] [C23] Fix typeof handling in enum declarations

We have a parsing helper function which parses either a parenthesized
expression or a parenthesized type name. This is used when parsing a
unary operator such as sizeof, for example.

The problem this solves is when that construct is ambiguous. Consider:

enum E : typeof(int) { F };

After we've parsed the 'typeof', what ParseParenExpression() is
responsible for is '(int) { F }' which looks like a compound literal
expression when it's actually the parens and operand for 'typeof'
followed by the enumerator list for the enumeration declaration. Then
consider:

sizeof (int){ 0 };

After we've parsed 'sizeof', ParseParenExpression is responsible for
parsing something grammatically similar to the problematic case.

The solution is to recognize that the expression form of 'typeof' is
required to have parentheses. So we know the open and close parens that
ParseParenExpression handles must be part of the grammar production for
the operator, not part of the operand expression itself.

Fixes #146351
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Parse/Parser.h |  8 ++-
 clang/lib/Parse/ParseExpr.cpp  | 34 +-
 clang/lib/Parse/Parser.cpp |  3 ++-
 clang/test/Parser/c2x-typeof.c | 10 +
 5 files changed, 45 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45b5f77545361..1b12061dad85b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -304,6 +304,8 @@ C23 Feature Support
   which clarified how Clang is handling underspecified object declarations.
 - Clang now accepts single variadic parameter in type-name. It's a part of
   `WG14 N2975 `_
+- Fixed a bug with handling the type operand form of ``typeof`` when it is used
+  to specify a fixed underlying type for an enumeration. #GH146351
 
 C11 Feature Support
 ^^^
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index a47e23ffbd357..ced9613b9ab9b 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -4184,7 +4184,12 @@ class Parser : public CodeCompletionHandler {
   /// ParseParenExpression - This parses the unit that starts with a '(' token,
   /// based on what is allowed by ExprType.  The actual thing parsed is 
returned
   /// in ExprType. If stopIfCastExpr is true, it will only return the parsed
-  /// type, not the parsed cast-expression.
+  /// type, not the parsed cast-expression. If ParenKnownToBeNonCast is true,
+  /// the initial open paren and its matching close paren are known to be part
+  /// of another grammar production and not part of the operand. e.g., the
+  /// typeof and typeof_unqual operators in C. If it is false, then the 
function
+  /// has to parse the parens to determine whether they're part of a cast or
+  /// compound literal expression rather than a parenthesized type.
   ///
   /// \verbatim
   ///   primary-expression: [C99 6.5.1]
@@ -4210,6 +4215,7 @@ class Parser : public CodeCompletionHandler {
   /// \endverbatim
   ExprResult ParseParenExpression(ParenParseOption &ExprType,
   bool stopIfCastExpr, bool isTypeCast,
+  bool ParenKnownToBeNonCast,
   ParsedType &CastTy,
   SourceLocation &RParenLoc);
 
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 3cf3d4ea7d705..c6731fca7bfa7 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -758,7 +758,8 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 ParsedType CastTy;
 SourceLocation RParenLoc;
 Res = ParseParenExpression(ParenExprType, false /*stopIfCastExr*/,
-   isTypeCast == TypeCastState::IsTypeCast, CastTy,
+   isTypeCast == TypeCastState::IsTypeCast,
+   false /*ParenKnownToBeNonCast*/, CastTy,
RParenLoc);
 
 // FIXME: What should we do if a vector literal is followed by a
@@ -2110,12 +2111,24 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token 
&OpTok,
 // If it starts with a '(', we know that it is either a parenthesized
 // type-name, or it is a unary-expression that starts with a compound
 // literal, or starts with a primary-expression that is a parenthesized
-// expression.
+// expression. Most unary operators have an expression form without parens
+// as part of the grammar for the operator, and a type f

[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

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

https://github.com/efriedma-quic updated 
https://github.com/llvm/llvm-project/pull/144611

>From c28804a471a9fe6be24479ffbfd7d4aa6c774125 Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Tue, 17 Jun 2025 11:48:47 -0700
Subject: [PATCH 1/7] [AArch64] Add option -msve-streaming-vector-bits= .

This is similar to -msve-vector-bits, but for streaming mode: it
constrains the legal values of "vscale", allowing optimizations based on
that constraint.

This also fixes conversions between SVE vectors and fixed-width vectors
in streaming functions with -msve-vector-bits and
-msve-streaming-vector-bits.

This currently doesn't touch the __ARM_FEATURE_SVE_BITS define or the
arm_sve_vector_bits attribute.
---
 clang/include/clang/AST/ASTContext.h  |  9 --
 clang/include/clang/Basic/LangOptions.def |  3 +
 clang/include/clang/Driver/Options.td | 19 
 clang/include/clang/Sema/SemaARM.h|  9 ++
 clang/lib/AST/ASTContext.cpp  | 81 
 clang/lib/Basic/Targets/AArch64.cpp   |  8 +-
 clang/lib/Driver/ToolChains/Clang.cpp | 29 --
 clang/lib/Frontend/CompilerInvocation.cpp |  5 +
 clang/lib/Sema/SemaARM.cpp| 97 +++
 clang/lib/Sema/SemaChecking.cpp   | 16 +--
 clang/lib/Sema/SemaExpr.cpp   |  5 +-
 clang/lib/Sema/SemaOverload.cpp   |  9 +-
 .../arm-sve-vector-bits-vscale-range.c| 58 ---
 clang/test/Driver/aarch64-sve-vector-bits.c   |  4 +
 ...rch64-streaming-sve-vector-conversions.cpp | 53 ++
 15 files changed, 277 insertions(+), 128 deletions(-)
 create mode 100644 
clang/test/SemaCXX/aarch64-streaming-sve-vector-conversions.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3abb49312255a..64d4c5547341e 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2486,15 +2486,6 @@ class ASTContext : public RefCountedBase {
   /// types.
   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
 
-  /// Return true if the given types are an SVE builtin and a VectorType that
-  /// is a fixed-length representation of the SVE builtin for a specific
-  /// vector-length.
-  bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
-  /// Return true if the given vector types are lax-compatible SVE vector 
types,
-  /// false otherwise.
-  bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
   /// Return true if the given types are an RISC-V vector builtin type and a
   /// VectorType that is a fixed-length representation of the RISC-V vector
   /// builtin type for a specific vector-length.
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 789761c1f3647..8054be1bb4e88 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -503,6 +503,9 @@ LANGOPT(OmitVTableRTTI, 1, 0,
 LANGOPT(VScaleMin, 32, 0, "Minimum vscale value")
 LANGOPT(VScaleMax, 32, 0, "Maximum vscale value")
 
+LANGOPT(VScaleStreamingMin, 32, 0, "Minimum streaming vscale value")
+LANGOPT(VScaleStreamingMax, 32, 0, "Maximum streaming vscale value")
+
 ENUM_LANGOPT(ExtendIntArgs, ExtendArgsKind, 1, ExtendArgsKind::ExtendTo32,
  "Controls how scalar integer arguments are extended in calls "
  "to unprototyped and varargs functions")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 152df89118a6a..2e8d5b18483d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5173,6 +5173,14 @@ def msve_vector_bits_EQ : Joined<["-"], 
"msve-vector-bits=">, Group,
   HelpText<"Specify the size in bits of an SVE vector register. Defaults to 
the"
" vector length agnostic value of \"scalable\". (AArch64 only)">;
+def msve_streaming_vector_bits_EQ
+: Joined<["-"], "msve-streaming-vector-bits=">,
+  Group,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<
+  "Specify the size in bits of an SVE vector register in streaming "
+  "mode. Defaults to the vector length agnostic value of "
+  "\"scalable\". (AArch64 only)">;
 } // let Flags = [TargetSpecific]
 
 def mvscale_min_EQ : Joined<["-"], "mvscale-min=">,
@@ -5184,6 +5192,17 @@ def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
   HelpText<"Specify the vscale maximum. Defaults to the"
" vector length agnostic value of \"0\". (AArch64/RISC-V only)">,
   MarshallingInfoInt>;
+def mvscale_streaming_min_EQ
+: Joined<["-"], "mvscale-streaming-min=">,
+  Visibility<[CC1Option, FC1Option]>,
+  HelpText<"Specify the vscale minimum. Defaults to \"1\". (AArch64 
only)">,
+  MarshallingInfoInt>;
+def mvscale_streaming_max_EQ
+: Joined<["-"], "mvscale-streaming-max=">,
+  Visibility<[CC1Option, FC1Option]>,
+  H

[clang] [Sema] Fix lifetime extension for temporaries in range-based for loops in C++23 (PR #145164)

2025-07-03 Thread Marco Vitale via cfe-commits

mrcvtl wrote:

> There are some test failures in the presubmit checks, you probably need to 
> update these tests.

Yes, indeed. For example, in `AST/ast-dump-for-range-lifetime.cpp` we move from:
 `-MaterializeTemporaryExpr {{.*}} 'C':'P2718R0::C' xvalue extended by Var 
{{.*}} '__range1' 'C &&'` 
 to: 
`-MaterializeTemporaryExpr  {{.*}} 'C':'P2718R0::C' xvalue`. 
At a first look it seems like we are losing info in the AST, but also a couple 
of line later we got:
`-MaterializeTemporaryExpr {{.*}} 'const C':'const P2718R0::C' lvalue extended 
by Var {{.*}} '__range1' 'C &&'`
So it might be fine...

In `special/class.temporary/p6.cpp` instead is a bit more weird, because it 
seems we are losing some IR call in case of for-range loops. You can take a 
look in the logs of the failing test.

Given that I don't know enough about it to say if it is okay or not, I wanted 
to double check with you. What do you think? 


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


[clang] [llvm] [clang][python][test] Move python binding tests to lit framework (PR #146844)

2025-07-03 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

No idea why it blew up on that particular s390x buildbot.
@AaronBallman Any ideas?

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


[clang] [clang-format] Propagate `LeadingEmptyLinesAffected` when joining lines (PR #146761)

2025-07-03 Thread Björn Schäpers via cfe-commits

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

Please wait a few days, or until another approval.

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


[clang] [OpenCL] Add decls for cl_intel_subgroup_local_block_io (PR #146656)

2025-07-03 Thread Michal Paszkowski via cfe-commits

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

LGTM!

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


[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

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

https://github.com/efriedma-quic updated 
https://github.com/llvm/llvm-project/pull/144611

>From c28804a471a9fe6be24479ffbfd7d4aa6c774125 Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Tue, 17 Jun 2025 11:48:47 -0700
Subject: [PATCH 1/8] [AArch64] Add option -msve-streaming-vector-bits= .

This is similar to -msve-vector-bits, but for streaming mode: it
constrains the legal values of "vscale", allowing optimizations based on
that constraint.

This also fixes conversions between SVE vectors and fixed-width vectors
in streaming functions with -msve-vector-bits and
-msve-streaming-vector-bits.

This currently doesn't touch the __ARM_FEATURE_SVE_BITS define or the
arm_sve_vector_bits attribute.
---
 clang/include/clang/AST/ASTContext.h  |  9 --
 clang/include/clang/Basic/LangOptions.def |  3 +
 clang/include/clang/Driver/Options.td | 19 
 clang/include/clang/Sema/SemaARM.h|  9 ++
 clang/lib/AST/ASTContext.cpp  | 81 
 clang/lib/Basic/Targets/AArch64.cpp   |  8 +-
 clang/lib/Driver/ToolChains/Clang.cpp | 29 --
 clang/lib/Frontend/CompilerInvocation.cpp |  5 +
 clang/lib/Sema/SemaARM.cpp| 97 +++
 clang/lib/Sema/SemaChecking.cpp   | 16 +--
 clang/lib/Sema/SemaExpr.cpp   |  5 +-
 clang/lib/Sema/SemaOverload.cpp   |  9 +-
 .../arm-sve-vector-bits-vscale-range.c| 58 ---
 clang/test/Driver/aarch64-sve-vector-bits.c   |  4 +
 ...rch64-streaming-sve-vector-conversions.cpp | 53 ++
 15 files changed, 277 insertions(+), 128 deletions(-)
 create mode 100644 
clang/test/SemaCXX/aarch64-streaming-sve-vector-conversions.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3abb49312255a..64d4c5547341e 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2486,15 +2486,6 @@ class ASTContext : public RefCountedBase {
   /// types.
   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
 
-  /// Return true if the given types are an SVE builtin and a VectorType that
-  /// is a fixed-length representation of the SVE builtin for a specific
-  /// vector-length.
-  bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
-  /// Return true if the given vector types are lax-compatible SVE vector 
types,
-  /// false otherwise.
-  bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
   /// Return true if the given types are an RISC-V vector builtin type and a
   /// VectorType that is a fixed-length representation of the RISC-V vector
   /// builtin type for a specific vector-length.
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 789761c1f3647..8054be1bb4e88 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -503,6 +503,9 @@ LANGOPT(OmitVTableRTTI, 1, 0,
 LANGOPT(VScaleMin, 32, 0, "Minimum vscale value")
 LANGOPT(VScaleMax, 32, 0, "Maximum vscale value")
 
+LANGOPT(VScaleStreamingMin, 32, 0, "Minimum streaming vscale value")
+LANGOPT(VScaleStreamingMax, 32, 0, "Maximum streaming vscale value")
+
 ENUM_LANGOPT(ExtendIntArgs, ExtendArgsKind, 1, ExtendArgsKind::ExtendTo32,
  "Controls how scalar integer arguments are extended in calls "
  "to unprototyped and varargs functions")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 152df89118a6a..2e8d5b18483d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5173,6 +5173,14 @@ def msve_vector_bits_EQ : Joined<["-"], 
"msve-vector-bits=">, Group,
   HelpText<"Specify the size in bits of an SVE vector register. Defaults to 
the"
" vector length agnostic value of \"scalable\". (AArch64 only)">;
+def msve_streaming_vector_bits_EQ
+: Joined<["-"], "msve-streaming-vector-bits=">,
+  Group,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<
+  "Specify the size in bits of an SVE vector register in streaming "
+  "mode. Defaults to the vector length agnostic value of "
+  "\"scalable\". (AArch64 only)">;
 } // let Flags = [TargetSpecific]
 
 def mvscale_min_EQ : Joined<["-"], "mvscale-min=">,
@@ -5184,6 +5192,17 @@ def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
   HelpText<"Specify the vscale maximum. Defaults to the"
" vector length agnostic value of \"0\". (AArch64/RISC-V only)">,
   MarshallingInfoInt>;
+def mvscale_streaming_min_EQ
+: Joined<["-"], "mvscale-streaming-min=">,
+  Visibility<[CC1Option, FC1Option]>,
+  HelpText<"Specify the vscale minimum. Defaults to \"1\". (AArch64 
only)">,
+  MarshallingInfoInt>;
+def mvscale_streaming_max_EQ
+: Joined<["-"], "mvscale-streaming-max=">,
+  Visibility<[CC1Option, FC1Option]>,
+  H

[clang] [AArch64] Add option -msve-streaming-vector-bits= . (PR #144611)

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

https://github.com/efriedma-quic updated 
https://github.com/llvm/llvm-project/pull/144611

>From c28804a471a9fe6be24479ffbfd7d4aa6c774125 Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Tue, 17 Jun 2025 11:48:47 -0700
Subject: [PATCH 1/9] [AArch64] Add option -msve-streaming-vector-bits= .

This is similar to -msve-vector-bits, but for streaming mode: it
constrains the legal values of "vscale", allowing optimizations based on
that constraint.

This also fixes conversions between SVE vectors and fixed-width vectors
in streaming functions with -msve-vector-bits and
-msve-streaming-vector-bits.

This currently doesn't touch the __ARM_FEATURE_SVE_BITS define or the
arm_sve_vector_bits attribute.
---
 clang/include/clang/AST/ASTContext.h  |  9 --
 clang/include/clang/Basic/LangOptions.def |  3 +
 clang/include/clang/Driver/Options.td | 19 
 clang/include/clang/Sema/SemaARM.h|  9 ++
 clang/lib/AST/ASTContext.cpp  | 81 
 clang/lib/Basic/Targets/AArch64.cpp   |  8 +-
 clang/lib/Driver/ToolChains/Clang.cpp | 29 --
 clang/lib/Frontend/CompilerInvocation.cpp |  5 +
 clang/lib/Sema/SemaARM.cpp| 97 +++
 clang/lib/Sema/SemaChecking.cpp   | 16 +--
 clang/lib/Sema/SemaExpr.cpp   |  5 +-
 clang/lib/Sema/SemaOverload.cpp   |  9 +-
 .../arm-sve-vector-bits-vscale-range.c| 58 ---
 clang/test/Driver/aarch64-sve-vector-bits.c   |  4 +
 ...rch64-streaming-sve-vector-conversions.cpp | 53 ++
 15 files changed, 277 insertions(+), 128 deletions(-)
 create mode 100644 
clang/test/SemaCXX/aarch64-streaming-sve-vector-conversions.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3abb49312255a..64d4c5547341e 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2486,15 +2486,6 @@ class ASTContext : public RefCountedBase {
   /// types.
   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
 
-  /// Return true if the given types are an SVE builtin and a VectorType that
-  /// is a fixed-length representation of the SVE builtin for a specific
-  /// vector-length.
-  bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
-  /// Return true if the given vector types are lax-compatible SVE vector 
types,
-  /// false otherwise.
-  bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
-
   /// Return true if the given types are an RISC-V vector builtin type and a
   /// VectorType that is a fixed-length representation of the RISC-V vector
   /// builtin type for a specific vector-length.
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 789761c1f3647..8054be1bb4e88 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -503,6 +503,9 @@ LANGOPT(OmitVTableRTTI, 1, 0,
 LANGOPT(VScaleMin, 32, 0, "Minimum vscale value")
 LANGOPT(VScaleMax, 32, 0, "Maximum vscale value")
 
+LANGOPT(VScaleStreamingMin, 32, 0, "Minimum streaming vscale value")
+LANGOPT(VScaleStreamingMax, 32, 0, "Maximum streaming vscale value")
+
 ENUM_LANGOPT(ExtendIntArgs, ExtendArgsKind, 1, ExtendArgsKind::ExtendTo32,
  "Controls how scalar integer arguments are extended in calls "
  "to unprototyped and varargs functions")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 152df89118a6a..2e8d5b18483d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5173,6 +5173,14 @@ def msve_vector_bits_EQ : Joined<["-"], 
"msve-vector-bits=">, Group,
   HelpText<"Specify the size in bits of an SVE vector register. Defaults to 
the"
" vector length agnostic value of \"scalable\". (AArch64 only)">;
+def msve_streaming_vector_bits_EQ
+: Joined<["-"], "msve-streaming-vector-bits=">,
+  Group,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<
+  "Specify the size in bits of an SVE vector register in streaming "
+  "mode. Defaults to the vector length agnostic value of "
+  "\"scalable\". (AArch64 only)">;
 } // let Flags = [TargetSpecific]
 
 def mvscale_min_EQ : Joined<["-"], "mvscale-min=">,
@@ -5184,6 +5192,17 @@ def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
   HelpText<"Specify the vscale maximum. Defaults to the"
" vector length agnostic value of \"0\". (AArch64/RISC-V only)">,
   MarshallingInfoInt>;
+def mvscale_streaming_min_EQ
+: Joined<["-"], "mvscale-streaming-min=">,
+  Visibility<[CC1Option, FC1Option]>,
+  HelpText<"Specify the vscale minimum. Defaults to \"1\". (AArch64 
only)">,
+  MarshallingInfoInt>;
+def mvscale_streaming_max_EQ
+: Joined<["-"], "mvscale-streaming-max=">,
+  Visibility<[CC1Option, FC1Option]>,
+  H

[clang] [llvm] AMDGPU: Implement tensor load and store instructions for gfx1250 (PR #146636)

2025-07-03 Thread Shilei Tian via cfe-commits

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


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


[clang] [clang][test] Avoid some C++14 warnings in discrim-union.cpp (PR #146829)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Before this patch, we emitted a bunch of irrelevant (to this test) warnings:
```
  ../clang/test/SemaCXX/discrim-union.cpp:49:24: warning: 'constexpr' 
non-static member function will not be implicitly 'const' in C++14; add 'const' 
to avoid a change in behavior [-Wconstexpr-not-const]
   49 | constexpr const T &get(select<0>) { return val; }
  |^
  |   const
../clang/test/SemaCXX/discrim-union.cpp:50:104: warning: 'constexpr' non-static 
member function will not be implicitly 'const' in C++14; add 'const' to avoid a 
change in behavior [-Wconstexpr-not-const]
   50 | template constexpr const 
decltype(static_cast(rest).get(select{})) 
get(select) {
  | 
   ^
  | 
  const
../clang/test/SemaCXX/discrim-union.cpp:82:22: warning: 'constexpr' non-static 
member function will not be implicitly 'const' in C++14; add 'const' to avoid a 
change in behavior [-Wconstexpr-not-const]
   82 |   constexpr unsigned index() noexcept { return elem; }
  |  ^
  |  const
../clang/test/SemaCXX/discrim-union.cpp:88:33: warning: 'constexpr' non-static 
member function will not be implicitly 'const' in C++14; add 'const' to avoid a 
change in behavior [-Wconstexpr-not-const]
   88 |   constexpr const_get_result get() {
  | ^
  |   const
../clang/test/SemaCXX/discrim-union.cpp:96:22: warning: 'constexpr' non-static 
member function will not be implicitly 'const' in C++14; add 'const' to avoid a 
change in behavior [-Wconstexpr-not-const]
   96 |   constexpr const U &get() {
  |  ^
  |const
5 warnings generated.
```

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


1 Files Affected:

- (modified) clang/test/SemaCXX/discrim-union.cpp (+5-5) 


``diff
diff --git a/clang/test/SemaCXX/discrim-union.cpp 
b/clang/test/SemaCXX/discrim-union.cpp
index 15c9a225ed9a9..9877b70205104 100644
--- a/clang/test/SemaCXX/discrim-union.cpp
+++ b/clang/test/SemaCXX/discrim-union.cpp
@@ -46,8 +46,8 @@ namespace detail {
 val.~T();
 }
 
-constexpr const T &get(select<0>) { return val; }
-template constexpr const decltype(static_cast(rest).get(select{})) get(select) {
+constexpr const T &get(select<0>) const { return val; }
+template constexpr const decltype(static_cast(rest).get(select{})) get(select) const {
   return rest.get(select{});
 }
   };
@@ -79,13 +79,13 @@ class either {
   // FIXME: declare a destructor iff any element has a nontrivial destructor
   //~either() { impl.destroy(elem); }
 
-  constexpr unsigned index() noexcept { return elem; }
+  constexpr unsigned index() const noexcept { return elem; }
 
   template using const_get_result =
 decltype(static_cast(impl).get(detail::select{}));
 
   template
-  constexpr const_get_result get() {
+  constexpr const_get_result get() const {
 // Can't just use throw here, since that makes the conditional a prvalue,
 // which means we return a reference to a temporary.
 return (elem != N ? throw_>("bad_either_get")
@@ -93,7 +93,7 @@ class either {
   }
 
   template
-  constexpr const U &get() {
+  constexpr const U &get() const {
 return get())>();
   }
 };

``




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


[clang] [clang-scan-deps] Fix "unterminated conditional directive" bug (PR #146645)

2025-07-03 Thread Ziqing Luo via cfe-commits

ziqingluo-90 wrote:

> The logic added in #143950 also handles line splices with 0 trailing 
> whitespace characters, so this code is now redundant. (When removing it, the 
> test run fine too.)
> 
> Should removing this code be a separate PR?

Done

https://github.com/llvm/llvm-project/pull/146645
___
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 new check: `modernize-use-concise-preprocessor-directives` (PR #146830)

2025-07-03 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clang-tidy

Author: Victor Chernyakin (localspook)


Changes

Closes #132561.

This is a check that rewrites `#if`s and `#elif`s like so:

```cpp
#if  defined(MEOW) // -> #ifdef  MEOW
#if !defined(MEOW) // -> #ifndef MEOW
```

And, since C23 and C++23:

```cpp
#elif  defined(MEOW) // -> #elifdef  MEOW
#elif !defined(MEOW) // -> #elifndef MEOW
```

We can bikeshed the name and category. For example, `modernize` isn't *ideal*; 
rewriting `#if defined(A)` as `#ifdef A` isn't
really "modernizing", because `#ifdef` has always existed, but rewriting `#elif 
defined(A)` as `#elifdef A`
certainly is.

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


8 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/CMakeLists.txt (+1) 
- (modified) clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
(+3) 
- (added) 
clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
 (+105) 
- (added) 
clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.h 
(+37) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) 
- (added) 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-concise-preprocessor-directives.rst
 (+28) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-concise-preprocessor-directives.cpp
 (+134) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 619a27b2f9bb6..22d5214b61441 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -30,6 +30,7 @@ add_clang_library(clangTidyModernizeModule STATIC
   UnaryStaticAssertCheck.cpp
   UseAutoCheck.cpp
   UseBoolLiteralsCheck.cpp
+  UseConcisePreprocessorDirectivesCheck.cpp
   UseConstraintsCheck.cpp
   UseDefaultMemberInitCheck.cpp
   UseDesignatedInitializersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index fdf38bc4b6308..28c5467f7b3e0 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -31,6 +31,7 @@
 #include "UnaryStaticAssertCheck.h"
 #include "UseAutoCheck.h"
 #include "UseBoolLiteralsCheck.h"
+#include "UseConcisePreprocessorDirectivesCheck.h"
 #include "UseConstraintsCheck.h"
 #include "UseDefaultMemberInitCheck.h"
 #include "UseDesignatedInitializersCheck.h"
@@ -76,6 +77,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "modernize-min-max-use-initializer-list");
 CheckFactories.registerCheck("modernize-pass-by-value");
+CheckFactories.registerCheck(
+"modernize-use-concise-preprocessor-directives");
 CheckFactories.registerCheck(
 "modernize-use-designated-initializers");
 CheckFactories.registerCheck(
diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
 
b/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
new file mode 100644
index 0..56ed1b3cc879d
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
@@ -0,0 +1,105 @@
+//===--- UseConcisePreprocessorDirectivesCheck.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 "UseConcisePreprocessorDirectivesCheck.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+
+namespace clang::tidy::modernize {
+
+namespace {
+
+class IfPreprocessorCallbacks final : public PPCallbacks {
+public:
+  IfPreprocessorCallbacks(ClangTidyCheck &Check, Preprocessor &PP)
+  : Check(Check), PP(PP) {}
+
+  void If(SourceLocation Loc, SourceRange ConditionRange,
+  ConditionValueKind) override {
+impl(Loc, ConditionRange, {"ifdef", "ifndef"});
+  }
+
+  void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind,
+SourceLocation) override {
+if (PP.getLangOpts().C23 || PP.getLangOpts().CPlusPlus23) {
+  impl(Loc, ConditionRange, {"elifdef", "elifndef"});
+}
+  }
+
+private:
+  void impl(SourceLocation DirectiveLoc, SourceRange ConditionRange,
+const llvm::StringLiteral (&Replacements)[2]) {
+StringRef Condition =
+Lexer::getSourceText(CharSourceRange::getTokenRange(ConditionRange),
+ PP.getSourceManager(), PP.getLangOpts(

[clang-tools-extra] [clang-tidy] Add new check: `modernize-use-concise-preprocessor-directives` (PR #146830)

2025-07-03 Thread Victor Chernyakin via cfe-commits

https://github.com/localspook created 
https://github.com/llvm/llvm-project/pull/146830

Closes #132561.

This is a check that rewrites `#if`s and `#elif`s like so:

```cpp
#if  defined(MEOW) // -> #ifdef  MEOW
#if !defined(MEOW) // -> #ifndef MEOW
```

And, since C23 and C++23:

```cpp
#elif  defined(MEOW) // -> #elifdef  MEOW
#elif !defined(MEOW) // -> #elifndef MEOW
```

We can bikeshed the name and category. For example, `modernize` isn't *ideal*; 
rewriting `#if defined(A)` as `#ifdef A` isn't
really "modernizing", because `#ifdef` has always existed, but rewriting `#elif 
defined(A)` as `#elifdef A`
certainly is.

>From 9eb58438d2b4061ad7a6bdbd1db82a5fd4043948 Mon Sep 17 00:00:00 2001
From: Victor Chernyakin 
Date: Thu, 3 Jul 2025 00:19:52 -0700
Subject: [PATCH] [clang-tidy] Add new check:
 `modernize-use-concise-preprocessor-directives`

Rewrites preprocessor conditions like
`#if defined(MEOW)` as `#ifdef MEOW` and
`#elif !defined(MEOW)` as `#elifndef MEOW`.

Closes #132561.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../UseConcisePreprocessorDirectivesCheck.cpp | 105 ++
 .../UseConcisePreprocessorDirectivesCheck.h   |  37 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../use-concise-preprocessor-directives.rst   |  28 
 .../use-concise-preprocessor-directives.cpp   | 134 ++
 8 files changed, 315 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-concise-preprocessor-directives.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-concise-preprocessor-directives.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 619a27b2f9bb6..22d5214b61441 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -30,6 +30,7 @@ add_clang_library(clangTidyModernizeModule STATIC
   UnaryStaticAssertCheck.cpp
   UseAutoCheck.cpp
   UseBoolLiteralsCheck.cpp
+  UseConcisePreprocessorDirectivesCheck.cpp
   UseConstraintsCheck.cpp
   UseDefaultMemberInitCheck.cpp
   UseDesignatedInitializersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index fdf38bc4b6308..28c5467f7b3e0 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -31,6 +31,7 @@
 #include "UnaryStaticAssertCheck.h"
 #include "UseAutoCheck.h"
 #include "UseBoolLiteralsCheck.h"
+#include "UseConcisePreprocessorDirectivesCheck.h"
 #include "UseConstraintsCheck.h"
 #include "UseDefaultMemberInitCheck.h"
 #include "UseDesignatedInitializersCheck.h"
@@ -76,6 +77,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "modernize-min-max-use-initializer-list");
 CheckFactories.registerCheck("modernize-pass-by-value");
+CheckFactories.registerCheck(
+"modernize-use-concise-preprocessor-directives");
 CheckFactories.registerCheck(
 "modernize-use-designated-initializers");
 CheckFactories.registerCheck(
diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
 
b/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
new file mode 100644
index 0..56ed1b3cc879d
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/modernize/UseConcisePreprocessorDirectivesCheck.cpp
@@ -0,0 +1,105 @@
+//===--- UseConcisePreprocessorDirectivesCheck.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 "UseConcisePreprocessorDirectivesCheck.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+
+namespace clang::tidy::modernize {
+
+namespace {
+
+class IfPreprocessorCallbacks final : public PPCallbacks {
+public:
+  IfPreprocessorCallbacks(ClangTidyCheck &Check, Preprocessor &PP)
+  : Check(Check), PP(PP) {}
+
+  void If(SourceLocation Loc, SourceRange ConditionRange,
+  ConditionValueKind) override {
+impl(Loc, ConditionRange, {"ifdef", "ifndef"});
+  }
+
+  void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind,
+SourceLocation) override {
+ 

[clang-tools-extra] [clang-tidy] Add new check: `modernize-use-concise-preprocessor-directives` (PR #146830)

2025-07-03 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write 
permissions for the repository. In which case you can instead tag reviewers by 
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a 
review by "ping"ing the PR by adding a comment “Ping”. The common courtesy 
"ping" rate is once a week. Please remember that you are asking for valuable 
time from other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [Sema] Fix lifetime extension for temporaries in range-based for loops in C++23 (PR #145164)

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


@@ -1304,6 +1304,13 @@ checkExprLifetimeImpl(Sema &SemaRef, const 
InitializedEntity *InitEntity,
   if (LK == LK_FullExpression)
 return;
 
+  if (LK == LK_Extended && SemaRef.getLangOpts().CPlusPlus23) {

hokein wrote:

Is the `LK == LK_Extended` check necessary here? I think we can simply bail out 
in this case, regardless of the LK value.

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


[clang] [llvm] Add __attribute__((visibility("default"))) attribute to certain symbols to stop them being hidden when linking clangInterpreter library to other libraries during Emscripten build (PR #1

2025-07-03 Thread Nikita Popov via cfe-commits

nikic wrote:

> Also, this is separate to the issue to making a Windows Shared library issue 
> here #109483 (this purely based on your comment that ' the annotation effort 
> hasn't progressed to them yet')

That same work also enables building libLLVM/libclang with 
`-fvisibilty=hidden`, which it sounds like what you are actually doing, and 
which is currently not a supported configuration. (At least going by your 
comment that `-fvisibility=default` works, which should already be the implicit 
default.)


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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread via cfe-commits

Hanwen-ece wrote:

Dear Shunsuke,

Thank you for your thoughtful response and for sharing your approach to complex 
division optimization. We encountered similar performance issues while 
analyzing SPEC2017 workloads, particularly in the handling of complex 
arithmetic, and were motivated to propose a solution grounded in the current 
design conventions of LLVM Flang.

While our implementation aligns closely with existing patterns in the Flang 
complex runtime, we’ve found that your formulation provides a more principled 
and generalizable abstraction. It is both elegant and insightful, and indeed 
offers a more flexible foundation for future extensions in this area. In our 
benchmarks, we observed that the performance gains achieved by your approach 
are comparable to those of our implementation.

We have carefully studied your proposal and found it to be genuinely inspiring. 
Your contribution exemplifies the clarity and depth characteristic of the LLVM 
community — something we hold in high regard.

We look forward to learning more from your work and to further engaging with 
the community on this topic. Enjoy the rest of your day!

Warmest regards,

Hanwen (https://github.com/OpenXiangShan)

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


[clang] [Sema] Fix lifetime extension for temporaries in range-based for loops in C++23 (PR #145164)

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

https://github.com/hokein commented:

There are some test failures in the presubmit checks, you probably need to 
update these tests.

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


[libclc] [libclc] Declare workitem built-ins in clc, move ptx-nvidiacl workitem built-ins into clc (PR #144333)

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

frasercrmck wrote:

> > I am seeing unresolved CLC functions in `nvptx--.bc` and `nvptx64--.bc`. I 
> > think it's because we're now building things like `get_num_groups` for 
> > `nvptx`/`nvptx64`, whereas previously they were not being built for those 
> > targets. We're also not building `__clc_get_num_groups` because we're 
> > (correctly) not including `ptx-nvidiacl` sources.
> 
> thanks @frasercrmck for the careful review. `nvptx--.bc` and `nvptx64--.bc` 
> issue is fixed in 
> [b1397a4](https://github.com/llvm/llvm-project/commit/b1397a4c0ba63a2fd2392aa064bfa351ce014a7d)
> 
> Please let me know if I should revert following style change and follow 
> existing tyle.
> 
> 1. add #ifndef __CLC_OPENCL_WORKITEM_* guard in opencl header file and 
> include needed #include . E.g. 
> libclc/opencl/include/clc/opencl/workitem/get_global_id.h.
> 
> 2. include only needed headers in OpenCL lib files, e.g. in 
> libclc/opencl/lib/ptx-nvidiacl/workitem/get_local_linear_id.cl
> 
> 
> ```
> #include 
> #include 
> 
> _CLC_OVERLOAD _CLC_DEF size_t get_local_linear_id() {
>   return __clc_get_local_linear_id();
> }
> ```

I think that's a good approach, thanks. We generally include far too much stuff 
in the OpenCL layer.

One comment is that I had initially intended for `clc/internal` to only be used 
by the CLC builtins. I realise it's already being used by some `fma.cl`s but we 
might want to nip it in the bud. Perhaps we need a stripped down OpenCL header, 
like `clc/opencl/opencl-base.h` which includes just the types and macro defs?

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


[clang] [clang-tools-extra] [clang][CodeComplete] skip explicit obj param in SignatureHelp (PR #146649)

2025-07-03 Thread Mythreya Kuricheti via cfe-commits

https://github.com/MythreyaK updated 
https://github.com/llvm/llvm-project/pull/146649

>From 7f8581f01c3c25363b77100635c6df7223badba3 Mon Sep 17 00:00:00 2001
From: Mythreya Kuricheti 
Date: Wed, 2 Jul 2025 01:26:25 -0700
Subject: [PATCH 1/2] [clang][CodeComplete] skip explicit obj param in
 SignatureHelp

---
 .../clangd/unittests/CodeCompleteTests.cpp| 28 +++
 clang/lib/Sema/SemaCodeComplete.cpp   |  8 ++
 .../skip-explicit-object-parameter.cpp| 24 
 3 files changed, 54 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index b7c64c7a06745..b18d712ee9aef 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -3266,6 +3266,34 @@ TEST(SignatureHelpTest, VariadicType) {
   }
 }
 
+TEST(SignatureHelpTest, SkipExplicitObjectParameter) {
+  Annotations Code(R"cpp(
+struct A {
+  void foo(this auto&& self, int arg); 
+};
+int main() {
+  A a {};
+  a.foo(^);
+}
+  )cpp");
+
+  auto TU = TestTU::withCode(Code.code());
+  TU.ExtraArgs = {"-std=c++23"};
+
+  MockFS FS;
+  auto Inputs = TU.inputs(FS);
+
+  auto Preamble = TU.preamble();
+  ASSERT_TRUE(Preamble);
+
+  const auto Result = signatureHelp(testPath(TU.Filename), Code.point(),
+*Preamble, Inputs, MarkupKind::PlainText);
+
+  EXPECT_EQ(1, Result.signatures.size());
+
+  EXPECT_THAT(Result.signatures[0], AllOf(sig("foo([[int arg]]) -> void")));
+}
+
 TEST(CompletionTest, IncludedCompletionKinds) {
   Annotations Test(R"cpp(#include "^)cpp");
   auto TU = TestTU::withCode(Test.code());
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index b5d4a94da83df..0077cf05bd5b0 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -4034,6 +4034,14 @@ static void AddOverloadParameterChunks(
   return;
 }
 
+// C++23 introduces an explicit object parameter, a.k.a. "deducing this"
+// Skip it for autocomplete and treat the next parameter as the first
+// parameter
+if (Function && FirstParameter &&
+Function->getParamDecl(P)->isExplicitObjectParameter()) {
+  continue;
+}
+
 if (FirstParameter)
   FirstParameter = false;
 else
diff --git a/clang/test/CodeCompletion/skip-explicit-object-parameter.cpp 
b/clang/test/CodeCompletion/skip-explicit-object-parameter.cpp
index 55c16bb126fee..0eb71dce95849 100644
--- a/clang/test/CodeCompletion/skip-explicit-object-parameter.cpp
+++ b/clang/test/CodeCompletion/skip-explicit-object-parameter.cpp
@@ -6,9 +6,21 @@ int main() {
   A a {};
   a.
 }
-// RUN: %clang_cc1 -cc1 -fsyntax-only -code-completion-at=%s:%(line-2):5 
-std=c++23 %s | FileCheck %s
-// CHECK: COMPLETION: A : A::
-// CHECK-NEXT: COMPLETION: foo : [#void#]foo(<#int arg#>)
-// CHECK-NEXT: COMPLETION: operator= : [#A &#]operator=(<#const A &#>)
-// CHECK-NEXT: COMPLETION: operator= : [#A &#]operator=(<#A &&#>)
-// CHECK-NEXT: COMPLETION: ~A : [#void#]~A()
+// RUN: %clang_cc1 -cc1 -fsyntax-only -code-completion-at=%s:%(line-2):5 
-std=c++23 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: COMPLETION: A : A::
+// CHECK-NEXT-CC1: COMPLETION: foo : [#void#]foo(<#int arg#>)
+// CHECK-NEXT-CC1: COMPLETION: operator= : [#A &#]operator=(<#const A &#>)
+// CHECK-NEXT-CC1: COMPLETION: operator= : [#A &#]operator=(<#A &&#>)
+// CHECK-NEXT-CC1: COMPLETION: ~A : [#void#]~A()
+
+struct B {
+  template 
+  void foo(this T&& self, int arg);
+};
+
+int main2() {
+  B b {};
+  b.foo();
+}
+// RUN: %clang_cc1 -cc1 -fsyntax-only -code-completion-at=%s:%(line-2):9 
-std=c++23 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OVERLOAD: [#void#]foo(int arg)

>From a7fae2277ea9267f65ecdfaf05c4b79bcc7a44c4 Mon Sep 17 00:00:00 2001
From: Mythreya Kuricheti 
Date: Thu, 3 Jul 2025 02:27:05 -0700
Subject: [PATCH 2/2] Update tests from code review

---
 .../clangd/unittests/CodeCompleteTests.cpp| 52 ++-
 .../skip-explicit-object-parameter.cpp| 26 --
 2 files changed, 61 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index b18d712ee9aef..5912937e2c80f 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -3270,10 +3270,13 @@ TEST(SignatureHelpTest, SkipExplicitObjectParameter) {
   Annotations Code(R"cpp(
 struct A {
   void foo(this auto&& self, int arg); 
+  void bar(this A self, int arg);
 };
 int main() {
   A a {};
-  a.foo(^);
+  a.foo($c1^);
+  (&A::bar)($c2^);
+  // TODO: (&A::foo)(^c3)
 }
   )cpp");
 
@@ -3286,12 +3289,22 @@ TEST(SignatureHelpTest, SkipExplicitObjectPara

[clang] [llvm] Add __attribute__((visibility("default"))) attribute to certain symbols to stop them being hidden when linking clangInterpreter library to other libraries during Emscripten build (PR #1

2025-07-03 Thread via cfe-commits

mcbarton wrote:

> > Also, this is separate to the issue to making a Windows Shared library 
> > issue here #109483 (this purely based on your comment that ' the annotation 
> > effort hasn't progressed to them yet')
> 
> That same work also enables building libLLVM/libclang with 
> `-fvisibilty=hidden`, which it sounds like what you are actually doing, and 
> which is currently not a supported configuration. (At least going by your 
> comment that `-fvisibility=default` works, which should already be the 
> implicit default.)

It is not the default for Web Assembly as far as I understand based on 
https://github.com/WebAssembly/tool-conventions/issues/176 (see line 'A long 
while ago we choose to make -fvisibility=hidden the default for the WebAssembly 
backend in llvm')  and 
https://github.com/emscripten-core/emscripten/blob/b0c461c10482e12f88e192e04b3640acb1577f64/emcc.py#L203
 (see 'even though the upstream backend defaults visibility=hidden'). @sbc100 
will be able to say for certain.

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits


@@ -1023,12 +1023,12 @@ defm offload_uniform_block : 
BoolFOption<"offload-uniform-block",
   BothFlags<[], [ClangOption], " that kernels are launched with uniform block 
sizes (default true for CUDA/HIP and false otherwise)">>;
 
 def fcomplex_arithmetic_EQ : Joined<["-"], "fcomplex-arithmetic=">, 
Group,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
   Values<"full,improved,promoted,basic">, NormalizedValuesScope<"LangOptions">,
   NormalizedValues<["CX_Full", "CX_Improved", "CX_Promoted", "CX_Basic"]>;

kiranchandramohan wrote:

Is help text available for these options? If not could you add?

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,35 @@
+! Test lowering of complex division according to options
+
+! REQUIRES: flang-supports-f128-math
+! RUN: bbc -complex-range=full -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,FULL
+! RUN: bbc -complex-range=improved -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,IMPRVD
+! RUN: bbc -complex-range=basic -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,BASIC
+! RUN: %flang_fc1 -complex-range=full -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,FULL
+! RUN: %flang_fc1 -complex-range=improved -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,IMPRVD
+! RUN: %flang_fc1 -complex-range=basic -emit-hlfir %s -o - | FileCheck %s 
--check-prefixes=CHECK,BASIC
+
+
+! CHECK-LABEL: @_QPdiv_test_quad
+! CHECK-SAME: %[[REF_0:.*]]: !fir.ref> {{.*}}, %[[REF_1:.*]]: 
!fir.ref> {{.*}}, %[[REF_2:.*]]: !fir.ref> {{.*}})
+! CHECK: %[[VAL_3:.*]] = fir.dummy_scope : !fir.dscope
+! CHECK: %[[VAL_4:.*]]:2 = hlfir.declare %[[REF_0]] dummy_scope %[[VAL_3]] 
{uniq_name = "_QFdiv_test_quadEa"} : (!fir.ref>, !fir.dscope) -> 
(!fir.ref>, !fir.ref>)
+! CHECK: %[[VAL_5:.*]]:2 = hlfir.declare %[[REF_1]] dummy_scope %[[VAL_3]] 
{uniq_name = "_QFdiv_test_quadEb"} : (!fir.ref>, !fir.dscope) -> 
(!fir.ref>, !fir.ref>)
+! CHECK: %[[VAL_6:.*]]:2 = hlfir.declare %[[REF_2]] dummy_scope %[[VAL_3]] 
{uniq_name = "_QFdiv_test_quadEc"} : (!fir.ref>, !fir.dscope) -> 
(!fir.ref>, !fir.ref>)
+! CHECK: %[[VAL_7:.*]] = fir.load %[[VAL_5]]#0 : !fir.ref>
+! CHECK: %[[VAL_8:.*]] = fir.load %[[VAL_6]]#0 : !fir.ref>
+
+! FULL: %[[VAL_9:.*]] = fir.extract_value %[[VAL_7]], [0 : index] : 
(complex) -> f128
+! FULL: %[[VAL_10:.*]] = fir.extract_value %[[VAL_7]], [1 : index] : 
(complex) -> f128
+! FULL: %[[VAL_11:.*]] = fir.extract_value %[[VAL_8]], [0 : index] : 
(complex) -> f128
+! FULL: %[[VAL_12:.*]] = fir.extract_value %[[VAL_8]], [1 : index] : 
(complex) -> f128
+! FULL: %[[VAL_RET:.*]] = fir.call @__divtc3(%[[VAL_9]], %[[VAL_10]], 
%[[VAL_11]], %[[VAL_12]]) fastmath : (f128, f128, f128, f128) -> 
complex
+
+! IMPRVD: %[[VAL_RET:.*]] = complex.div %[[VAL_7]], %[[VAL_8]] 
fastmath : complex
+! BASIC: %[[VAL_RET:.*]] = complex.div %[[VAL_7]], %[[VAL_8]] 
fastmath : complex
+
+! CHECK: hlfir.assign %[[VAL_RET]] to %[[VAL_4]]#0 : complex, 
!fir.ref>
+! CHECK: return
+subroutine div_test_quad(a,b,c)
+  complex(kind=16) :: a, b, c
+  a = b / c
+end subroutine div_test_quad

kiranchandramohan wrote:

Nit: end of line/newline

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits


@@ -595,6 +595,30 @@ void Flang::addOffloadOptions(Compilation &C, const 
InputInfoList &Inputs,
   addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
 }
 
+static std::string ComplexRangeKindToStr(LangOptions::ComplexRangeKind Range) {
+  switch (Range) {
+  case LangOptions::ComplexRangeKind::CX_Full:
+return "full";
+break;
+  case LangOptions::ComplexRangeKind::CX_Improved:
+return "improved";
+break;
+  case LangOptions::ComplexRangeKind::CX_Basic:
+return "basic";
+break;
+  default:
+return "";
+  }
+}
+
+static std::string
+RenderComplexRangeOption(LangOptions::ComplexRangeKind Range) {
+  std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
+  if (!ComplexRangeStr.empty())
+return "-complex-range=" + ComplexRangeStr;
+  return ComplexRangeStr;
+}
+

kiranchandramohan wrote:

Can we share this code with similar code in Clang.cpp by moving to 
CommonArgs.cpp or a suitable place?

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits

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

LG. Thanks for all the work and experiments here.

Couple of nit/trivial comments.

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


[clang] [flang] [flang] Add -fcomplex-arithmetic= option and select complex division algorithm (PR #146641)

2025-07-03 Thread Kiran Chandramohan via cfe-commits


@@ -1066,8 +1066,16 @@ struct BinaryOp(loc, lhs, rhs)};

kiranchandramohan wrote:

Nit: braces

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


[clang] [llvm] [win][aarch64] Always reserve frame pointers for Arm64 Windows (PR #146582)

2025-07-03 Thread David Truby via cfe-commits


@@ -518,6 +518,27 @@ bool AArch64FrameLowering::hasFPImpl(const MachineFunction 
&MF) const {
   return false;
 }
 
+/// Should the Frame Pointer be reserved for the current function?
+bool AArch64FrameLowering::isFPReserved(const MachineFunction &MF) const {
+  const TargetMachine &TM = MF.getTarget();
+  const Triple &TT = TM.getTargetTriple();
+
+  // These OSes require the frame chain is valid, even if the current frame 
does
+  // not use a frame pointer.
+  if (TT.isOSDarwin() || TT.isOSWindows())

DavidTruby wrote:

I think just removing the clang change will fix the fact that this fails for 
flang, so it might be worth removing for that reason

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


[clang] [llvm] [AMDGPU][clang][CodeGen][opt] Add late-resolved feature identifying predicates (PR #134016)

2025-07-03 Thread Alex Voicu via cfe-commits

AlexVlx wrote:

> @efriedma-quic was kind enough to have a call where we discussed this a bit 
> more. I'll update tomorrow with a potential way forward, for the group's 
> consideration.

Following up, here's a possible approach to making progress, broken down in 
phases, (@efriedma-quic can correct me if I am misrepresenting any of these):

1. Have what is proposed here as an initial step, with the addition that we 
issue warnings on unguarded uses of builtins / ASM (similar to what 
`__builtin_available` / `@available` do), and we clean-up non-extern functions 
that become unreachable as a consequence of predicate expansion (i.e. `foo` can 
only be called from within this module, and it was only being called from a 
predicate guarded block, which was removed);
2. Add attribute based checking for predicate guarded areas:
 - Functions can be annotated either with the existing `target` attribute 
or with a new `target_can_invoke` (name up for bike-shedding) attribute;
 - Within a predicate guarded scope, if we encounter contradictions, e.g. 
we call a `target("gfx9000")` function, or a 
`target_can_invoke(builtin_only_on_gfx9000)`, within a 
`__builtin_amdgcn_processor_is("gfx8999")`, that is an error
 - This should reward users that go through the effort of annotating their 
functions, making it much harder to write bugs
 - I'm not entirely sure how to do this well yet (nested guarded regions, 
where to track the currently active guard etc.), and it probably needs a bit 
more design, hence why it's a different phase
 - It is a pre-requisite for any attempt at making these general, rather 
than target specific
3. In relation with generalisation, if we go in that direction (i.e. other 
targets are interested / we think there's merit into hoisting these into 
generic Clang builtins), we will have to look at whether or not we want a 
different IR representation (possibly / probably along the lines of what has 
been discussed here), for cases where a target must run some potentially 
disruptive optimisations before and cannot just do the expansion right after 
Clang.

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Tom Honermann via cfe-commits

https://github.com/tahonermann requested changes to this pull request.


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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Tom Honermann via cfe-commits


@@ -1,19 +1,19 @@
 // RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-device 
-disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s 
'-D$ADDRSPACE='
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-__attribute__((sycl_kernel)) void kernel(Func F){
+[[clang::sycl_entry_point]] void kernel(Func F){
   F();
 }
 
 template
-__attribute__((sycl_kernel)) void kernel2(Func F){
+[[clang::sycl_entry_point]] void kernel2(Func F){

tahonermann wrote:

```suggestion
[[clang::sycl_kernel_entry_point(KN)]] void kernel2(Func F){
```

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Tom Honermann via cfe-commits


@@ -1,19 +1,19 @@
 // RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-device 
-disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s 
'-D$ADDRSPACE='
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-__attribute__((sycl_kernel)) void kernel(Func F){
+[[clang::sycl_entry_point]] void kernel(Func F){
   F();
 }
 
 template
-__attribute__((sycl_kernel)) void kernel2(Func F){
+[[clang::sycl_entry_point]] void kernel2(Func F){
   F(1);
 }
 
 template
-__attribute__((sycl_kernel)) void kernel3(Func F){
+[[clang::sycl_entry_point]] void kernel3(Func F){

tahonermann wrote:

```suggestion
[[clang::sycl_kernel_entry_point(KN)]] void kernel3(Func F){
```

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Tom Honermann via cfe-commits


@@ -1,19 +1,19 @@
 // RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '

tahonermann wrote:

The redundant `-fsycl-is-device` option can be removed.
```suggestion
// RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -emit-llvm %s -o - 
| FileCheck %s '-D$ADDRSPACE=addrspace(1) '
```

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Tom Honermann via cfe-commits


@@ -1,19 +1,19 @@
 // RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-device 
-disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s 
'-D$ADDRSPACE='
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-__attribute__((sycl_kernel)) void kernel(Func F){
+[[clang::sycl_entry_point]] void kernel(Func F){

tahonermann wrote:

```suggestion
[[clang::sycl_kernel_entry_point(KN)]] void kernel(Func F){
```

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Mariya Podchishchaeva via cfe-commits

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon updated 
https://github.com/llvm/llvm-project/pull/146854

>From 9a640eefb5d27a65f236b5f7df1398bdf1bcc017 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Thu, 3 Jul 2025 03:46:41 -0700
Subject: [PATCH 1/2] [NFC][clang] Fix
 CodeGenSYCL::unique_stable_name_windows_diff test

The test checks x86 target in fsycl-is-device mode. x86 is not a valid
offloading target and IMO test meant to check fsycl-is-host mode to make
sure host invocations of __builtin_sycl_unique_stable_name work
correctly.
---
 .../test/CodeGenSYCL/unique_stable_name_windows_diff.cpp  | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp 
b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
index 7dd08a0c89255..70a09e4afd275 100644
--- a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
+++ b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
@@ -1,19 +1,19 @@
 // RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-device 
-disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s 
'-D$ADDRSPACE='
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-__attribute__((sycl_kernel)) void kernel(Func F){
+[[clang::sycl_entry_point]] void kernel(Func F){
   F();
 }
 
 template
-__attribute__((sycl_kernel)) void kernel2(Func F){
+[[clang::sycl_entry_point]] void kernel2(Func F){
   F(1);
 }
 
 template
-__attribute__((sycl_kernel)) void kernel3(Func F){
+[[clang::sycl_entry_point]] void kernel3(Func F){
   F(1.1);
 }
 

>From 98182d4a04250ed10c15d0e36e68417ec9b00187 Mon Sep 17 00:00:00 2001
From: Mariya Podchishchaeva 
Date: Thu, 3 Jul 2025 15:07:56 +0200
Subject: [PATCH 2/2] Apply suggestions from code review

Co-authored-by: Tom Honermann 
---
 .../test/CodeGenSYCL/unique_stable_name_windows_diff.cpp  | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp 
b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
index 70a09e4afd275..c844673db0d0e 100644
--- a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
+++ b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
@@ -1,19 +1,19 @@
-// RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
+// RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -emit-llvm %s -o - 
| FileCheck %s '-D$ADDRSPACE=addrspace(1) '
 // RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-[[clang::sycl_entry_point]] void kernel(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel(Func F){
   F();
 }
 
 template
-[[clang::sycl_entry_point]] void kernel2(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel2(Func F){
   F(1);
 }
 
 template
-[[clang::sycl_entry_point]] void kernel3(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel3(Func F){
   F(1.1);
 }
 

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


[clang] [NFC][clang] Fix CodeGenSYCL::unique_stable_name_windows_diff test (PR #146854)

2025-07-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mariya Podchishchaeva (Fznamznon)


Changes

The test checks x86 target in fsycl-is-device mode. x86 is not a valid 
offloading target and IMO test meant to check fsycl-is-host mode to make sure 
host invocations of __builtin_sycl_unique_stable_name work correctly. This also 
switches the test to use sycl_entry_point attribute instead of sycl_kernel 
because the intention for the future SYCL changes is to use sycl_entry_point 
and eventually remove sycl_kernel attribute when sycl_entry_point supports 
enough SYCL cases.

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


1 Files Affected:

- (modified) clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp (+5-5) 


``diff
diff --git a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp 
b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
index 7dd08a0c89255..c844673db0d0e 100644
--- a/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
+++ b/clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp
@@ -1,19 +1,19 @@
-// RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -fsycl-is-device 
-emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE=addrspace(1) '
-// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-device 
-disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s 
'-D$ADDRSPACE='
+// RUN: %clang_cc1 -triple spir64-unknown-unknown-sycldevice -aux-triple 
x86_64-pc-windows-msvc -fsycl-is-device -disable-llvm-passes -emit-llvm %s -o - 
| FileCheck %s '-D$ADDRSPACE=addrspace(1) '
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsycl-is-host 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s '-D$ADDRSPACE='
 
 
 template
-__attribute__((sycl_kernel)) void kernel(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel(Func F){
   F();
 }
 
 template
-__attribute__((sycl_kernel)) void kernel2(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel2(Func F){
   F(1);
 }
 
 template
-__attribute__((sycl_kernel)) void kernel3(Func F){
+[[clang::sycl_kernel_entry_point(KN)]] void kernel3(Func F){
   F(1.1);
 }
 

``




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


[clang] [Clang] Fix evaluation context of lambdas appearing in discarded statements (PR #146857)

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

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/146857

>From 4ee72df191e9792be38195b00b0f6422de3a767a Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 3 Jul 2025 13:00:46 +0200
Subject: [PATCH 1/2] [Clang] Fix evaluation context of lambdas appearing in
 discarded statements

Fixes 2 bugs reported in #146063

 - The body of a lambda appearing in a discarded statement was sometimes
   considered discarded itself
 - A lambda conversion operator that was not odr-used was sometimes not
   defined even if it was needed

Fixes #146063
---
 clang/lib/Sema/SemaExpr.cpp   |  5 +
 clang/lib/Sema/TreeTransform.h| 10 +++--
 .../CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp  | 22 +++
 3 files changed, 30 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 437df742d572b..a23497afddefe 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18252,6 +18252,11 @@ static bool 
isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
 
   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
 return true;
+
+  // Lambda conversion operators are never user provided
+  if (CXXConversionDecl *Conv = dyn_cast(Func))
+return isLambdaConversionOperator(Conv);
+
   auto *CCD = dyn_cast(Func);
   return CCD && CCD->getInheritedConstructor();
 }
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0d58587cb8a99..2f57672375a01 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -15723,13 +15723,9 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
 
   // FIXME: Sema's lambda-building mechanism expects us to push an expression
   // evaluation context even if we're not transforming the function body.
-  getSema().PushExpressionEvaluationContext(
-  E->getCallOperator()->isConsteval() ?
-  Sema::ExpressionEvaluationContext::ImmediateFunctionContext :
-  Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
-  getSema().currentEvaluationContext().InImmediateEscalatingFunctionContext =
-  getSema().getLangOpts().CPlusPlus20 &&
-  E->getCallOperator()->isImmediateEscalating();
+  getSema().PushExpressionEvaluationContextForFunction(
+  Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+  E->getCallOperator());
 
   Sema::CodeSynthesisContext C;
   C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
diff --git a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp 
b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
index ac21e36daf870..abb42447d3e0b 100644
--- a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
+++ b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
@@ -218,4 +218,26 @@ void regression() {
 
 }
 
+namespace GH146063 {
+template 
+struct A {
+  static_assert([]() constexpr { return true; }());
+};
+
+void f1() {
+  if constexpr (false) {
+A a;
+  }
+}
+
+void f2() {
+  if constexpr (false) {
+static_assert([]{});
+// expected-warning@-1 {{address of lambda function pointer conversion 
operator will always evaluate to 'true'}}
+  }
+}
+
+}
+
+
 #endif

>From 34b4b5e0f22b99dd04e5007ff4ea401908f3ac38 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 3 Jul 2025 15:11:19 +0200
Subject: [PATCH 2/2] Update clang/lib/Sema/SemaExpr.cpp

Co-authored-by: Timm Baeder 
---
 clang/lib/Sema/SemaExpr.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index a23497afddefe..f2954cb287c8d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18253,7 +18253,7 @@ static bool 
isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
 return true;
 
-  // Lambda conversion operators are never user provided
+  // Lambda conversion operators are never user provided.
   if (CXXConversionDecl *Conv = dyn_cast(Func))
 return isLambdaConversionOperator(Conv);
 

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits

https://github.com/flovent updated 
https://github.com/llvm/llvm-project/pull/146212

>From 9da53c788fc01cd3fc2dd4c178b836035b5d380b Mon Sep 17 00:00:00 2001
From: flovent 
Date: Sat, 28 Jun 2025 20:58:43 +0800
Subject: [PATCH 1/5] [analyzer] Avoid unnecessary super region invalidation in
 `CStringChecker`

---
 .../Checkers/CStringChecker.cpp   |  77 -
 .../cstring-should-not-invalidate.cpp | 107 ++
 2 files changed, 178 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/Analysis/cstring-should-not-invalidate.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 4d12fdcec1f1a..433fd2ce5f292 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -272,7 +272,8 @@ class CStringChecker : public Checker< eval::Call,
   static ProgramStateRef
   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
 const Expr *BufE, ConstCFGElementRef Elem,
-SVal BufV, SVal SizeV, QualType SizeTy);
+SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound = true);
 
   /// Operation never overflows, do not invalidate the super region.
   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
@@ -1211,14 +1212,17 @@ bool CStringChecker::isFirstBufInBound(CheckerContext 
&C, ProgramStateRef State,
 
 ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
 CheckerContext &C, ProgramStateRef S, const Expr *BufE,
-ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) {
+ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound) {
   auto InvalidationTraitOperations =
-  [&C, S, BufTy = BufE->getType(), BufV, SizeV,
-   SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) 
{
+  [&C, S, BufTy = BufE->getType(), BufV, SizeV, SizeTy,
+   CouldAccessOutOfBound](RegionAndSymbolInvalidationTraits &ITraits,
+  const MemRegion *R) {
 // If destination buffer is a field region and access is in bound, do
 // not invalidate its super region.
 if (MemRegion::FieldRegionKind == R->getKind() &&
-isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
+(!CouldAccessOutOfBound ||
+ isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy))) {
   ITraits.setTrait(
   R,
   
RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
@@ -2223,6 +2227,67 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, 
const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
+  SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
+
+  // Protect against misdeclared strncpy().
+  lenVal =
+  svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
+
+  std::optional lenValNL = lenVal.getAs();
+
+  auto CouldAccessOutOfBoundForSVal = [&](NonLoc Val) -> bool {
+return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
+  Dst.Expression->getType(), Val,
+  C.getASTContext().getSizeType());
+  };
+
+  if (strLengthNL) {
+CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*strLengthNL);
+  }
+
+  if (CouldAccessOutOfBound && lenValNL) {
+switch (appendK) {
+case ConcatFnKind::none:
+case ConcatFnKind::strcat: {
+  CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*lenValNL);
+  break;
+}
+case ConcatFnKind::strlcat: {
+  if (!dstStrLengthNL)
+break;
+
+  SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
+   *dstStrLengthNL, sizeTy);
+  if (!isa(freeSpace))
+break;
+
+  freeSpace =
+  svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
+svalBuilder.makeIntVal(1, sizeTy), sizeTy);
+  std::optional fre

[clang] [C23] Fix typeof handling in enum declarations (PR #146394)

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

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

>From 94cd71d65fe27cdde0c39416a0e2e709af98ed0c Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Mon, 30 Jun 2025 13:26:57 -0400
Subject: [PATCH 1/6] [C23] Fix typeof handling in enum declarations

We have a parsing helper function which parses either a parenthesized
expression or a parenthesized type name. This is used when parsing a
unary operator such as sizeof, for example.

The problem this solves is when that construct is ambiguous. Consider:

enum E : typeof(int) { F };

After we've parsed the 'typeof', what ParseParenExpression() is
responsible for is '(int) { F }' which looks like a compound literal
expression when it's actually the parens and operand for 'typeof'
followed by the enumerator list for the enumeration declaration. Then
consider:

sizeof (int){ 0 };

After we've parsed 'sizeof', ParseParenExpression is responsible for
parsing something grammatically similar to the problematic case.

The solution is to recognize that the expression form of 'typeof' is
required to have parentheses. So we know the open and close parens that
ParseParenExpression handles must be part of the grammar production for
the operator, not part of the operand expression itself.

Fixes #146351
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Parse/Parser.h |  8 ++-
 clang/lib/Parse/ParseExpr.cpp  | 34 +-
 clang/lib/Parse/Parser.cpp |  3 ++-
 clang/test/Parser/c2x-typeof.c | 10 +
 5 files changed, 45 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45b5f77545361..1b12061dad85b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -304,6 +304,8 @@ C23 Feature Support
   which clarified how Clang is handling underspecified object declarations.
 - Clang now accepts single variadic parameter in type-name. It's a part of
   `WG14 N2975 `_
+- Fixed a bug with handling the type operand form of ``typeof`` when it is used
+  to specify a fixed underlying type for an enumeration. #GH146351
 
 C11 Feature Support
 ^^^
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index a47e23ffbd357..ced9613b9ab9b 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -4184,7 +4184,12 @@ class Parser : public CodeCompletionHandler {
   /// ParseParenExpression - This parses the unit that starts with a '(' token,
   /// based on what is allowed by ExprType.  The actual thing parsed is 
returned
   /// in ExprType. If stopIfCastExpr is true, it will only return the parsed
-  /// type, not the parsed cast-expression.
+  /// type, not the parsed cast-expression. If ParenKnownToBeNonCast is true,
+  /// the initial open paren and its matching close paren are known to be part
+  /// of another grammar production and not part of the operand. e.g., the
+  /// typeof and typeof_unqual operators in C. If it is false, then the 
function
+  /// has to parse the parens to determine whether they're part of a cast or
+  /// compound literal expression rather than a parenthesized type.
   ///
   /// \verbatim
   ///   primary-expression: [C99 6.5.1]
@@ -4210,6 +4215,7 @@ class Parser : public CodeCompletionHandler {
   /// \endverbatim
   ExprResult ParseParenExpression(ParenParseOption &ExprType,
   bool stopIfCastExpr, bool isTypeCast,
+  bool ParenKnownToBeNonCast,
   ParsedType &CastTy,
   SourceLocation &RParenLoc);
 
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 3cf3d4ea7d705..c6731fca7bfa7 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -758,7 +758,8 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 ParsedType CastTy;
 SourceLocation RParenLoc;
 Res = ParseParenExpression(ParenExprType, false /*stopIfCastExr*/,
-   isTypeCast == TypeCastState::IsTypeCast, CastTy,
+   isTypeCast == TypeCastState::IsTypeCast,
+   false /*ParenKnownToBeNonCast*/, CastTy,
RParenLoc);
 
 // FIXME: What should we do if a vector literal is followed by a
@@ -2110,12 +2111,24 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token 
&OpTok,
 // If it starts with a '(', we know that it is either a parenthesized
 // type-name, or it is a unary-expression that starts with a compound
 // literal, or starts with a primary-expression that is a parenthesized
-// expression.
+// expression. Most unary operators have an expression form without parens
+// as part of the grammar for the operator, and a type f

[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits


@@ -2223,16 +2223,81 @@ void CStringChecker::evalStrcpyCommon(CheckerContext 
&C, const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};

flovent wrote:

Done.

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


[clang] [clang] SourceManager: Cache offsets for LastFileIDLookup to speed up getFileID (PR #146782)

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


@@ -849,7 +850,12 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
   FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
-  NumLinearScans += NumProbes+1;
+  LastLookupStartOffset = LocalSLocEntryTable[GreaterIndex].getOffset();
+  LastLookupEndOffset =
+  GreaterIndex + 1 >= LocalSLocEntryTable.size()

erichkeane wrote:

Got it, thanks!

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


[clang] [clang] SourceManager: Cache offsets for LastFileIDLookup to speed up getFileID (PR #146782)

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


@@ -832,13 +835,11 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
   unsigned LessIndex = 0;
   // upper bound of the search range.
   unsigned GreaterIndex = LocalSLocEntryTable.size();
-  if (LastFileIDLookup.ID >= 0) {
-// Use the LastFileIDLookup to prune the search space.
-if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
-  LessIndex = LastFileIDLookup.ID;
-else
-  GreaterIndex = LastFileIDLookup.ID;
-  }
+  // Use the LastFileIDLookup to prune the search space.
+  if (LastLookupStartOffset < SLocOffset)
+LessIndex = LastFileIDLookup.ID;

erichkeane wrote:

Oh!  Does this mean that the old test here (`LastFileIDLookup.ID >= 0`) was a 
dead branch?  Or actually, the alternative?  Always executed? 

Thats why i asked...

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


[clang] [analyzer] Add support for consteval in ConditionBRVisitor::VisitTerminator (PR #146859)

2025-07-03 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: %clang_analyze_cc1 -std=c++23 -analyzer-checker=core -verify %s
+
+void test_consteval() {
+  if consteval {
+int *ptr = nullptr;
+*ptr = 42; // expected-warning{{Dereference of null pointer (loaded from 
variable 'ptr')}}
+  }
+}

steakhal wrote:

```suggestion
}

```

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits

flovent wrote:

> Also please follow the [Coding 
> Standard](https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly)
>  and use `UpperCamelCase` variables for variables (including ones that store 
> lambda functions), while `lowerCamelCase` is for methods. Of course, it is 
> also right to follow the "local customs" of older code fragments, but I'd 
> suggest gradually transitioning to the global standard by following the 
> coding standard for the freshly added variables and perhaps transitioning the 
> variables which are mostly used in the code that you edit.

I totally agree using new standard in new code, i think i didn't notice that 
because i  basiclly copy the orginal code to here and clangd doesn't give 
warning about clang-tidy's `readability-identifier-naming` check (just found 
out it's disabled in clang folder), will check that manually next time.

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


[clang] [clang][analyzer] Fix the false positive ArgInitializedness warning on unnamed bit-field (PR #145066)

2025-07-03 Thread Balazs Benics via cfe-commits


@@ -2122,8 +2122,21 @@ SVal 
RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
   if (const std::optional &V = B.getDirectBinding(R))
 return *V;
 
-  // If the containing record was initialized, try to get its constant value.
+  // UnnamedBitField is always Undefined unless using memory operation such
+  // as 'memset'.
+  // For example, for code
+  //typedef struct {
+  //  int i  :2;
+  //  int:30;  // unnamed bit-field
+  //} A;
+  //A a = {1};
+  // The bits of the unnamed bit-field in local variable a can be anything.
   const FieldDecl *FD = R->getDecl();
+  if (FD->isUnnamedBitField()) {
+  return UndefinedVal();
+  }
+
+  // If the containing record was initialized, try to get its constant value.

steakhal wrote:

Would any of the tests break if you would remove that part?

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


[clang] [clang][analyzer] Fix the false positive ArgInitializedness warning on unnamed bit-field (PR #145066)

2025-07-03 Thread via cfe-commits


@@ -2122,8 +2122,21 @@ SVal 
RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
   if (const std::optional &V = B.getDirectBinding(R))
 return *V;
 
-  // If the containing record was initialized, try to get its constant value.
+  // UnnamedBitField is always Undefined unless using memory operation such
+  // as 'memset'.
+  // For example, for code
+  //typedef struct {
+  //  int i  :2;
+  //  int:30;  // unnamed bit-field
+  //} A;
+  //A a = {1};
+  // The bits of the unnamed bit-field in local variable a can be anything.
   const FieldDecl *FD = R->getDecl();
+  if (FD->isUnnamedBitField()) {
+  return UndefinedVal();
+  }
+
+  // If the containing record was initialized, try to get its constant value.

Tedlion wrote:

@steakhal  I have tested the check-clang-analysis, no more testcases break

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


[clang] [llvm] [analyzer] Correct Z3 test cases, fix exposed crashes (PR #146597)

2025-07-03 Thread via cfe-commits

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


[clang] [CIR] Bit manipulation builtin functions (PR #146529)

2025-07-03 Thread Sirui Mu via cfe-commits

https://github.com/Lancern updated 
https://github.com/llvm/llvm-project/pull/146529

>From c00abbed243cf4048317031c3abde185a050a2d4 Mon Sep 17 00:00:00 2001
From: Sirui Mu 
Date: Tue, 1 Jul 2025 21:26:23 +0800
Subject: [PATCH] [CIR] Bit manipulation builtin functions

This patch adds CIR support for the following families of bit manipulation
builtin functions:

- `__builtin_clrsb`, represented by the `cir.bit.clrsb` operation
- `__builtin_ctz`, represented by the `cir.bit.clz` operation
- `__builtin_clz`, represented by the `cir.bit.ctz` operation
- `__builtin_parity`, represented by the `cir.bit.parity` operation
- `__builtin_popcount`, represented by the `cir.bit.popcnt` operation

The `__builtin_ffs` builtin function is not included in this patch because the
current CIRGen would emit it as a library call to `@ffs`.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  | 140 
 clang/include/clang/CIR/MissingFeatures.h |   1 +
 clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp   |  64 
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp |  80 +
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  50 +++
 clang/test/CIR/CodeGen/builtin_bit.cpp| 327 ++
 6 files changed, 662 insertions(+)
 create mode 100644 clang/test/CIR/CodeGen/builtin_bit.cpp

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 187e04bc25f24..de0eddba91e33 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -2535,6 +2535,146 @@ def ComplexImagOp : CIR_Op<"complex.imag", [Pure]> {
   let hasFolder = 1;
 }
 
+//===--===//
+// Bit Manipulation Operations
+//===--===//
+
+class CIR_BitOpBase
+  : CIR_Op {
+  let arguments = (ins operandTy:$input);
+  let results = (outs operandTy:$result);
+
+  let assemblyFormat = [{
+`(` $input `:` type($input) `)` `:` type($result) attr-dict
+  }];
+}
+
+class CIR_BitZeroCountOpBase
+  : CIR_BitOpBase {
+  let arguments = (ins operandTy:$input, UnitAttr:$poison_zero);
+
+  let assemblyFormat = [{
+`(` $input `:` type($input) `)` (`poison_zero` $poison_zero^)?
+`:` type($result) attr-dict
+  }];
+}
+
+def BitClrsbOp : CIR_BitOpBase<"bit.clrsb", CIR_SIntOfWidths<[32, 64]>> {
+  let summary = "Get the number of leading redundant sign bits in the input";
+  let description = [{
+Compute the number of leading redundant sign bits in the input integer.
+
+The input integer must be a signed integer. The most significant bit of the
+input integer is the sign bit. The `cir.bit.clrsb` operation returns the
+number of consecutive bits following the sign bit that are identical to the
+sign bit.
+
+The bit width of the input integer must be either 32 or 64.
+
+Examples:
+
+```mlir
+// %0 = 0b1101_1110_1010_1101_1011_1110_1110_
+%0 = cir.const #cir.int<3735928559> : !s32i
+// %1 will be 1 because there is 1 bit following the most significant bit
+// that is identical to it.
+%1 = cir.bit.clrsb(%0 : !s32i) : !s32i
+
+// %2 = 1, 0b_______0001
+%2 = cir.const #cir.int<1> : !s32i
+// %3 will be 30 because there are 30 consecutive bits following the sign
+// bit that are identical to the sign bit.
+%3 = cir.bit.clrsb(%2 : !s32i) : !s32i
+```
+  }];
+}
+
+def BitClzOp : CIR_BitZeroCountOpBase<"bit.clz",
+  CIR_UIntOfWidths<[16, 32, 64]>> {
+  let summary = "Get the number of leading 0-bits in the input";
+  let description = [{
+Compute the number of leading 0-bits in the input.
+
+The input integer must be an unsigned integer. The `cir.bit.clz` operation
+returns the number of consecutive 0-bits at the most significant bit
+position in the input.
+
+If the `poison_zero` attribute is present, this operation will have
+undefined behavior if the input value is 0.
+
+Example:
+
+```mlir
+// %0 = 0b_______1000
+%0 = cir.const #cir.int<8> : !u32i
+// %1 will be 28
+%1 = cir.bit.clz(%0 : !u32i) poison_zero : !u32i
+```
+  }];
+}
+
+def BitCtzOp : CIR_BitZeroCountOpBase<"bit.ctz",
+  CIR_UIntOfWidths<[16, 32, 64]>> {
+  let summary = "Get the number of trailing 0-bits in the input";
+  let description = [{
+Compute the number of trailing 0-bits in the input.
+
+The input integer must be an unsigned integer. The `cir.bit.ctz` operation
+counts the number of consecutive 0-bits starting from the least significant
+bit.
+
+If the `poison_zero` attribute is present, this operation will have
+undefined behavior if the input value is 0.
+
+Example:
+
+```mlir
+// %0 = 0b1000
+%0 = cir.const #cir.int<8> : !u32i
+// %1 will be 3
+%1 = cir.bit.ctz(%

[clang] [Clang][AArch64] Remove redundant tune args to the backend (PR #146896)

2025-07-03 Thread Tomer Shafir via cfe-commits

https://github.com/tomershafir created 
https://github.com/llvm/llvm-project/pull/146896

This change removes unnecessary tune args to the AArch64 backend. The AArch64 
backend automatically handles `tune-cpu` and adds the necessary features based 
on the models from TableGen.

>From 47da7044807f139512c04b3f3ad3ef6634d49a44 Mon Sep 17 00:00:00 2001
From: tomershafir 
Date: Thu, 3 Jul 2025 16:53:26 +0300
Subject: [PATCH] [Clang][AArch64] Remove redundant tune args to the backend

This change removes unnecessary tune args to the AArch64 backend. The AArch64 
backend automatically handles `tune-cpu` and adds the necessary features based 
on the models from TableGen.
---
 clang/lib/Driver/ToolChains/Arch/AArch64.cpp | 11 ---
 .../test/Preprocessor/aarch64-target-features.c  | 16 
 2 files changed, 8 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 343a18b9ca2ea..4f45c369c83db 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -163,17 +163,6 @@ getAArch64MicroArchFeaturesFromMtune(const Driver &D, 
StringRef Mtune,
   if (!DecodeAArch64Mcpu(D, MtuneLowerCase, Tune, Extensions))
 return false;
 
-  // Handle CPU name is 'native'.
-  if (MtuneLowerCase == "native")
-MtuneLowerCase = std::string(llvm::sys::getHostCPUName());
-
-  // 'cyclone' and later have zero-cycle register moves and zeroing.
-  if (MtuneLowerCase == "cyclone" ||
-  StringRef(MtuneLowerCase).starts_with("apple")) {
-Features.push_back("+zcm-gpr64");
-Features.push_back("+zcz");
-  }
-
   return true;
 }
 
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 6700153b79795..f45f3e74d690f 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -316,7 +316,7 @@
 
 // == Check whether -mtune accepts mixed-case features.
 // RUN: %clang -target aarch64 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MTUNE-CYCLONE %s
-// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" "+v8a"
+// CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a"
 
 // RUN: %clang -target aarch64 -mcpu=apple-a7 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
 // RUN: %clang -target aarch64 -mcpu=apple-a8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-APPLE-A7 %s
@@ -342,12 +342,12 @@
 // RUN: %clang -target aarch64 -mcpu=thunderx2t99 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-THUNDERX2T99 %s
 // RUN: %clang -target aarch64 -mcpu=a64fx -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-A64FX %s
 // RUN: %clang -target aarch64 -mcpu=carmel -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-MCPU-CARMEL %s
-// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8a" "-target-feature" "+aes" "-target-feature" "+crc" "-target-feature" 
"+fp-armv8" "-target-feature" "+lor" "-target-feature" "+neon" 
"-target-feature" "+pan" "-target-feature" "+perfmon" "-target-feature" "+rdm" 
"-target-feature" "+sha2" "-target-feature" "+vh"
-// CHECK-MCPU-APPLE-A11: "-cc1"{{.*}} "-triple" 
"aarch64{{.*}}"{{.*}}"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" 
"-target-feature" "+v8.2a" "-target-feature" "+aes" "-target-feature" "+crc" 
"-target-feature" "+fp-armv8" "-target-feature" "+fullfp16" "-target-feature" 
"+lse" "-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" 
"+ras" "-target-feature" "+rdm" "-target-feature" "+sha2"
-// CHECK-MCPU-APPLE-A12: "-cc1"{{.*}} "-triple" "aarch64"{{.*}} 
"-target-feature" "+zcm-gpr64" "-target-feature" "+zcz" "-target-feature" 
"+v8.3a" "-target-feature" "+aes" "-target-feature" "+complxnum" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+fullfp16" "-target-feature" "+jsconv" "-target-feature" "+lse" 
"-target-feature" "+neon" "-target-feature" "+pauth" "-target-feature" 
"+perfmon" "-target-feature" "+ras" "-target-feature" "+rcpc" "-target-feature" 
"+rdm" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2"
+// CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" 
"-target-feature" "+v8a" "-target-feature" "+aes" "-targ

[clang] [C23] Fix typeof handling in enum declarations (PR #146394)

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

AaronBallman wrote:

> > > > ```c++
> > > > typeof(int){} x; // Probably parsed as typeof(int{})
> > > > ```
> > > 
> > > 
> > > Actually, I’m not sure what we think this is supposed to be; I haven’t 
> > > checked.
> > 
> > 
> > Actually, that’s just a compound literal; I forgot we supported those in 
> > C++.
> 
> It's a realy funky compound literal though, so worth explaining for 
> others:
> 
> That's `(int){}` as a compound literal expression, which is the expression 
> operand to an unparenthesized `typeof` operator, which yields the type `int` 
> for the declaration of `x`.

Nope, I'm wrong.

`typeof` requires the parens. That should be ill-formed.

I'll investigate.

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits


@@ -0,0 +1,106 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s

flovent wrote:

Added `alpha.unix.cstring` and `unix.cstring` to testcase, `alpha.unix.cstring` 
makes a difference, in line 66, if `size` is equal to `dest`'s size, 
`alpha.unix.cstring.OutOfBounds` will be reported, that's before we check 
`size` or `srcLen`.

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


[clang] [analyzer] Avoid unnecessary super region invalidation in `CStringChecker` (PR #146212)

2025-07-03 Thread via cfe-commits

https://github.com/flovent updated 
https://github.com/llvm/llvm-project/pull/146212

>From 9da53c788fc01cd3fc2dd4c178b836035b5d380b Mon Sep 17 00:00:00 2001
From: flovent 
Date: Sat, 28 Jun 2025 20:58:43 +0800
Subject: [PATCH 1/9] [analyzer] Avoid unnecessary super region invalidation in
 `CStringChecker`

---
 .../Checkers/CStringChecker.cpp   |  77 -
 .../cstring-should-not-invalidate.cpp | 107 ++
 2 files changed, 178 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/Analysis/cstring-should-not-invalidate.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 4d12fdcec1f1a..433fd2ce5f292 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -272,7 +272,8 @@ class CStringChecker : public Checker< eval::Call,
   static ProgramStateRef
   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
 const Expr *BufE, ConstCFGElementRef Elem,
-SVal BufV, SVal SizeV, QualType SizeTy);
+SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound = true);
 
   /// Operation never overflows, do not invalidate the super region.
   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
@@ -1211,14 +1212,17 @@ bool CStringChecker::isFirstBufInBound(CheckerContext 
&C, ProgramStateRef State,
 
 ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
 CheckerContext &C, ProgramStateRef S, const Expr *BufE,
-ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) {
+ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy,
+bool CouldAccessOutOfBound) {
   auto InvalidationTraitOperations =
-  [&C, S, BufTy = BufE->getType(), BufV, SizeV,
-   SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) 
{
+  [&C, S, BufTy = BufE->getType(), BufV, SizeV, SizeTy,
+   CouldAccessOutOfBound](RegionAndSymbolInvalidationTraits &ITraits,
+  const MemRegion *R) {
 // If destination buffer is a field region and access is in bound, do
 // not invalidate its super region.
 if (MemRegion::FieldRegionKind == R->getKind() &&
-isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
+(!CouldAccessOutOfBound ||
+ isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy))) {
   ITraits.setTrait(
   R,
   
RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
@@ -2223,6 +2227,67 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, 
const CallEvent &Call,
 Result = lastElement;
 }
 
+// For bounded method, amountCopied take the minimum of two values,
+// for ConcatFnKind::strlcat:
+// amountCopied = min (size - dstLen - 1 , srcLen)
+// for others:
+// amountCopied = min (srcLen, size)
+// So even if we don't know about amountCopied, as long as one of them will
+// not cause an out-of-bound access, the whole function's operation will 
not
+// too, that will avoid invalidating the superRegion of data member in that
+// situation.
+bool CouldAccessOutOfBound = true;
+if (IsBounded && amountCopied.isUnknown()) {
+  // Get the max number of characters to copy.
+  SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
+  SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
+
+  // Protect against misdeclared strncpy().
+  lenVal =
+  svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
+
+  std::optional lenValNL = lenVal.getAs();
+
+  auto CouldAccessOutOfBoundForSVal = [&](NonLoc Val) -> bool {
+return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
+  Dst.Expression->getType(), Val,
+  C.getASTContext().getSizeType());
+  };
+
+  if (strLengthNL) {
+CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*strLengthNL);
+  }
+
+  if (CouldAccessOutOfBound && lenValNL) {
+switch (appendK) {
+case ConcatFnKind::none:
+case ConcatFnKind::strcat: {
+  CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(*lenValNL);
+  break;
+}
+case ConcatFnKind::strlcat: {
+  if (!dstStrLengthNL)
+break;
+
+  SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
+   *dstStrLengthNL, sizeTy);
+  if (!isa(freeSpace))
+break;
+
+  freeSpace =
+  svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
+svalBuilder.makeIntVal(1, sizeTy), sizeTy);
+  std::optional fre

[clang] [clang][analyzer] Fix the false positive ArgInitializedness warning on unnamed bit-field (PR #145066)

2025-07-03 Thread via cfe-commits


@@ -2122,8 +2122,21 @@ SVal 
RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
   if (const std::optional &V = B.getDirectBinding(R))
 return *V;
 
-  // If the containing record was initialized, try to get its constant value.
+  // UnnamedBitField is always Undefined unless using memory operation such
+  // as 'memset'.
+  // For example, for code
+  //typedef struct {
+  //  int i  :2;
+  //  int:30;  // unnamed bit-field
+  //} A;
+  //A a = {1};
+  // The bits of the unnamed bit-field in local variable a can be anything.
   const FieldDecl *FD = R->getDecl();
+  if (FD->isUnnamedBitField()) {
+  return UndefinedVal();
+  }
+
+  // If the containing record was initialized, try to get its constant value.

Tedlion wrote:

The continue line is added in commit 3720e2f00630ace63fbf2c8d154e340c029fc186, 
when the function `tryBindSmallStruct` is added. The commit log illustrates the 
reason for binding a LazyCompoundVal to simple struct by  memberwise copy, but 
discusses nothing  about the unnamed bit-field.
I'll make a new pull-request to fix this soon.

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


[clang] [llvm] Add __attribute__((visibility("default"))) attribute to certain symbols to stop them being hidden when linking clangInterpreter library to other libraries during Emscripten build (PR #1

2025-07-03 Thread Saleem Abdulrasool via cfe-commits

compnerd wrote:

I think that it might be better to wait on this change until we do this 
properly. In the mean time, the workaround would be to use 
`-fvisibility=default`. If you want to help with the annotations to make clang 
build as a DSO, I think that @andrurogerz would welcome the help. But, this 
change should be split up so that it can be easily reviewed similar to how we 
have been approaching the LLVM side.

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


[clang] [llvm] [NFC][HLSL][DirectX] Let `HLSLRootSignature` reuse the `dxbc` defined enums (PR #145986)

2025-07-03 Thread Justin Bogner via cfe-commits

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

looks good, one more comment about using enum values rather than bit patterns 
in a test

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


[clang] [llvm] [NFC][HLSL][DirectX] Let `HLSLRootSignature` reuse the `dxbc` defined enums (PR #145986)

2025-07-03 Thread Justin Bogner via cfe-commits

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


[clang] [llvm] [NFC][HLSL][DirectX] Let `HLSLRootSignature` reuse the `dxbc` defined enums (PR #145986)

2025-07-03 Thread Justin Bogner via cfe-commits


@@ -56,7 +56,7 @@ TEST(HLSLRootSignatureTest, DescriptorUAVClauseDump) {
   Clause.NumDescriptors = 3298;
   Clause.Space = 932847;
   Clause.Offset = 1;
-  Clause.Flags = DescriptorRangeFlags::ValidFlags;
+  Clause.Flags = llvm::dxbc::DescriptorRangeFlags(0x1000f);

bogner wrote:

Should we `or` enum values together here as well? Also applies to a couple of 
places later in this file.

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


[clang] [CIR] Upstream __builtin_creal for ComplexType (PR #146927)

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

https://github.com/AmrDeveloper created 
https://github.com/llvm/llvm-project/pull/146927

Upstream `__builtin_creal` support for ComplexType

https://github.com/llvm/llvm-project/issues/141365

>From 518f6ee1e10319f12eac78c675e082a6fbeebb33 Mon Sep 17 00:00:00 2001
From: AmrDeveloper 
Date: Thu, 3 Jul 2025 19:14:55 +0200
Subject: [PATCH] [CIR] Upstream __builtin_creal for ComplexType

---
 clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp | 25 +++--
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp|  3 +--
 clang/test/CIR/CodeGen/complex-builtins.cpp | 25 +
 3 files changed, 44 insertions(+), 9 deletions(-)

diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp 
b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
index fb046533a91b8..1e56ea4d9bd8e 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
@@ -83,13 +83,6 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl &gd, 
unsigned builtinID,
 
   const FunctionDecl *fd = gd.getDecl()->getAsFunction();
 
-  // If this is an alias for a lib function (e.g. __builtin_sin), emit
-  // the call using the normal call path, but using the unmangled
-  // version of the function name.
-  if (getContext().BuiltinInfo.isLibFunction(builtinID))
-return emitLibraryCall(*this, fd, e,
-   cgm.getBuiltinLibFunction(fd, builtinID));
-
   assert(!cir::MissingFeatures::builtinCallF128());
 
   // If the builtin has been declared explicitly with an assembler label,
@@ -124,6 +117,17 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl 
&gd, unsigned builtinID,
 return RValue::get(complex);
   }
 
+  case Builtin::BI__builtin_creal:
+  case Builtin::BI__builtin_crealf:
+  case Builtin::BI__builtin_creall:
+  case Builtin::BIcreal:
+  case Builtin::BIcrealf:
+  case Builtin::BIcreall: {
+mlir::Value complex = emitComplexExpr(e->getArg(0));
+mlir::Value real = builder.createComplexReal(loc, complex);
+return RValue::get(real);
+  }
+
   case Builtin::BI__builtin_clrsb:
   case Builtin::BI__builtin_clrsbl:
   case Builtin::BI__builtin_clrsbll:
@@ -192,6 +196,13 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl 
&gd, unsigned builtinID,
   }
   }
 
+  // If this is an alias for a lib function (e.g. __builtin_sin), emit
+  // the call using the normal call path, but using the unmangled
+  // version of the function name.
+  if (getContext().BuiltinInfo.isLibFunction(builtinID))
+return emitLibraryCall(*this, fd, e,
+   cgm.getBuiltinLibFunction(fd, builtinID));
+
   cgm.errorNYI(e->getSourceRange(), "unimplemented builtin call");
   return getUndefRValue(e->getType());
 }
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 68d7f1f5bca48..300ba7a456e4b 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -1094,8 +1094,7 @@ RValue CIRGenFunction::emitAnyExpr(const Expr *e, 
AggValueSlot aggSlot) {
   case cir::TEK_Scalar:
 return RValue::get(emitScalarExpr(e));
   case cir::TEK_Complex:
-cgm.errorNYI(e->getSourceRange(), "emitAnyExpr: complex type");
-return RValue::get(nullptr);
+return RValue::getComplex(emitComplexExpr(e));
   case cir::TEK_Aggregate: {
 if (aggSlot.isIgnored())
   aggSlot = createAggTemp(e->getType(), getLoc(e->getSourceRange()),
diff --git a/clang/test/CIR/CodeGen/complex-builtins.cpp 
b/clang/test/CIR/CodeGen/complex-builtins.cpp
index 2372ab571e533..fdda5eb707fb7 100644
--- a/clang/test/CIR/CodeGen/complex-builtins.cpp
+++ b/clang/test/CIR/CodeGen/complex-builtins.cpp
@@ -33,3 +33,28 @@ void foo() {
 // OGCG: %[[R_IMAG_PTR:.*]] = getelementptr inbounds nuw { i32, i32 }, ptr 
%[[COMPLEX_R]], i32 0, i32 1
 // OGCG: store i32 %[[A_REAL]], ptr %[[R_REAL_PTR]], align 4
 // OGCG: store i32 %[[A_IMAG]], ptr %[[R_IMAG_PTR]], align 4
+
+void foo2() {
+  double _Complex a;
+  double real = __builtin_creal(a);
+}
+
+// CIR: %[[COMPLEX:.*]] = cir.alloca !cir.complex, 
!cir.ptr>, ["a"]
+// CIR: %[[INIT:.*]] = cir.alloca !cir.double, !cir.ptr, ["real", 
init]
+// CIR: %[[TMP:.*]] = cir.load{{.*}} %[[COMPLEX]] : 
!cir.ptr>, !cir.complex
+// CIR: %[[REAL:.*]] = cir.complex.real %[[TMP]] : !cir.complex 
-> !cir.double
+// CIR: cir.store{{.*}} %[[REAL]], %[[INIT]] : !cir.double, 
!cir.ptr
+
+// LLVM: %[[COMPLEX:.*]] = alloca { double, double }, i64 1, align 8
+// LLVM: %[[INIT:.*]] = alloca double, i64 1, align 8
+// LLVM: %[[TMP:.*]] = load { double, double }, ptr %[[COMPLEX]], align 8
+// LLVM: %[[REAL:.*]] = extractvalue { double, double } %[[TMP]], 0
+// LLVM: store double %[[REAL]], ptr %[[INIT]], align 8
+
+// OGCG: %[[COMPLEX:.*]] = alloca { double, double }, align 8
+// OGCG: %[[INIT:.*]] = alloca double, align 8
+// OGCG: %[[A_REAL_PTR:.*]] = getelementptr inbounds nuw { double, double }, 
ptr %[[COMPLEX]], i32 0, i32 0
+// OGCG: %[[A_REAL:.*]] = load double, ptr %[[A_REAL_PTR]], align 8
+// OGCG: %[[A_IMAG

  1   2   3   4   5   6   >