[libunwind] [libunwind] [SEH] Implement parsing of aarch64 pdata/xdata (PR #137949)

2025-05-01 Thread Martin Storsjö via cfe-commits


@@ -2018,6 +2018,52 @@ bool UnwindCursor::getInfoFromSEH(pint_t pc) {
   _info.handler = 0;
 }
   }
+#elif defined(_LIBUNWIND_TARGET_AARCH64)
+  if (unwindEntry->Flag != 0) { // Packed unwind info
+_info.end_ip = _info.start_ip + unwindEntry->FunctionLength * 4;
+// Only fill in the handler and LSDA if they're stale.
+if (pc != getLastPC()) {
+  // Packed unwind info doesn't have an exception handler.
+  _info.lsda = 0;
+  _info.handler = 0;
+}
+  } else {
+IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY_XDATA *xdata =
+reinterpret_cast(
+base + unwindEntry->UnwindData);
+_info.end_ip = _info.start_ip + xdata->FunctionLength * 4;
+// Only fill in the handler and LSDA if they're stale.
+if (pc != getLastPC()) {
+  if (xdata->ExceptionDataPresent) {
+uint32_t offset = 1; // The main xdata
+uint32_t codeWords = xdata->CodeWords;
+uint32_t epilogScopes = xdata->EpilogCount;
+if (xdata->EpilogCount == 0 && xdata->CodeWords == 0) {
+  uint32_t extensionWord = reinterpret_cast(xdata)[1];
+  codeWords = (extensionWord >> 16) & 0xff;
+  epilogScopes = extensionWord & 0x;
+  offset++;
+}
+if (!xdata->EpilogInHeader)
+  offset += epilogScopes;
+offset += codeWords;
+uint32_t *exceptionHandlerInfo =
+reinterpret_cast(xdata) + offset;
+_dispContext.HandlerData = &exceptionHandlerInfo[1];
+_dispContext.LanguageHandler = reinterpret_cast(
+base + exceptionHandlerInfo[0]);
+_info.lsda = reinterpret_cast(_dispContext.HandlerData);
+if (_dispContext.LanguageHandler)

mstorsjo wrote:

Oh, yes, that's right - thanks for catching!

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


[clang] [llvm] [mlir] [AMDGPU] Add a new amdgcn.load.to.lds intrinsic (PR #137425)

2025-05-01 Thread Krzysztof Drewniak via cfe-commits

https://github.com/krzysz00 updated 
https://github.com/llvm/llvm-project/pull/137425



  



Rate limit · GitHub


  body {
background-color: #f6f8fa;
color: #24292e;
font-family: -apple-system,BlinkMacSystemFont,Segoe 
UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
font-size: 14px;
line-height: 1.5;
margin: 0;
  }

  .container { margin: 50px auto; max-width: 600px; text-align: center; 
padding: 0 24px; }

  a { color: #0366d6; text-decoration: none; }
  a:hover { text-decoration: underline; }

  h1 { line-height: 60px; font-size: 48px; font-weight: 300; margin: 0px; 
text-shadow: 0 1px 0 #fff; }
  p { color: rgba(0, 0, 0, 0.5); margin: 20px 0 40px; }

  ul { list-style: none; margin: 25px 0; padding: 0; }
  li { display: table-cell; font-weight: bold; width: 1%; }

  .logo { display: inline-block; margin-top: 35px; }
  .logo-img-2x { display: none; }
  @media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and ( -o-min-device-pixel-ratio: 2/1),
  only screen and (min-device-pixel-ratio: 2),
  only screen and (min-resolution: 192dpi),
  only screen and (min-resolution: 2dppx) {
.logo-img-1x { display: none; }
.logo-img-2x { display: inline-block; }
  }

  #suggestions {
margin-top: 35px;
color: #ccc;
  }
  #suggestions a {
color: #66;
font-weight: 200;
font-size: 14px;
margin: 0 10px;
  }


  
  



  Whoa there!
  You have exceeded a secondary rate limit.
Please wait a few minutes before you try again;
in some cases this may take up to an hour.
  
  
https://support.github.com/contact";>Contact Support —
https://githubstatus.com";>GitHub Status —
https://twitter.com/githubstatus";>@githubstatus
  

  

  

  

  

  


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


[clang] [C] Allow __attribute__((nonstring)) on multidimensional arrays (PR #138133)

2025-05-01 Thread Nathan Chancellor via cfe-commits

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

Thanks, this appears to resolve the warning in the one place that I know needs 
it.

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


[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Andy Kaylor via cfe-commits

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

lgtm

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


[clang-tools-extra] [clang-tidy] Return error code on config parse error (PR #136167)

2025-05-01 Thread Galen Elias via cfe-commits


@@ -266,7 +266,7 @@ ClangTidyOptions 
ClangTidyContext::getOptionsForFile(StringRef File) const {
   // Merge options on top of getDefaults() as a safeguard against options with
   // unset values.
   return ClangTidyOptions::getDefaults().merge(
-  OptionsProvider->getOptions(File), 0);
+  *OptionsProvider->getOptions(File), 0);

galenelias wrote:

Ok, so my current plan is:
* Loop through all input files in clangTidyMain to explicitly validate configs 
for each input file and be able to return an error code there if a failure is 
found.
* In this method (`ClangTidyContext::getOptionsForFile`) just return the 
default config options if an error is found, which is similar to the behavior 
before this PR.  It seems like trying to make getOptionsForFile return an 
ErrorOr object and handle that at each call site is very cumbersome and leads 
to a lot of non-obvious failure modes that need to be resolved.

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


[clang] [OpenACC] Implement better dupe catching for device_type clauses (PR #138196)

2025-05-01 Thread Erich Keane via cfe-commits

https://github.com/erichkeane created 
https://github.com/llvm/llvm-project/pull/138196

Previously we just checked duplicates for a handful of clauses between active 
device_type clauses.  However, after looking into the implementation for 
'collapse', I discovered that duplicate device_type identifiers with duplicate 
versions of htese clause are problematic.

This patch corrects this and now catches these conflicts.

>From 3b0bd9a11e85324d2b00566a6816b03930afcfe7 Mon Sep 17 00:00:00 2001
From: erichkeane 
Date: Thu, 1 May 2025 13:14:51 -0700
Subject: [PATCH] [OpenACC] Implement better dupe catching for device_type
 clauses

Previously we just checked duplicates for a handful of clauses between
active device_type clauses.  However, after looking into the
implementation for 'collapse', I discovered that duplicate device_type
identifiers with duplicate versions of htese clause are problematic.

This patch corrects this and now catches these conflicts.
---
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +
 clang/lib/Sema/SemaOpenACCClause.cpp  | 98 ---
 .../compute-construct-num_gangs-clause.c  | 15 +++
 .../compute-construct-num_workers-clause.c| 15 +++
 .../compute-construct-vector_length-clause.c  | 15 +++
 .../loop-construct-collapse-clause.cpp| 21 
 .../loop-construct-tile-clause.cpp| 16 +++
 7 files changed, 171 insertions(+), 12 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 604bb56d28252..f279d84136562 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13075,6 +13075,9 @@ def err_acc_clause_routine_one_of_in_region
 def err_acc_clause_since_last_device_type
 : Error<"OpenACC '%0' clause cannot appear more than once%select{| in a "
 "'device_type' region}2 on a '%1' directive">;
+def err_acc_clause_conflicts_prev_dev_type
+: Error<"OpenACC '%0' clause applies to 'device_type' '%1', which "
+"conflicts with previous clause">;
 
 def err_acc_reduction_num_gangs_conflict
 : Error<"OpenACC '%1' clause %select{|with more than 1 argument }0may not "
diff --git a/clang/lib/Sema/SemaOpenACCClause.cpp 
b/clang/lib/Sema/SemaOpenACCClause.cpp
index 6cf6888e2a3a9..87dae457ac3e9 100644
--- a/clang/lib/Sema/SemaOpenACCClause.cpp
+++ b/clang/lib/Sema/SemaOpenACCClause.cpp
@@ -335,29 +335,103 @@ class SemaOpenACCClauseVisitor {
 
   // For 'tile' and 'collapse', only allow 1 per 'device_type'.
   // Also applies to num_worker, num_gangs, vector_length, and async.
+  // This does introspection into the actual device-types to prevent duplicates
+  // across device types as well.
   template 
   bool DisallowSinceLastDeviceType(SemaOpenACC::OpenACCParsedClause &Clause) {
 auto LastDeviceTypeItr =
 std::find_if(ExistingClauses.rbegin(), ExistingClauses.rend(),
  llvm::IsaPred);
 
-auto Last = std::find_if(ExistingClauses.rbegin(), LastDeviceTypeItr,
- llvm::IsaPred);
+auto LastSinceDevTy =
+std::find_if(ExistingClauses.rbegin(), LastDeviceTypeItr,
+ llvm::IsaPred);
 
-if (Last == LastDeviceTypeItr)
+// In this case there is a duplicate since the last device_type/lack of a
+// device_type.  Diagnose these as duplicates.
+if (LastSinceDevTy != LastDeviceTypeItr) {
+  SemaRef.Diag(Clause.getBeginLoc(),
+   diag::err_acc_clause_since_last_device_type)
+  << Clause.getClauseKind() << Clause.getDirectiveKind()
+  << (LastDeviceTypeItr != ExistingClauses.rend());
+  SemaRef.Diag((*LastSinceDevTy)->getBeginLoc(),
+   diag::note_acc_previous_clause_here);
+
+  // Mention the last device_type as well.
+  if (LastDeviceTypeItr != ExistingClauses.rend())
+SemaRef.Diag((*LastDeviceTypeItr)->getBeginLoc(),
+ diag::note_acc_previous_clause_here);
+  return true;
+}
+
+// If this isn't in a device_type, and we didn't diagnose that there are
+// dupes above, just give up, no sense in searching for previous 
device_type
+// regions as they don't exist.
+if (LastDeviceTypeItr == ExistingClauses.rend())
   return false;
 
-SemaRef.Diag(Clause.getBeginLoc(),
- diag::err_acc_clause_since_last_device_type)
-<< Clause.getClauseKind() << Clause.getDirectiveKind()
-<< (LastDeviceTypeItr != ExistingClauses.rend());
-SemaRef.Diag((*Last)->getBeginLoc(), diag::note_acc_previous_clause_here);
+// The device-type that is active for us, so we can compare to the previous
+// ones.
+const auto &ActiveDeviceTypeClause =
+cast(**LastDeviceTypeItr);
 
-if (LastDeviceTypeItr != ExistingClauses.rend())
-  SemaRef.Diag((*LastDeviceTypeItr)->getBeginLoc(),
-   diag::note_acc_previous_clause_here);
+  

[clang] [OpenACC] Implement better dupe catching for device_type clauses (PR #138196)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Erich Keane (erichkeane)


Changes

Previously we just checked duplicates for a handful of clauses between active 
device_type clauses.  However, after looking into the implementation for 
'collapse', I discovered that duplicate device_type identifiers with duplicate 
versions of htese clause are problematic.

This patch corrects this and now catches these conflicts.

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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/lib/Sema/SemaOpenACCClause.cpp (+86-12) 
- (modified) clang/test/SemaOpenACC/compute-construct-num_gangs-clause.c (+15) 
- (modified) clang/test/SemaOpenACC/compute-construct-num_workers-clause.c 
(+15) 
- (modified) clang/test/SemaOpenACC/compute-construct-vector_length-clause.c 
(+15) 
- (modified) clang/test/SemaOpenACC/loop-construct-collapse-clause.cpp (+21) 
- (modified) clang/test/SemaOpenACC/loop-construct-tile-clause.cpp (+16) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 604bb56d28252..f279d84136562 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13075,6 +13075,9 @@ def err_acc_clause_routine_one_of_in_region
 def err_acc_clause_since_last_device_type
 : Error<"OpenACC '%0' clause cannot appear more than once%select{| in a "
 "'device_type' region}2 on a '%1' directive">;
+def err_acc_clause_conflicts_prev_dev_type
+: Error<"OpenACC '%0' clause applies to 'device_type' '%1', which "
+"conflicts with previous clause">;
 
 def err_acc_reduction_num_gangs_conflict
 : Error<"OpenACC '%1' clause %select{|with more than 1 argument }0may not "
diff --git a/clang/lib/Sema/SemaOpenACCClause.cpp 
b/clang/lib/Sema/SemaOpenACCClause.cpp
index 6cf6888e2a3a9..87dae457ac3e9 100644
--- a/clang/lib/Sema/SemaOpenACCClause.cpp
+++ b/clang/lib/Sema/SemaOpenACCClause.cpp
@@ -335,29 +335,103 @@ class SemaOpenACCClauseVisitor {
 
   // For 'tile' and 'collapse', only allow 1 per 'device_type'.
   // Also applies to num_worker, num_gangs, vector_length, and async.
+  // This does introspection into the actual device-types to prevent duplicates
+  // across device types as well.
   template 
   bool DisallowSinceLastDeviceType(SemaOpenACC::OpenACCParsedClause &Clause) {
 auto LastDeviceTypeItr =
 std::find_if(ExistingClauses.rbegin(), ExistingClauses.rend(),
  llvm::IsaPred);
 
-auto Last = std::find_if(ExistingClauses.rbegin(), LastDeviceTypeItr,
- llvm::IsaPred);
+auto LastSinceDevTy =
+std::find_if(ExistingClauses.rbegin(), LastDeviceTypeItr,
+ llvm::IsaPred);
 
-if (Last == LastDeviceTypeItr)
+// In this case there is a duplicate since the last device_type/lack of a
+// device_type.  Diagnose these as duplicates.
+if (LastSinceDevTy != LastDeviceTypeItr) {
+  SemaRef.Diag(Clause.getBeginLoc(),
+   diag::err_acc_clause_since_last_device_type)
+  << Clause.getClauseKind() << Clause.getDirectiveKind()
+  << (LastDeviceTypeItr != ExistingClauses.rend());
+  SemaRef.Diag((*LastSinceDevTy)->getBeginLoc(),
+   diag::note_acc_previous_clause_here);
+
+  // Mention the last device_type as well.
+  if (LastDeviceTypeItr != ExistingClauses.rend())
+SemaRef.Diag((*LastDeviceTypeItr)->getBeginLoc(),
+ diag::note_acc_previous_clause_here);
+  return true;
+}
+
+// If this isn't in a device_type, and we didn't diagnose that there are
+// dupes above, just give up, no sense in searching for previous 
device_type
+// regions as they don't exist.
+if (LastDeviceTypeItr == ExistingClauses.rend())
   return false;
 
-SemaRef.Diag(Clause.getBeginLoc(),
- diag::err_acc_clause_since_last_device_type)
-<< Clause.getClauseKind() << Clause.getDirectiveKind()
-<< (LastDeviceTypeItr != ExistingClauses.rend());
-SemaRef.Diag((*Last)->getBeginLoc(), diag::note_acc_previous_clause_here);
+// The device-type that is active for us, so we can compare to the previous
+// ones.
+const auto &ActiveDeviceTypeClause =
+cast(**LastDeviceTypeItr);
 
-if (LastDeviceTypeItr != ExistingClauses.rend())
-  SemaRef.Diag((*LastDeviceTypeItr)->getBeginLoc(),
-   diag::note_acc_previous_clause_here);
+auto PrevDeviceTypeItr = LastDeviceTypeItr;
+auto CurDevTypeItr = LastDeviceTypeItr;
 
-return true;
+while ((CurDevTypeItr = std::find_if(
+std::next(PrevDeviceTypeItr), ExistingClauses.rend(),
+llvm::IsaPred)) !=
+   ExistingClauses.rend()) {
+  // At this point, we know that we have a region between two devi

[clang] [lldb] [llvm] [mlir] [NFC][Support] Add llvm::uninitialized_copy (PR #138174)

2025-05-01 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/138174

>From de1b49fc6b8819b591e48b81634567ceeffe5089 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 30 Apr 2025 23:47:37 -0700
Subject: [PATCH] [NFC][Support] Add llvm::uninitialized_copy

Add `llvm::uninitialized_copy` that accepts a range instead of two
iterators for the source of the copy and adopt it.
---
 clang/include/clang/AST/DeclCXX.h |  6 +-
 clang/include/clang/AST/DeclOpenACC.h |  9 +--
 clang/include/clang/AST/ExprCXX.h |  6 +-
 clang/include/clang/AST/OpenACCClause.h   | 72 +++
 clang/include/clang/AST/StmtOpenACC.h | 54 +++---
 clang/include/clang/Sema/ParsedTemplate.h |  4 +-
 clang/lib/AST/Decl.cpp|  6 +-
 clang/lib/AST/DeclObjC.cpp|  4 +-
 clang/lib/AST/DeclTemplate.cpp| 11 ++-
 clang/lib/AST/Expr.cpp|  8 +--
 clang/lib/AST/ExprCXX.cpp | 16 ++---
 clang/lib/AST/OpenACCClause.cpp   | 13 ++--
 clang/lib/AST/StmtOpenACC.cpp |  4 +-
 clang/lib/AST/Type.cpp|  8 +--
 clang/tools/libclang/CXIndexDataConsumer.cpp  |  3 +-
 lldb/source/Utility/Checksum.cpp  |  4 +-
 llvm/include/llvm/ADT/ArrayRef.h  |  2 +-
 llvm/include/llvm/ADT/STLExtras.h |  5 ++
 llvm/lib/Analysis/ScalarEvolution.cpp | 10 +--
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp |  3 +-
 llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp   |  4 +-
 llvm/lib/DebugInfo/MSF/MSFBuilder.cpp |  6 +-
 llvm/lib/IR/AttributeImpl.h   |  2 +-
 llvm/lib/ObjectYAML/MinidumpEmitter.cpp   |  2 +-
 llvm/lib/Support/FoldingSet.cpp   |  4 +-
 .../AMDGPU/MCTargetDesc/AMDGPUMCExpr.cpp  |  2 +-
 llvm/lib/Transforms/IPO/LowerTypeTests.cpp|  7 +-
 .../unittests/Support/TrailingObjectsTest.cpp | 11 ++-
 mlir/include/mlir/IR/BuiltinAttributes.td |  2 +-
 mlir/include/mlir/Support/StorageUniquer.h|  4 +-
 .../Dialect/Affine/Analysis/NestedMatcher.cpp |  4 +-
 mlir/lib/IR/AffineMapDetail.h |  3 +-
 mlir/lib/IR/Location.cpp  |  8 +--
 mlir/lib/IR/MLIRContext.cpp   |  2 +-
 mlir/lib/IR/TypeDetail.h  |  3 +-
 mlir/lib/Tools/PDLL/AST/Nodes.cpp | 42 ---
 36 files changed, 153 insertions(+), 201 deletions(-)

diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index dd325815ee28d..20720115bf6c3 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -3861,8 +3861,7 @@ class UsingPackDecl final
   InstantiatedFrom ? InstantiatedFrom->getDeclName()
: DeclarationName()),
 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
-std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(UsingDecls, getTrailingObjects());
   }
 
   void anchor() override;
@@ -4233,8 +4232,7 @@ class DecompositionDecl final
   : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
 SC),
 NumBindings(Bindings.size()) {
-std::uninitialized_copy(Bindings.begin(), Bindings.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Bindings, getTrailingObjects());
 for (auto *B : Bindings) {
   B->setDecomposedDecl(this);
   if (B->isParameterPack() && B->getBinding()) {
diff --git a/clang/include/clang/AST/DeclOpenACC.h 
b/clang/include/clang/AST/DeclOpenACC.h
index 8c612fbf1ec07..905d9bf636ea1 100644
--- a/clang/include/clang/AST/DeclOpenACC.h
+++ b/clang/include/clang/AST/DeclOpenACC.h
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/OpenACCClause.h"
 #include "clang/Basic/OpenACCKinds.h"
+#include "llvm/ADT/STLExtras.h"
 
 namespace clang {
 
@@ -85,8 +86,8 @@ class OpenACCDeclareDecl final
   : OpenACCConstructDecl(OpenACCDeclare, DC, OpenACCDirectiveKind::Declare,
  StartLoc, DirLoc, EndLoc) {
 // Initialize the trailing storage.
-std::uninitialized_copy(Clauses.begin(), Clauses.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Clauses,
+ getTrailingObjects());
 
 setClauseList(MutableArrayRef(getTrailingObjects(),
   Clauses.size()));
@@ -136,8 +137,8 @@ class OpenACCRoutineDecl final
 assert(LParenLoc.isValid() &&
"Cannot represent implicit name with this declaration");
 // Initialize the trailing storage.
-std::uninitialized_copy(Clauses.begin(), Clauses.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Clauses,
+ getTrailingObj

[clang] [CIR] Upstream local initialization for VectorType (PR #138107)

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -1584,6 +1586,47 @@ mlir::Value 
ScalarExprEmitter::VisitMemberExpr(MemberExpr *e) {
   return emitLoadOfLValue(e);
 }
 
+mlir::Value ScalarExprEmitter::VisitInitListExpr(InitListExpr *e) {
+  const unsigned numInitElements = e->getNumInits();
+
+  if (e->hadArrayRangeDesignator()) {
+cgf.cgm.errorNYI(e->getSourceRange(), "ArrayRangeDesignator");
+return {};
+  }
+
+  if (numInitElements == 0) {
+cgf.cgm.errorNYI(e->getSourceRange(), "InitListExpr with 0 init elements");
+return {};
+  }
+
+  if (e->getType()->isVectorType()) {
+const auto vectorType =
+mlir::cast(cgf.convertType(e->getType()));
+
+SmallVector elements;
+for (Expr *init : e->inits()) {
+  elements.push_back(Visit(init));
+}
+
+// Zero-initialize any remaining values.
+if (numInitElements < vectorType.getSize()) {
+  mlir::TypedAttr zeroInitAttr =
+  cgf.getBuilder().getZeroInitAttr(vectorType.getElementType());
+  cir::ConstantOp zeroValue = cgf.getBuilder().getConstant(
+  cgf.getLoc(e->getSourceRange()), zeroInitAttr);
+
+  for (uint64_t i = numInitElements; i < vectorType.getSize(); ++i) {

andykaylor wrote:

Yes, that looks right.

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


[clang] a76936f - [CIR] Upstream support for range-based for loops (#138176)

2025-05-01 Thread via cfe-commits

Author: Andy Kaylor
Date: 2025-05-01T14:47:20-07:00
New Revision: a76936f1c01c7cadbce8ea6553af758d0f614b6a

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

LOG: [CIR] Upstream support for range-based for loops (#138176)

This upstreams the code needed to handle CXXForRangeStmt.

Added: 


Modified: 
clang/lib/CIR/CodeGen/CIRGenExpr.cpp
clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
clang/lib/CIR/CodeGen/CIRGenFunction.h
clang/lib/CIR/CodeGen/CIRGenStmt.cpp
clang/test/CIR/CodeGen/loop.cpp

Removed: 




diff  --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index da5a0b97a395e..471c8b3975d96 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -948,6 +948,41 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+Address CIRGenFunction::emitArrayToPointerDecay(const Expr *e) {
+  assert(e->getType()->isArrayType() &&
+ "Array to pointer decay must have array source type!");
+
+  // Expressions of array type can't be bitfields or vector elements.
+  LValue lv = emitLValue(e);
+  Address addr = lv.getAddress();
+
+  // If the array type was an incomplete type, we need to make sure
+  // the decay ends up being the right type.
+  auto lvalueAddrTy = 
mlir::cast(addr.getPointer().getType());
+
+  if (e->getType()->isVariableArrayType())
+return addr;
+
+  auto pointeeTy = mlir::cast(lvalueAddrTy.getPointee());
+
+  mlir::Type arrayTy = convertType(e->getType());
+  assert(mlir::isa(arrayTy) && "expected array");
+  assert(pointeeTy == arrayTy);
+
+  // The result of this decay conversion points to an array element within the
+  // base lvalue. However, since TBAA currently does not support representing
+  // accesses to elements of member arrays, we conservatively represent 
accesses
+  // to the pointee object as if it had no any base lvalue specified.
+  // TODO: Support TBAA for member arrays.
+  QualType eltType = e->getType()->castAsArrayTypeUnsafe()->getElementType();
+  assert(!cir::MissingFeatures::opTBAA());
+
+  mlir::Value ptr = builder.maybeBuildArrayDecay(
+  cgm.getLoc(e->getSourceRange()), addr.getPointer(),
+  convertTypeForMem(eltType));
+  return Address(ptr, addr.getAlignment());
+}
+
 /// Emit an `if` on a boolean condition, filling `then` and `else` into
 /// appropriated regions.
 mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,

diff  --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 78eb3cbd430bc..423cddd374e8f 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -1567,6 +1567,9 @@ mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr 
*ce) {
 return v;
   }
 
+  case CK_ArrayToPointerDecay:
+return cgf.emitArrayToPointerDecay(subExpr).getPointer();
+
   case CK_NullToPointer: {
 if (mustVisitNullValue(subExpr))
   cgf.emitIgnoredExpr(subExpr);

diff  --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h 
b/clang/lib/CIR/CodeGen/CIRGenFunction.h
index d50abfcfbc867..ac5d39fc61795 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.h
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h
@@ -449,6 +449,8 @@ class CIRGenFunction : public CIRGenTypeCache {
 
   LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e);
 
+  Address emitArrayToPointerDecay(const Expr *array);
+
   AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d);
 
   /// Emit code and set up symbol table for a variable declaration with auto,
@@ -485,6 +487,10 @@ class CIRGenFunction : public CIRGenTypeCache {
   LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e);
 
   mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s);
+
+  mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s,
+  llvm::ArrayRef attrs);
+
   mlir::LogicalResult emitDoStmt(const clang::DoStmt &s);
 
   /// Emit an expression as an initializer for an object (variable, field, 
etc.)

diff  --git a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp 
b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
index dffa71046df1d..ee4dcc861a1f2 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
@@ -97,6 +97,8 @@ mlir::LogicalResult CIRGenFunction::emitStmt(const Stmt *s,
 return emitWhileStmt(cast(*s));
   case Stmt::DoStmtClass:
 return emitDoStmt(cast(*s));
+  case Stmt::CXXForRangeStmtClass:
+return emitCXXForRangeStmt(cast(*s), attr);
   case Stmt::OpenACCComputeConstructClass:
 return emitOpenACCComputeConstruct(cast(*s));
   case Stmt::OpenACCLoopConstructClass:
@@ -137,7 +139,6 @@ mlir::LogicalResult CIRGenFunction::emitStmt(const Stmt *s

[clang] [llvm] [HLSL][DXIL] Implement `refract` intrinsic (PR #136026)

2025-05-01 Thread via cfe-commits

https://github.com/raoanag updated 
https://github.com/llvm/llvm-project/pull/136026

>From 6ce233acf415d2d48eca8f75d69b678c8877aa84 Mon Sep 17 00:00:00 2001
From: Anagha Rajendra Rao 
Date: Wed, 16 Apr 2025 11:47:27 -0700
Subject: [PATCH 1/6] Refract implementation

---
 clang/test/CodeGenHLSL/builtins/refract.hlsl  | 92 +++
 clang/test/CodeGenSPIRV/Builtins/refract.c| 32 +++
 .../SemaHLSL/BuiltIns/refract-errors.hlsl | 74 +++
 .../CodeGen/SPIRV/hlsl-intrinsics/refract.ll  | 33 +++
 4 files changed, 231 insertions(+)
 create mode 100644 clang/test/CodeGenHLSL/builtins/refract.hlsl
 create mode 100644 clang/test/CodeGenSPIRV/Builtins/refract.c
 create mode 100644 clang/test/SemaHLSL/BuiltIns/refract-errors.hlsl
 create mode 100644 llvm/test/CodeGen/SPIRV/hlsl-intrinsics/refract.ll

diff --git a/clang/test/CodeGenHLSL/builtins/refract.hlsl 
b/clang/test/CodeGenHLSL/builtins/refract.hlsl
new file mode 100644
index 0..4dc5b66251b62
--- /dev/null
+++ b/clang/test/CodeGenHLSL/builtins/refract.hlsl
@@ -0,0 +1,92 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -finclude-default-header -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -O1 -o - | FileCheck %s
+// RUN: %clang_cc1 -finclude-default-header -triple \
+// RUN:   spirv-unknown-vulkan-compute %s -fnative-half-type \
+// RUN:   -emit-llvm -O1 -o - | FileCheck %s --check-prefix=SPVCHECK
+
+// CHECK-LABEL: define noundef nofpclass(nan inf) float 
@_Z18test_refract_floatff(
+// CHECK-SAME: float noundef nofpclass(nan inf) [[I:%.*]], float noundef 
nofpclass(nan inf) [[N:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[MUL_I:%.*]] = fmul reassoc nnan ninf nsz arcp afn float 
[[I]], 2.00e+00
+// CHECK-NEXT:[[TMP0:%.*]] = fmul reassoc nnan ninf nsz arcp afn float 
[[N]], [[N]]
+// CHECK-NEXT:[[MUL2_I:%.*]] = fmul reassoc nnan ninf nsz arcp afn float 
[[TMP0]], [[MUL_I]]
+// CHECK-NEXT:[[SUB_I:%.*]] = fsub reassoc nnan ninf nsz arcp afn float 
[[I]], [[MUL2_I]]
+// CHECK-NEXT:ret float [[SUB_I]]
+//
+// SPVCHECK-LABEL: define spir_func noundef nofpclass(nan inf) float 
@_Z18test_refract_floatff(
+// SPVCHECK-SAME: float noundef nofpclass(nan inf) [[I:%.*]], float noundef 
nofpclass(nan inf) [[N:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// SPVCHECK-NEXT:  [[ENTRY:.*:]]
+// SPVCHECK-NEXT:[[MUL_I:%.*]] = fmul reassoc nnan ninf nsz arcp afn float 
[[I]], 2.00e+00
+// SPVCHECK-NEXT:[[TMP0:%.*]] = fmul reassoc nnan ninf nsz arcp afn float 
[[N]], [[N]]
+// SPVCHECK-NEXT:[[MUL2_I:%.*]] = fmul reassoc nnan ninf nsz arcp afn 
float [[TMP0]], [[MUL_I]]
+// SPVCHECK-NEXT:[[SUB_I:%.*]] = fsub reassoc nnan ninf nsz arcp afn float 
[[I]], [[MUL2_I]]
+// SPVCHECK-NEXT:ret float [[SUB_I]]
+//
+float test_refract_float(float I, float N, float eta) {
+return refract(I, N, eta);
+}
+
+// CHECK-LABEL: define noundef nofpclass(nan inf) <2 x float> 
@_Z19test_refract_float2Dv2_fS_(
+// CHECK-SAME: <2 x float> noundef nofpclass(nan inf) [[I:%.*]], <2 x float> 
noundef nofpclass(nan inf) [[N:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[HLSL_DOT_I:%.*]] = tail call reassoc nnan ninf nsz arcp 
afn float @llvm.dx.fdot.v2f32(<2 x float> [[I]], <2 x float> [[N]])
+// CHECK-NEXT:[[DOTSCALAR:%.*]] = fmul reassoc nnan ninf nsz arcp afn 
float [[HLSL_DOT_I]], 2.00e+00
+// CHECK-NEXT:[[TMP0:%.*]] = insertelement <2 x float> poison, float 
[[DOTSCALAR]], i64 0
+// CHECK-NEXT:[[TMP1:%.*]] = shufflevector <2 x float> [[TMP0]], <2 x 
float> poison, <2 x i32> zeroinitializer
+// CHECK-NEXT:[[MUL1_I:%.*]] = fmul reassoc nnan ninf nsz arcp afn <2 x 
float> [[TMP1]], [[N]]
+// CHECK-NEXT:[[SUB_I:%.*]] = fsub reassoc nnan ninf nsz arcp afn <2 x 
float> [[I]], [[MUL1_I]]
+// CHECK-NEXT:ret <2 x float> [[SUB_I]]
+//
+// SPVCHECK-LABEL: define spir_func noundef nofpclass(nan inf) <2 x float> 
@_Z19test_refract_float2Dv2_fS_(
+// SPVCHECK-SAME: <2 x float> noundef nofpclass(nan inf) [[I:%.*]], <2 x 
float> noundef nofpclass(nan inf) [[N:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// SPVCHECK-NEXT:  [[ENTRY:.*:]]
+// SPVCHECK-NEXT:[[SPV_refract_I:%.*]] = tail call reassoc nnan ninf nsz 
arcp afn noundef <2 x float> @llvm.spv.refract.v2f32(<2 x float> [[I]], <2 x 
float> [[N]])
+// SPVCHECK-NEXT:ret <2 x float> [[SPV_refract_I]]
+//
+float2 test_refract_float2(float2 I, float2 N, float eta) {
+return refract(I, N, eta);
+}
+
+// CHECK-LABEL: define noundef nofpclass(nan inf) <3 x float> 
@_Z19test_refract_float3Dv3_fS_(
+// CHECK-SAME: <3 x float> noundef nofpclass(nan inf) [[I:%.*]], <3 x float> 
noundef nofpclass(nan inf) [[N:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[HLSL_DOT_I:%.*]] = tail call reassoc nnan ninf ns

[clang] [C] Add -Wjump-bypasses-init (PR #138009)

2025-05-01 Thread Shafik Yaghmour via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=c,both -Wjump-bypasses-init %s
+// RUN: %clang_cc1 -fsyntax-only -verify=c,both -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only -verify=good %s
+// RUN: %clang_cc1 -fsyntax-only -verify=cxx,both -x c++ %s
+// good-no-diagnostics
+
+void goto_func_1(void) {

shafik wrote:

Also:

```c
void f(void) {  

 for (int i=({ goto ouch; int x = 10; x;});i<0;++i)

ouch:
  ;
}
```

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


[clang] [C] Add -Wjump-bypasses-init (PR #138009)

2025-05-01 Thread Shafik Yaghmour via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=c,both -Wjump-bypasses-init %s
+// RUN: %clang_cc1 -fsyntax-only -verify=c,both -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only -verify=good %s
+// RUN: %clang_cc1 -fsyntax-only -verify=cxx,both -x c++ %s
+// good-no-diagnostics
+
+void goto_func_1(void) {

shafik wrote:

How about:

```c
void f(void) {  
  ({ 
goto ouch;  
int i = 12;
  });

ouch:
  ;
}
```

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


[clang] [lldb] [llvm] [mlir] [NFC][Support] Add llvm::uninitialized_copy (PR #138174)

2025-05-01 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/138174

>From fbe3ca0c2e4d195149f5e3e6b8d32797cf47b9df Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 30 Apr 2025 23:47:37 -0700
Subject: [PATCH] [NFC][Support] Add llvm::uninitialized_copy

Add `llvm::uninitialized_copy` that accepts a range instead of two
iterators for the source of the copy and adopt it.
---
 clang/include/clang/AST/DeclCXX.h |  6 +-
 clang/include/clang/AST/DeclOpenACC.h |  9 +--
 clang/include/clang/AST/ExprCXX.h |  6 +-
 clang/include/clang/AST/OpenACCClause.h   | 72 +++
 clang/include/clang/AST/StmtOpenACC.h | 54 +++---
 clang/include/clang/Sema/ParsedTemplate.h |  4 +-
 clang/lib/AST/Decl.cpp|  6 +-
 clang/lib/AST/DeclObjC.cpp|  4 +-
 clang/lib/AST/DeclTemplate.cpp| 11 ++-
 clang/lib/AST/Expr.cpp|  8 +--
 clang/lib/AST/ExprCXX.cpp | 16 ++---
 clang/lib/AST/OpenACCClause.cpp   | 13 ++--
 clang/lib/AST/StmtOpenACC.cpp |  4 +-
 clang/lib/AST/Type.cpp|  8 +--
 clang/tools/libclang/CXIndexDataConsumer.cpp  |  3 +-
 lldb/source/Utility/Checksum.cpp  |  4 +-
 llvm/include/llvm/ADT/ArrayRef.h  |  2 +-
 llvm/include/llvm/ADT/STLExtras.h |  5 ++
 llvm/lib/Analysis/ScalarEvolution.cpp | 10 +--
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp |  3 +-
 llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp   |  4 +-
 llvm/lib/DebugInfo/MSF/MSFBuilder.cpp |  6 +-
 llvm/lib/IR/AttributeImpl.h   |  2 +-
 llvm/lib/ObjectYAML/MinidumpEmitter.cpp   |  2 +-
 llvm/lib/Support/FoldingSet.cpp   |  4 +-
 .../AMDGPU/MCTargetDesc/AMDGPUMCExpr.cpp  |  2 +-
 llvm/lib/Transforms/IPO/LowerTypeTests.cpp|  7 +-
 .../unittests/Support/TrailingObjectsTest.cpp | 11 ++-
 mlir/include/mlir/IR/BuiltinAttributes.td |  2 +-
 mlir/include/mlir/Support/StorageUniquer.h|  4 +-
 .../Dialect/Affine/Analysis/NestedMatcher.cpp |  4 +-
 mlir/lib/IR/AffineMapDetail.h |  3 +-
 mlir/lib/IR/Location.cpp  |  8 +--
 mlir/lib/IR/MLIRContext.cpp   |  2 +-
 mlir/lib/IR/TypeDetail.h  |  3 +-
 mlir/lib/Tools/PDLL/AST/Nodes.cpp | 42 ---
 36 files changed, 153 insertions(+), 201 deletions(-)

diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index dd325815ee28d..20720115bf6c3 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -3861,8 +3861,7 @@ class UsingPackDecl final
   InstantiatedFrom ? InstantiatedFrom->getDeclName()
: DeclarationName()),
 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
-std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(UsingDecls, getTrailingObjects());
   }
 
   void anchor() override;
@@ -4233,8 +4232,7 @@ class DecompositionDecl final
   : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
 SC),
 NumBindings(Bindings.size()) {
-std::uninitialized_copy(Bindings.begin(), Bindings.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Bindings, getTrailingObjects());
 for (auto *B : Bindings) {
   B->setDecomposedDecl(this);
   if (B->isParameterPack() && B->getBinding()) {
diff --git a/clang/include/clang/AST/DeclOpenACC.h 
b/clang/include/clang/AST/DeclOpenACC.h
index 8c612fbf1ec07..905d9bf636ea1 100644
--- a/clang/include/clang/AST/DeclOpenACC.h
+++ b/clang/include/clang/AST/DeclOpenACC.h
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/OpenACCClause.h"
 #include "clang/Basic/OpenACCKinds.h"
+#include "llvm/ADT/STLExtras.h"
 
 namespace clang {
 
@@ -85,8 +86,8 @@ class OpenACCDeclareDecl final
   : OpenACCConstructDecl(OpenACCDeclare, DC, OpenACCDirectiveKind::Declare,
  StartLoc, DirLoc, EndLoc) {
 // Initialize the trailing storage.
-std::uninitialized_copy(Clauses.begin(), Clauses.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Clauses,
+ getTrailingObjects());
 
 setClauseList(MutableArrayRef(getTrailingObjects(),
   Clauses.size()));
@@ -136,8 +137,8 @@ class OpenACCRoutineDecl final
 assert(LParenLoc.isValid() &&
"Cannot represent implicit name with this declaration");
 // Initialize the trailing storage.
-std::uninitialized_copy(Clauses.begin(), Clauses.end(),
-getTrailingObjects());
+llvm::uninitialized_copy(Clauses,
+ getTrailingObj

[clang] [llvm] [HLSL][DXIL] Implement `refract` intrinsic (PR #136026)

2025-05-01 Thread via cfe-commits


@@ -69,6 +69,49 @@ bool SemaSPIRV::CheckSPIRVBuiltinFunctionCall(unsigned 
BuiltinID,
 TheCall->setType(RetTy);
 break;
   }
+  case SPIRV::BI__builtin_spirv_refract: {
+if (SemaRef.checkArgCount(TheCall, 3))
+  return true;
+
+ExprResult A = TheCall->getArg(0);
+QualType ArgTyA = A.get()->getType();
+auto *VTyA = ArgTyA->getAs();
+if (VTyA == nullptr) {
+  SemaRef.Diag(A.get()->getBeginLoc(),
+   diag::err_typecheck_convert_incompatible)
+  << ArgTyA
+  << SemaRef.Context.getVectorType(ArgTyA, 2, VectorKind::Generic) << 1
+  << 0 << 0;
+  return true;
+}
+
+ExprResult B = TheCall->getArg(1);
+QualType ArgTyB = B.get()->getType();
+auto *VTyB = ArgTyB->getAs();
+if (VTyB == nullptr) {
+  SemaRef.Diag(B.get()->getBeginLoc(),
+   diag::err_typecheck_convert_incompatible)
+  << ArgTyB
+  << SemaRef.Context.getVectorType(ArgTyB, 2, VectorKind::Generic) << 1
+  << 0 << 0;
+  return true;
+}
+
+ExprResult C = TheCall->getArg(2);
+QualType ArgTyC = C.get()->getType();
+if (!ArgTyC->hasFloatingRepresentation()) {
+  SemaRef.Diag(C.get()->getBeginLoc(),
+   diag::err_builtin_invalid_arg_type)
+  << 3 << /* scalar or vector */ 5 << /* no int */ 0 << /* fp */ 1
+  << ArgTyC;
+  return true;
+}
+
+QualType RetTy = ArgTyA;
+TheCall->setType(RetTy);
+assert(RetTy == ArgTyA);

raoanag wrote:

yes, this is remanent of some debugging that I was doing 

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


[clang] [C] Add -Wduplicate-decl-specifier to -Wc++-compat (PR #138012)

2025-05-01 Thread Shafik Yaghmour via cfe-commits


@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wduplicate-decl-specifier %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-duplicate-decl-specifier 
-Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only -verify=good -Wc++-compat 
-Wno-duplicate-decl-specifier %s
+// RUN: %clang_cc1 -fsyntax-only -verify=good -Wno-duplicate-decl-specifier %s
+// RUN: %clang_cc1 -fsyntax-only -verify -x c++ %s
+// good-no-diagnostics
+
+// Note: we treat this as a warning in C++, so you get the same diagnostics in
+// either language mode. However, GCC diagnoses this as an error, so the
+// compatibility warning has value.
+const const int i = 12; // expected-warning {{duplicate 'const' declaration 
specifier}}

shafik wrote:

`volatile const volatile const int x = 1;` might also be worth checking, to get 
in `volatile` and test that we catch alternating qualifies.

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


[clang] [CIR] Refactor global variable emission and initialization (PR #138222)

2025-05-01 Thread Andy Kaylor via cfe-commits

https://github.com/andykaylor created 
https://github.com/llvm/llvm-project/pull/138222

When global variable support was initially upstreamed, we took some shortcuts 
and only implemented the minimum support for simple variables and constant 
initializers.

This change refactors the code that creates global variables to introduce more 
of the complexities that are present in the incubator and the classic codegen. 
I can't really say this is NFC, because the code executed is very different and 
it will report different NYI diagnostics, but for the currently implemented 
cases, it results in the same output.

>From b3ae2d60a178f3c5bb8950804041386a667abc6e Mon Sep 17 00:00:00 2001
From: Andy Kaylor 
Date: Tue, 29 Apr 2025 15:47:01 -0700
Subject: [PATCH] [CIR] Refactor global variable emission and initialization

When global variable support was initially upstreamed, we took some
shortcuts and only implemented the minimum support for simple variables
and constant initializers.

This change refactors the code that creates global variables to introduce
more of the complexities that are present in the incubator and the classic
codegen. I can't really say this is NFC, because the code executed is very
different and it will report different NYI diagnostics, but for the
currently implemented cases, it results in the same output.
---
 clang/include/clang/CIR/MissingFeatures.h |   6 +
 clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h |  36 +++-
 clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp  | 137 +-
 clang/lib/CIR/CodeGen/CIRGenModule.cpp| 174 ++
 clang/lib/CIR/CodeGen/CIRGenModule.h  |   6 +
 5 files changed, 320 insertions(+), 39 deletions(-)

diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 4d4951aa0e126..3a6b1874581e7 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -36,6 +36,8 @@ struct MissingFeatures {
   static bool opGlobalConstant() { return false; }
   static bool opGlobalAlignment() { return false; }
   static bool opGlobalWeakRef() { return false; }
+  static bool opGlobalLinkage() { return false; }
+  static bool opGlobalSetVisitibility() { return false; }
 
   static bool supportIFuncAttr() { return false; }
   static bool supportVisibility() { return false; }
@@ -163,6 +165,10 @@ struct MissingFeatures {
   static bool setDSOLocal() { return false; }
   static bool foldCaseStmt() { return false; }
   static bool constantFoldSwitchStatement() { return false; }
+  static bool cudaSupport() { return false; }
+  static bool maybeHandleStaticInExternC() { return false; }
+  static bool constEmitterArrayILE() { return false; }
+  static bool constEmitterVectorILE() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h 
b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
index ca4e607992bbc..54c3710690ef1 100644
--- a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
+++ b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
@@ -31,6 +31,15 @@ class ConstantEmitter {
 private:
   bool abstract = false;
 
+  /// Whether non-abstract components of the emitter have been initialized.
+  bool initializedNonAbstract = false;
+
+  /// Whether the emitter has been finalized.
+  bool finalized = false;
+
+  /// Whether the constant-emission failed.
+  bool failed = false;
+
   /// Whether we're in a constant context.
   bool inConstantContext = false;
 
@@ -46,6 +55,14 @@ class ConstantEmitter {
   ConstantEmitter(const ConstantEmitter &other) = delete;
   ConstantEmitter &operator=(const ConstantEmitter &other) = delete;
 
+  ~ConstantEmitter();
+
+  /// Try to emit the initiaizer of the given declaration as an abstract
+  /// constant.  If this succeeds, the emission must be finalized.
+  mlir::Attribute tryEmitForInitializer(const VarDecl &d);
+
+  void finalize(cir::GlobalOp gv);
+
   // All of the "abstract" emission methods below permit the emission to
   // be immediately discarded without finalizing anything.  Therefore, they
   // must also promise not to do anything that will, in the future, require
@@ -61,6 +78,10 @@ class ConstantEmitter {
   // reference to its current location.
   mlir::Attribute emitForMemory(mlir::Attribute c, QualType t);
 
+  /// Try to emit the initializer of the given declaration as an abstract
+  /// constant.
+  mlir::Attribute tryEmitAbstractForInitializer(const VarDecl &d);
+
   /// Emit the result of the given expression as an abstract constant,
   /// asserting that it succeeded.  This is only safe to do when the
   /// expression is known to be a constant expression with either a fairly
@@ -79,11 +100,18 @@ class ConstantEmitter {
   mlir::Attribute tryEmitPrivate(const APValue &value, QualType destType);
   mlir::Attribute tryEmitPrivateForMemory(const APValue &value, QualType t);
 
-  /// Try to emit the initializer of the given dec

[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Sarah Spall via cfe-commits


@@ -303,6 +303,48 @@ fmod(__detail::HLSL_FIXED_VECTOR X,
   return __detail::fmod_vec_impl(X, Y);
 }
 
+//===--===//
+// ldexp builtins
+//===--===//
+
+/// \fn T ldexp(T X, T Exp)
+/// \brief Returns the result of multiplying the specified value by two, raised

spall wrote:

I think the comma after two changes the meaning of this. To me this reads as (X 
* 2) ^ exp. 
I would remove the comma.

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


[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Sarah Spall via cfe-commits


@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.6-library %s -fnative-half-type -emit-llvm-only 
-disable-llvm-passes -verify
+
+float test_double_inputs(double p0, double p1) {
+  return ldexp(p0, p1);
+  // expected-error@-1  {{no matching function for call to 'ldexp'}}
+  // expected-note@hlsl/hlsl_intrinsics.h:* {{candidate template ignored}}

spall wrote:

is it worth including these notes in these tests? They don't seem valuable to 
me, and can be excluded with -verify-ignore-unexpected=note

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


[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Sarah Spall via cfe-commits


@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -finclude-default-header -x hlsl -triple 
dxil-pc-shadermodel6.3-library %s -fnative-half-type -emit-llvm 
-disable-llvm-passes -o - | FileCheck %s

spall wrote:

A lot of the builtins that support half and float have tests with native half 
and without native half.
See: 
https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGenHLSL/builtins/cos.hlsl
Should we do that here? 

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


[clang] [CIR] Refactor global variable emission and initialization (PR #138222)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andy Kaylor (andykaylor)


Changes

When global variable support was initially upstreamed, we took some shortcuts 
and only implemented the minimum support for simple variables and constant 
initializers.

This change refactors the code that creates global variables to introduce more 
of the complexities that are present in the incubator and the classic codegen. 
I can't really say this is NFC, because the code executed is very different and 
it will report different NYI diagnostics, but for the currently implemented 
cases, it results in the same output.

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


5 Files Affected:

- (modified) clang/include/clang/CIR/MissingFeatures.h (+6) 
- (modified) clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h (+32-4) 
- (modified) clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp (+134-3) 
- (modified) clang/lib/CIR/CodeGen/CIRGenModule.cpp (+142-32) 
- (modified) clang/lib/CIR/CodeGen/CIRGenModule.h (+6) 


``diff
diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 4d4951aa0e126..3a6b1874581e7 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -36,6 +36,8 @@ struct MissingFeatures {
   static bool opGlobalConstant() { return false; }
   static bool opGlobalAlignment() { return false; }
   static bool opGlobalWeakRef() { return false; }
+  static bool opGlobalLinkage() { return false; }
+  static bool opGlobalSetVisitibility() { return false; }
 
   static bool supportIFuncAttr() { return false; }
   static bool supportVisibility() { return false; }
@@ -163,6 +165,10 @@ struct MissingFeatures {
   static bool setDSOLocal() { return false; }
   static bool foldCaseStmt() { return false; }
   static bool constantFoldSwitchStatement() { return false; }
+  static bool cudaSupport() { return false; }
+  static bool maybeHandleStaticInExternC() { return false; }
+  static bool constEmitterArrayILE() { return false; }
+  static bool constEmitterVectorILE() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h 
b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
index ca4e607992bbc..54c3710690ef1 100644
--- a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
+++ b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
@@ -31,6 +31,15 @@ class ConstantEmitter {
 private:
   bool abstract = false;
 
+  /// Whether non-abstract components of the emitter have been initialized.
+  bool initializedNonAbstract = false;
+
+  /// Whether the emitter has been finalized.
+  bool finalized = false;
+
+  /// Whether the constant-emission failed.
+  bool failed = false;
+
   /// Whether we're in a constant context.
   bool inConstantContext = false;
 
@@ -46,6 +55,14 @@ class ConstantEmitter {
   ConstantEmitter(const ConstantEmitter &other) = delete;
   ConstantEmitter &operator=(const ConstantEmitter &other) = delete;
 
+  ~ConstantEmitter();
+
+  /// Try to emit the initiaizer of the given declaration as an abstract
+  /// constant.  If this succeeds, the emission must be finalized.
+  mlir::Attribute tryEmitForInitializer(const VarDecl &d);
+
+  void finalize(cir::GlobalOp gv);
+
   // All of the "abstract" emission methods below permit the emission to
   // be immediately discarded without finalizing anything.  Therefore, they
   // must also promise not to do anything that will, in the future, require
@@ -61,6 +78,10 @@ class ConstantEmitter {
   // reference to its current location.
   mlir::Attribute emitForMemory(mlir::Attribute c, QualType t);
 
+  /// Try to emit the initializer of the given declaration as an abstract
+  /// constant.
+  mlir::Attribute tryEmitAbstractForInitializer(const VarDecl &d);
+
   /// Emit the result of the given expression as an abstract constant,
   /// asserting that it succeeded.  This is only safe to do when the
   /// expression is known to be a constant expression with either a fairly
@@ -79,11 +100,18 @@ class ConstantEmitter {
   mlir::Attribute tryEmitPrivate(const APValue &value, QualType destType);
   mlir::Attribute tryEmitPrivateForMemory(const APValue &value, QualType t);
 
-  /// Try to emit the initializer of the given declaration as an abstract
-  /// constant.
-  mlir::Attribute tryEmitAbstractForInitializer(const VarDecl &d);
-
 private:
+  void initializeNonAbstract() {
+assert(!initializedNonAbstract);
+initializedNonAbstract = true;
+assert(!cir::MissingFeatures::addressSpace());
+  }
+  mlir::Attribute markIfFailed(mlir::Attribute init) {
+if (!init)
+  failed = true;
+return init;
+  }
+
   class AbstractStateRAII {
 ConstantEmitter &emitter;
 bool oldValue;
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
index 6e5c7b8fb51f8..ca718677d7442 100644
--- a/clang/lib/CIR/CodeGen/CIRGen

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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -948,6 +950,165 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+// Handle the case where the condition is a constant evaluatable simple 
integer,
+// which means we don't have to separately handle the true/false blocks.
+static std::optional handleConditionalOperatorLValueSimpleCase(
+CIRGenFunction &cgf, const AbstractConditionalOperator *e) {
+  const Expr *condExpr = e->getCond();
+  bool condExprBool = false;
+  if (cgf.constantFoldsToSimpleInteger(condExpr, condExprBool)) {
+const Expr *live = e->getTrueExpr(), *dead = e->getFalseExpr();
+if (!condExprBool)
+  std::swap(live, dead);
+
+if (!cgf.containsLabel(dead)) {
+  // If the true case is live, we need to track its region.
+  if (condExprBool) {
+assert(!cir::MissingFeatures::incrementProfileCounter());
+  }
+  // If a throw expression we emit it and return an undefined lvalue
+  // because it can't be used.
+  if (isa(live->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(live->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+  return cgf.emitLValue(live);
+}
+  }
+  return std::nullopt;
+}
+
+/// Emit the operand of a glvalue conditional operator. This is either a 
glvalue
+/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
+/// LValue is returned and the current block has been terminated.
+static std::optional emitLValueOrThrowExpression(CIRGenFunction &cgf,
+ const Expr *operand) {
+  if (isa(operand->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(operand->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+
+  return cgf.emitLValue(operand);
+}
+
+// Create and generate the 3 blocks for a conditional operator.
+// Leaves the 'current block' in the continuation basic block.
+template 
+CIRGenFunction::ConditionalInfo
+CIRGenFunction::emitConditionalBlocks(const AbstractConditionalOperator *e,
+  const FuncTy &branchGenFunc) {
+  ConditionalInfo info;
+  CIRGenFunction &cgf = *this;
+  ConditionalEvaluation eval(cgf);
+  mlir::Location loc = cgf.getLoc(e->getSourceRange());
+  CIRGenBuilderTy &builder = cgf.getBuilder();
+  Expr *trueExpr = e->getTrueExpr();
+  Expr *falseExpr = e->getFalseExpr();
+
+  mlir::Value condV = cgf.emitOpOnBoolExpr(loc, e->getCond());
+  SmallVector insertPoints{};
+  mlir::Type yieldTy{};
+
+  auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc, Expr *expr,
+std::optional &branchInfo) {
+CIRGenFunction::LexicalScope lexScope{cgf, loc, b.getInsertionBlock()};
+cgf.curLexScope->setAsTernary();
+
+assert(!cir::MissingFeatures::incrementProfileCounter());
+eval.begin(cgf);
+branchInfo = branchGenFunc(cgf, expr);
+mlir::Value branch = branchInfo->getPointer();
+eval.end(cgf);
+
+if (branch) {
+  yieldTy = branch.getType();
+  b.create(loc, branch);
+} else {
+  // If LHS or RHS is a throw or void expression we need to patch
+  // arms as to properly match yield types.
+  insertPoints.push_back(b.saveInsertionPoint());
+}
+  };
+
+  info.result = builder
+.create(
+loc, condV, /*trueBuilder=*/
+[&](mlir::OpBuilder &b, mlir::Location loc) {
+  emitBranch(b, loc, trueExpr, info.lhs);
+},
+/*falseBuilder=*/
+[&](mlir::OpBuilder &b, mlir::Location loc) {
+  emitBranch(b, loc, falseExpr, info.rhs);
+})
+.getResult();
+
+  if (!insertPoints.empty()) {
+// If both arms are void, so be it.
+if (!yieldTy)
+  yieldTy = cgf.VoidTy;
+
+// Insert required yields.
+for (mlir::OpBuilder::InsertPoint &toInsert : insertPoints) {
+  mlir::OpBuilder::InsertionGuard guard(builder);
+  builder.restoreInsertionPoint(toInsert);
+
+  // Block does not return: build empty yield.
+  if (mlir::isa(yieldTy)) {
+builder.create(loc);
+  } else { // Block returns: set null yield value.
+mlir::Value op0 = builder.getNullValue(yieldTy, loc);

andykaylor wrote:

I don't think this is right. If a block contains a throw, the incubator 
generates a `cir.throw` followed by a `cir.unreachable` and then inserts a null 
constant and a `cir.yield`. This causes verification to fail because 
`cir.unreachable` isn't the last operation in the block.

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

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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -642,12 +798,97 @@ class CIRGenFunction : public CIRGenTypeCache {
   void emitNullabilityCheck(LValue lhs, mlir::Value rhs,
 clang::SourceLocation loc);
 
+  /// An object to manage conditionally-evaluated expressions.
+  class ConditionalEvaluation {
+mlir::OpBuilder::InsertPoint insertPt;
+
+  public:
+ConditionalEvaluation(CIRGenFunction &cgf)
+: insertPt(cgf.builder.saveInsertionPoint()) {}
+ConditionalEvaluation(mlir::OpBuilder::InsertPoint ip) : insertPt(ip) {}
+
+void begin(CIRGenFunction &cgf) {

andykaylor wrote:

If we saved a reference to `cgf` in the constructor, we wouldn't need to pass 
it to `begin()` and `end()`

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


[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Deric C. via cfe-commits


@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.6-library %s -fnative-half-type -emit-llvm-only 
-disable-llvm-passes -verify
+
+float test_double_inputs(double p0, double p1) {
+  return ldexp(p0, p1);
+  // expected-error@-1  {{no matching function for call to 'ldexp'}}
+  // expected-note@hlsl/hlsl_intrinsics.h:* {{candidate template ignored}}

Icohedron wrote:

Yea the notes don't seem worthwhile to include. They're more distracting than 
anything useful. Plus, I don't see any other tests checking for notes.

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


[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Deric C. via cfe-commits


@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -finclude-default-header -x hlsl -triple 
dxil-pc-shadermodel6.3-library %s -fnative-half-type -emit-llvm 
-disable-llvm-passes -o - | FileCheck %s

Icohedron wrote:

Yea, to be consistent if nothing else.

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


[clang] [HLSL] Implement the `ldexp` intrinsic (PR #138182)

2025-05-01 Thread Deric C. via cfe-commits

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

@spall pointed out some good changes that should be made

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -948,6 +950,165 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+// Handle the case where the condition is a constant evaluatable simple 
integer,
+// which means we don't have to separately handle the true/false blocks.
+static std::optional handleConditionalOperatorLValueSimpleCase(
+CIRGenFunction &cgf, const AbstractConditionalOperator *e) {
+  const Expr *condExpr = e->getCond();
+  bool condExprBool = false;
+  if (cgf.constantFoldsToSimpleInteger(condExpr, condExprBool)) {
+const Expr *live = e->getTrueExpr(), *dead = e->getFalseExpr();
+if (!condExprBool)
+  std::swap(live, dead);
+
+if (!cgf.containsLabel(dead)) {
+  // If the true case is live, we need to track its region.
+  if (condExprBool) {
+assert(!cir::MissingFeatures::incrementProfileCounter());
+  }
+  // If a throw expression we emit it and return an undefined lvalue
+  // because it can't be used.
+  if (isa(live->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(live->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+  return cgf.emitLValue(live);
+}
+  }
+  return std::nullopt;
+}
+
+/// Emit the operand of a glvalue conditional operator. This is either a 
glvalue
+/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
+/// LValue is returned and the current block has been terminated.
+static std::optional emitLValueOrThrowExpression(CIRGenFunction &cgf,
+ const Expr *operand) {
+  if (isa(operand->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(operand->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+
+  return cgf.emitLValue(operand);
+}
+
+// Create and generate the 3 blocks for a conditional operator.
+// Leaves the 'current block' in the continuation basic block.
+template 
+CIRGenFunction::ConditionalInfo
+CIRGenFunction::emitConditionalBlocks(const AbstractConditionalOperator *e,
+  const FuncTy &branchGenFunc) {
+  ConditionalInfo info;
+  CIRGenFunction &cgf = *this;
+  ConditionalEvaluation eval(cgf);
+  mlir::Location loc = cgf.getLoc(e->getSourceRange());
+  CIRGenBuilderTy &builder = cgf.getBuilder();
+  Expr *trueExpr = e->getTrueExpr();
+  Expr *falseExpr = e->getFalseExpr();
+
+  mlir::Value condV = cgf.emitOpOnBoolExpr(loc, e->getCond());
+  SmallVector insertPoints{};
+  mlir::Type yieldTy{};
+
+  auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc, Expr *expr,
+std::optional &branchInfo) {
+CIRGenFunction::LexicalScope lexScope{cgf, loc, b.getInsertionBlock()};
+cgf.curLexScope->setAsTernary();
+
+assert(!cir::MissingFeatures::incrementProfileCounter());
+eval.begin(cgf);
+branchInfo = branchGenFunc(cgf, expr);
+mlir::Value branch = branchInfo->getPointer();
+eval.end(cgf);
+
+if (branch) {
+  yieldTy = branch.getType();
+  b.create(loc, branch);
+} else {
+  // If LHS or RHS is a throw or void expression we need to patch
+  // arms as to properly match yield types.
+  insertPoints.push_back(b.saveInsertionPoint());
+}
+  };
+
+  info.result = builder
+.create(
+loc, condV, /*trueBuilder=*/
+[&](mlir::OpBuilder &b, mlir::Location loc) {
+  emitBranch(b, loc, trueExpr, info.lhs);
+},
+/*falseBuilder=*/
+[&](mlir::OpBuilder &b, mlir::Location loc) {
+  emitBranch(b, loc, falseExpr, info.rhs);
+})
+.getResult();
+
+  if (!insertPoints.empty()) {
+// If both arms are void, so be it.
+if (!yieldTy)
+  yieldTy = cgf.VoidTy;
+
+// Insert required yields.
+for (mlir::OpBuilder::InsertPoint &toInsert : insertPoints) {
+  mlir::OpBuilder::InsertionGuard guard(builder);
+  builder.restoreInsertionPoint(toInsert);
+
+  // Block does not return: build empty yield.
+  if (mlir::isa(yieldTy)) {
+builder.create(loc);
+  } else { // Block returns: set null yield value.
+mlir::Value op0 = builder.getNullValue(yieldTy, loc);
+builder.create(loc, op0);
+  }
+}
+  }
+  return info;
+}
+
+LValue CIRGenFunction::emitConditionalOperatorLValue(

andykaylor wrote:

It doesn't look like this is called from anywhere in this patch. In the 
incubator, it is called from emitLValue(), and the fact that you didn't need 
that here makes me suspect this is entirely duplicated somewhere else (maybe in 
the VisitAbstractConditionalOperator implementation?).

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

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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -272,6 +272,22 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
 return createCast(loc, cir::CastKind::bitcast, src, newTy);
   }
 
+  // TODO(cir): the following function was introduced to keep in sync with LLVM

andykaylor wrote:

This probably made sense when the incubator was in the early stages of 
development, but I don't think there's much value in staying structurally in 
sync with classic codegen when the CIR implementation is doing something 
entirely different. The "eventually" in the comment should be now. However, we 
should probably leave a bread crumb so anyone upstreaming code that calls this 
function can easily figure out what we did with it.

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -1658,6 +1828,170 @@ mlir::Value 
ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
cgf.cgm.UInt64Ty, e->EvaluateKnownConstInt(cgf.getContext(;
 }
 
+/// Return true if the specified expression is cheap enough and 
side-effect-free
+/// enough to evaluate unconditionally instead of conditionally.  This is used
+/// to convert control flow into selects in some cases.
+/// TODO(cir): can be shared with LLVM codegen.
+static bool isCheapEnoughToEvaluateUnconditionally(const Expr *e,
+   CIRGenFunction &cgf) {
+  // Anything that is an integer or floating point constant is fine.
+  return e->IgnoreParens()->isEvaluatable(cgf.getContext());

andykaylor wrote:

We wouldn't want to speculatively evaluate constant foldable floating point 
expressions if they might raise an exception. I don't think this handles that 
correctly. We are a long way from having strict floating-point semantics in 
CIR, but the classic codegen gets this wrong: https://godbolt.org/z/nvfT4WxK4

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -948,6 +950,165 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+// Handle the case where the condition is a constant evaluatable simple 
integer,
+// which means we don't have to separately handle the true/false blocks.
+static std::optional handleConditionalOperatorLValueSimpleCase(
+CIRGenFunction &cgf, const AbstractConditionalOperator *e) {
+  const Expr *condExpr = e->getCond();
+  bool condExprBool = false;
+  if (cgf.constantFoldsToSimpleInteger(condExpr, condExprBool)) {
+const Expr *live = e->getTrueExpr(), *dead = e->getFalseExpr();
+if (!condExprBool)
+  std::swap(live, dead);
+
+if (!cgf.containsLabel(dead)) {
+  // If the true case is live, we need to track its region.
+  if (condExprBool) {
+assert(!cir::MissingFeatures::incrementProfileCounter());
+  }
+  // If a throw expression we emit it and return an undefined lvalue
+  // because it can't be used.
+  if (isa(live->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(live->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+  return cgf.emitLValue(live);
+}
+  }
+  return std::nullopt;
+}
+
+/// Emit the operand of a glvalue conditional operator. This is either a 
glvalue
+/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
+/// LValue is returned and the current block has been terminated.
+static std::optional emitLValueOrThrowExpression(CIRGenFunction &cgf,
+ const Expr *operand) {
+  if (isa(operand->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(operand->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+
+  return cgf.emitLValue(operand);
+}
+
+// Create and generate the 3 blocks for a conditional operator.
+// Leaves the 'current block' in the continuation basic block.
+template 
+CIRGenFunction::ConditionalInfo
+CIRGenFunction::emitConditionalBlocks(const AbstractConditionalOperator *e,
+  const FuncTy &branchGenFunc) {
+  ConditionalInfo info;
+  CIRGenFunction &cgf = *this;
+  ConditionalEvaluation eval(cgf);
+  mlir::Location loc = cgf.getLoc(e->getSourceRange());
+  CIRGenBuilderTy &builder = cgf.getBuilder();

andykaylor wrote:

The use of `cgf` throughout this function is odd. In the classic codegen it was 
a standalone function that took `CGF` as a parameter, but since it's a member 
function here, there's no reason to do that. Also, `builder` here is shadowing 
the `builder` member variable in `CIRGenFunction`.

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -875,6 +877,174 @@ class ScalarExprEmitter : public 
StmtVisitor {
 // NOTE: We don't need to EnsureInsertPoint() like LLVM codegen.
 return Visit(e->getRHS());
   }
+
+  mlir::Value VisitBinLAnd(const clang::BinaryOperator *e) {
+if (e->getType()->isVectorType()) {
+  assert(!cir::MissingFeatures::vectorType());
+  return {};
+}
+
+bool instrumentRegions = cgf.cgm.getCodeGenOpts().hasProfileClangInstr();
+mlir::Type resTy = cgf.convertType(e->getType());
+mlir::Location loc = cgf.getLoc(e->getExprLoc());
+
+// If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
+// If we have 1 && X, just emit X without inserting the control flow.
+bool lhsCondVal;
+if (cgf.constantFoldsToSimpleInteger(e->getLHS(), lhsCondVal)) {

andykaylor wrote:

It feels like we have code the code to check for this folding and then create a 
ternary op in a lot of places. Is there no way to reduce the duplication?

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits

https://github.com/andykaylor commented:

Could you break this up a bit more? Maybe cut it back to just the code needed 
for the logical operators?

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -948,6 +950,165 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+// Handle the case where the condition is a constant evaluatable simple 
integer,
+// which means we don't have to separately handle the true/false blocks.
+static std::optional handleConditionalOperatorLValueSimpleCase(

andykaylor wrote:

This is another of those cases where we're doing optimization in the front end. 
This has come up several times. I personally don't like the idea, but I guess 
the classic codegen does things like this.

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits

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


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

2025-05-01 Thread Andy Kaylor via cfe-commits


@@ -948,6 +950,165 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+// Handle the case where the condition is a constant evaluatable simple 
integer,
+// which means we don't have to separately handle the true/false blocks.
+static std::optional handleConditionalOperatorLValueSimpleCase(
+CIRGenFunction &cgf, const AbstractConditionalOperator *e) {
+  const Expr *condExpr = e->getCond();
+  bool condExprBool;
+  if (cgf.constantFoldsToSimpleInteger(condExpr, condExprBool)) {
+const Expr *live = e->getTrueExpr(), *dead = e->getFalseExpr();
+if (!condExprBool)
+  std::swap(live, dead);
+
+if (!cgf.containsLabel(dead)) {
+  // If the true case is live, we need to track its region.
+  if (condExprBool) {
+assert(!cir::MissingFeatures::incrementProfileCounter());
+  }
+  // If a throw expression we emit it and return an undefined lvalue
+  // because it can't be used.
+  if (isa(live->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(live->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+  return cgf.emitLValue(live);
+}
+  }
+  return std::nullopt;
+}
+
+/// Emit the operand of a glvalue conditional operator. This is either a 
glvalue
+/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
+/// LValue is returned and the current block has been terminated.
+static std::optional emitLValueOrThrowExpression(CIRGenFunction &cgf,
+ const Expr *operand) {
+  if (isa(operand->IgnoreParens())) {
+assert(!cir::MissingFeatures::throwOp());
+cgf.cgm.errorNYI(operand->getSourceRange(),
+ "throw expressions in conditional operator");
+return std::nullopt;
+  }
+
+  return cgf.emitLValue(operand);
+}
+
+// Create and generate the 3 blocks for a conditional operator.
+// Leaves the 'current block' in the continuation basic block.
+template 
+CIRGenFunction::ConditionalInfo
+CIRGenFunction::emitConditionalBlocks(const AbstractConditionalOperator *e,
+  const FuncTy &branchGenFunc) {
+  ConditionalInfo info;
+  CIRGenFunction &cgf = *this;
+  ConditionalEvaluation eval(cgf);
+  mlir::Location loc = cgf.getLoc(e->getSourceRange());
+  CIRGenBuilderTy &builder = cgf.getBuilder();
+  Expr *trueExpr = e->getTrueExpr();
+  Expr *falseExpr = e->getFalseExpr();
+
+  mlir::Value condV = cgf.emitOpOnBoolExpr(loc, e->getCond());
+  SmallVector insertPoints{};
+  mlir::Type yieldTy{};
+
+  auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc, Expr *expr,

andykaylor wrote:

I think the incubator code patches up the region as part of the ternary 
operation creation. Is it possible that doing it after could cause a 
verification failure?

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


[clang] [clang-format] Add AlignAfterOpenBracketOptions (PR #108332)

2025-05-01 Thread Gedare Bloom via cfe-commits

gedare wrote:

> Why would `AlignAfterControlStatement` have anything to do with 
> `AlignAfterOpenBracket`, which is for arguments of function/macro calls?
> 

Unfortunately, `AlignAfterOpenBracket` is not just for arguments of 
function/macro calls. It affects parentheses of control statements already, at 
least in some regard: https://github.com/llvm/llvm-project/pull/77699

We could certainly make the distinction between breaking and alignment more 
explicit, as mentioned at https://github.com/llvm/llvm-project/issues/80049

That's really what this PR is doing, it is adding an option to break the start 
of the control expression. The alignment gets inherited from the 
`AlignAfterOpenBracket`. I guess another possiblity is to call this 
`AlignAfterControlStatement` and make the `AlignAfterOpenBracket` really only 
for functions/macros. 

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


[clang] 1b1e360 - [NFC][clang] No sharedlibs for UEFI (#137872)

2025-05-01 Thread via cfe-commits

Author: Prabhu Rajasekaran
Date: 2025-05-01T15:49:32-07:00
New Revision: 1b1e360b76d31fcd09b93b8c05be8a93dfea432b

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

LOG: [NFC][clang] No sharedlibs for UEFI (#137872)

There is no support for shared libraries for UEFI target. Remove the
incorrect -dll flag set from UEFI toolchain.

Added: 


Modified: 
clang/lib/Driver/ToolChains/UEFI.cpp
clang/test/Driver/uefi-constructed-args.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/UEFI.cpp 
b/clang/lib/Driver/ToolChains/UEFI.cpp
index a9d7e7892c5a6..fbef72e34a3b1 100644
--- a/clang/lib/Driver/ToolChains/UEFI.cpp
+++ b/clang/lib/Driver/ToolChains/UEFI.cpp
@@ -80,9 +80,6 @@ void tools::uefi::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   // "Terminal Service Aware" flag is not needed for UEFI applications.
   CmdArgs.push_back("-tsaware:no");
 
-  // EFI_APPLICATION to be linked as DLL by default.
-  CmdArgs.push_back("-dll");
-
   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
 CmdArgs.push_back("-debug");
 

diff  --git a/clang/test/Driver/uefi-constructed-args.c 
b/clang/test/Driver/uefi-constructed-args.c
index 44d2271e0c8ba..49ede47a8953e 100644
--- a/clang/test/Driver/uefi-constructed-args.c
+++ b/clang/test/Driver/uefi-constructed-args.c
@@ -11,5 +11,4 @@
 // CHECK-SAME: "-subsystem:efi_application"
 // CHECK-SAME: "-entry:EfiMain"
 // CHECK-SAME: "-tsaware:no"
-// CHECK-SAME: "-dll"
 // CHECK-SAME: "-debug"



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


[clang] [NFC][clang] No sharedlibs for UEFI (PR #137872)

2025-05-01 Thread Prabhu Rajasekaran via cfe-commits

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


[clang] [C] Add -Wjump-bypasses-init (PR #138009)

2025-05-01 Thread Shafik Yaghmour via cfe-commits


@@ -6561,18 +6561,28 @@ def ext_goto_into_protected_scope : ExtWarn<
 def warn_cxx98_compat_goto_into_protected_scope : Warning<
   "jump from this goto statement to its label is incompatible with C++98">,
   InGroup, DefaultIgnore;
+def warn_cpp_compat_goto_into_protected_scope : Warning<

shafik wrote:

It looks like this diagnostic and the last one are not covered in the test.

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


[clang] [clang][lex] Fix lexing malformed pragma within include directive (PR #138165)

2025-05-01 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/Lex/Pragma.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp
index 607e7b6a7..ea7eda0d0 100644
--- a/clang/lib/Lex/Pragma.cpp
+++ b/clang/lib/Lex/Pragma.cpp
@@ -222,10 +222,8 @@ void Preprocessor::Handle_Pragma(Token &Tok) {
 // Skip bad tokens, and the ')', if present.
 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
   Lex(Tok);
-while (Tok.isNot(tok::r_paren) &&
-   !Tok.isAtStartOfLine() &&
-   Tok.isNot(tok::eof) &&
-   Tok.isNot(tok::eod))
+while (Tok.isNot(tok::r_paren) && !Tok.isAtStartOfLine() &&
+   Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
   Lex(Tok);
 if (Tok.is(tok::r_paren))
   Lex(Tok);

``




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


[clang] [clang][lex] Fix lexing malformed pragma within include directive (PR #138165)

2025-05-01 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

Thank you for the fix, this needs a test and release note. 

Release notes for clang are in `clang/docs/ReleaseNotes.rst`.

I am not sure what the right file for testing is though @AaronBallman 

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


[clang] [libclang/python] Add tests for equality operators. (PR #138132)

2025-05-01 Thread Jannick Kremer via cfe-commits

https://github.com/DeinAlptraum updated 
https://github.com/llvm/llvm-project/pull/138132

>From 74cf17d76918c465aa24e391e15546ab030483f2 Mon Sep 17 00:00:00 2001
From: Jannick Kremer 
Date: Thu, 1 May 2025 22:42:56 +0900
Subject: [PATCH 1/2] [libclang/python] Add tests for equality operators.

Adds tests for SourceRange, SourceLocation and Cursor.
This is a follow-up to #138074
---
 .../python/tests/cindex/test_cursor.py| 15 ++
 .../python/tests/cindex/test_location.py  | 20 +++
 .../python/tests/cindex/test_source_range.py  | 15 ++
 3 files changed, 50 insertions(+)

diff --git a/clang/bindings/python/tests/cindex/test_cursor.py 
b/clang/bindings/python/tests/cindex/test_cursor.py
index 82f40c60afa59..b90a0495ca7be 100644
--- a/clang/bindings/python/tests/cindex/test_cursor.py
+++ b/clang/bindings/python/tests/cindex/test_cursor.py
@@ -1035,3 +1035,18 @@ def test_specialized_template(self):
 self.assertNotEqual(foos[0], foos[1])
 self.assertEqual(foos[0], prime_foo)
 self.assertIsNone(tu.cursor.specialized_template)
+
+def test_equality(self):
+tu = get_tu(CHILDREN_TEST, lang="cpp")
+cursor1 = get_cursor(tu, "s0")
+cursor1_2 = get_cursor(tu, "s0")
+cursor2 = get_cursor(tu, "f0")
+
+self.assertIsNotNone(cursor1)
+self.assertIsNotNone(cursor1_2)
+self.assertIsNotNone(cursor2)
+
+self.assertEqual(cursor1, cursor1)
+self.assertEqual(cursor1, cursor1_2)
+self.assertNotEqual(cursor1, cursor2)
+self.assertNotEqual(cursor1, "foo")
diff --git a/clang/bindings/python/tests/cindex/test_location.py 
b/clang/bindings/python/tests/cindex/test_location.py
index 21c6169bb0a6f..f1a4589738f52 100644
--- a/clang/bindings/python/tests/cindex/test_location.py
+++ b/clang/bindings/python/tests/cindex/test_location.py
@@ -16,6 +16,8 @@
 
 from .util import get_cursor, get_tu
 
+INPUTS_DIR = os.path.join(os.path.dirname(__file__), "INPUTS")
+
 BASE_INPUT = "int one;\nint two;\n"
 
 
@@ -151,3 +153,21 @@ def test_operator_lt(self):
 assert l_t1_12 < l_t2_13 < l_t1_14
 assert not l_t2_13 < l_t1_12
 assert not l_t1_14 < l_t2_13
+
+def test_equality(self):
+path = os.path.join(INPUTS_DIR, "testfile.c")
+path_a = os.path.join(INPUTS_DIR, "a.inc")
+tu = TranslationUnit.from_source(path)
+main_file = File.from_name(tu, path)
+a_file = File.from_name(tu, path_a)
+
+location1 = SourceLocation.from_position(tu, main_file, 1, 3)
+location2 = SourceLocation.from_position(tu, main_file, 2, 2)
+location1_2 = SourceLocation.from_position(tu, main_file, 1, 3)
+file2_location1 = SourceLocation.from_position(tu, a_file, 1, 3)
+
+self.assertEqual(location1, location1)
+self.assertEqual(location1, location1_2)
+self.assertNotEqual(location1, location2)
+self.assertNotEqual(location1, file2_location1)
+self.assertNotEqual(location1, "foo")
diff --git a/clang/bindings/python/tests/cindex/test_source_range.py 
b/clang/bindings/python/tests/cindex/test_source_range.py
index 81c0a9b05cff8..87b17caaac69b 100644
--- a/clang/bindings/python/tests/cindex/test_source_range.py
+++ b/clang/bindings/python/tests/cindex/test_source_range.py
@@ -9,6 +9,8 @@
 
 from .util import get_tu
 
+INPUTS_DIR = os.path.join(os.path.dirname(__file__), "INPUTS")
+
 
 def create_range(tu, line1, column1, line2, column2):
 return SourceRange.from_locations(
@@ -83,3 +85,16 @@ def test_contains(self):
 r_curly = create_range(tu2, 1, 11, 3, 1)
 l_f2 = SourceLocation.from_position(tu2, 
tu2.get_file("./numbers.inc"), 4, 1)
 assert l_f2 in r_curly
+
+def test_equality(self):
+path = os.path.join(INPUTS_DIR, "testfile.c")
+tu = TranslationUnit.from_source(path)
+
+r1 = create_range(tu, 1, 1, 2, 2)
+r2 = create_range(tu, 1, 2, 2, 2)
+r1_2 = create_range(tu, 1, 1, 2, 2)
+
+self.assertEqual(r1, r1)
+self.assertEqual(r1, r1_2)
+self.assertNotEqual(r1, r2)
+self.assertNotEqual(r1, "foo")

>From 686f5078bd875eaff54b7984d2286a6de6d4d060 Mon Sep 17 00:00:00 2001
From: Jannick Kremer 
Date: Fri, 2 May 2025 10:59:46 +0900
Subject: [PATCH 2/2] Use pathlib for input file paths

---
 clang/bindings/python/tests/cindex/test_location.py | 7 ---
 clang/bindings/python/tests/cindex/test_source_range.py | 5 +++--
 2 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/clang/bindings/python/tests/cindex/test_location.py 
b/clang/bindings/python/tests/cindex/test_location.py
index f1a4589738f52..3c6b0357e2f83 100644
--- a/clang/bindings/python/tests/cindex/test_location.py
+++ b/clang/bindings/python/tests/cindex/test_location.py
@@ -1,4 +1,5 @@
 import os
+from pathlib import Path
 
 from clang.cindex import (
 Config,
@@ -16,7 +17,7 @@
 
 from .util import get_cursor, get_tu

[clang] [libclang/python] Add tests for equality operators. (PR #138132)

2025-05-01 Thread Jannick Kremer via cfe-commits


@@ -16,6 +16,8 @@
 
 from .util import get_cursor, get_tu
 
+INPUTS_DIR = os.path.join(os.path.dirname(__file__), "INPUTS")

DeinAlptraum wrote:

Yes, I changed these to use `pathlib.Path` instead

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


[clang] 44c4b4c - [CIR] Upstream cir.call with scalar arguments (#136810)

2025-05-01 Thread via cfe-commits

Author: Sirui Mu
Date: 2025-05-02T10:04:48+08:00
New Revision: 44c4b4cef9d13ef91a771c45664dde643009f996

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

LOG: [CIR] Upstream cir.call with scalar arguments (#136810)

This PR upstreams support for scalar arguments in `cir.call` operation.

Related to #132487 .

Added: 


Modified: 
clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
clang/include/clang/CIR/Dialect/IR/CIRDialect.h
clang/include/clang/CIR/Dialect/IR/CIROps.td
clang/include/clang/CIR/Interfaces/CIROpInterfaces.td
clang/include/clang/CIR/MissingFeatures.h
clang/lib/CIR/CodeGen/CIRGenCall.cpp
clang/lib/CIR/CodeGen/CIRGenCall.h
clang/lib/CIR/CodeGen/CIRGenExpr.cpp
clang/lib/CIR/CodeGen/CIRGenFunction.h
clang/lib/CIR/CodeGen/CIRGenFunctionInfo.h
clang/lib/CIR/CodeGen/CIRGenTypes.cpp
clang/lib/CIR/CodeGen/CIRGenTypes.h
clang/lib/CIR/CodeGen/TargetInfo.cpp
clang/lib/CIR/Dialect/IR/CIRDialect.cpp
clang/test/CIR/CodeGen/call.cpp
clang/test/CIR/IR/call.cir
clang/test/CIR/IR/invalid-call.cir

Removed: 




diff  --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h 
b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index d58ced6ec8bff..d96a1394b97f2 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -215,14 +215,14 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   
//======//
 
   cir::CallOp createCallOp(mlir::Location loc, mlir::SymbolRefAttr callee,
-   mlir::Type returnType) {
-auto op = create(loc, callee, returnType);
-return op;
+   mlir::Type returnType, mlir::ValueRange operands) {
+return create(loc, callee, returnType, operands);
   }
 
-  cir::CallOp createCallOp(mlir::Location loc, cir::FuncOp callee) {
+  cir::CallOp createCallOp(mlir::Location loc, cir::FuncOp callee,
+   mlir::ValueRange operands) {
 return createCallOp(loc, mlir::SymbolRefAttr::get(callee),
-callee.getFunctionType().getReturnType());
+callee.getFunctionType().getReturnType(), operands);
   }
 
   
//======//

diff  --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
index ffa727cca4064..aa1494ab4df1e 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
@@ -31,6 +31,7 @@
 #include "clang/CIR/Dialect/IR/CIROpsEnums.h"
 #include "clang/CIR/Interfaces/CIRLoopOpInterface.h"
 #include "clang/CIR/Interfaces/CIROpInterfaces.h"
+#include "clang/CIR/MissingFeatures.h"
 
 namespace mlir {
 namespace OpTrait {

diff  --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 8319364b9e5e3..c9f4be61b2666 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -1769,6 +1769,13 @@ def FuncOp : CIR_Op<"func", [
return getFunctionType().getReturnTypes();
 }
 
+// TODO(cir): this should be an operand attribute, but for now we just 
hard-
+// wire this as a function. Will later add a $no_proto argument to this op.
+bool getNoProto() {
+  assert(!cir::MissingFeatures::opFuncNoProto());
+  return false;
+}
+
 
//===--===//
 // SymbolOpInterface Methods
 
//===--===//
@@ -1789,6 +1796,41 @@ class CIR_CallOpBase 
extra_traits = []>
  !listconcat(extra_traits,
  [DeclareOpInterfaceMethods,
   DeclareOpInterfaceMethods])> {
+  let extraClassDeclaration = [{
+/// Get the argument operands to the called function.
+mlir::OperandRange getArgOperands() {
+  return getArgs();
+}
+
+mlir::MutableOperandRange getArgOperandsMutable() {
+  return getArgsMutable();
+}
+
+/// Return the callee of this operation
+mlir::CallInterfaceCallable getCallableForCallee() {
+  return (*this)->getAttrOfType("callee");
+}
+
+/// Set the callee for this operation.
+void setCalleeFromCallable(::mlir::CallInterfaceCallable callee) {
+  (*this)->setAttr(getCalleeAttrName(),
+   mlir::cast(callee));
+}
+
+mlir::ArrayAttr getArgAttrsAttr() { return {}; }
+::mlir::ArrayAttr getResAttrsAttr() { return {}; }
+
+void setResAttrsAttr(::mlir::ArrayAttr attrs) {}
+void setArgAttr

[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits

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


[clang] [libclang/python] Add typing annotations for the Cursor class (PR #138103)

2025-05-01 Thread Jannick Kremer via cfe-commits

https://github.com/DeinAlptraum created 
https://github.com/llvm/llvm-project/pull/138103

None

>From d03f89a960e4fd57be2c37ee4c0cd59b5c784316 Mon Sep 17 00:00:00 2001
From: Jannick Kremer 
Date: Thu, 1 May 2025 18:37:43 +0900
Subject: [PATCH] [libclang/python] Add typing annotations for the Cursor class

---
 clang/bindings/python/clang/cindex.py | 154 +-
 1 file changed, 80 insertions(+), 74 deletions(-)

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index a5227df093e73..bdff8ae9edc7b 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -72,6 +72,7 @@
 Any,
 Callable,
 Generic,
+Iterator,
 Optional,
 Type as TType,
 TypeVar,
@@ -1546,66 +1547,68 @@ class Cursor(Structure):
 
 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
 
+_tu: TranslationUnit
+
 @staticmethod
-def from_location(tu, location):
+def from_location(tu: TranslationUnit, location: SourceLocation) -> Cursor:
 # We store a reference to the TU in the instance so the TU won't get
 # collected before the cursor.
-cursor = conf.lib.clang_getCursor(tu, location)
+cursor: Cursor = conf.lib.clang_getCursor(tu, location)
 cursor._tu = tu
 
 return cursor
 
-def __eq__(self, other):
+def __eq__(self, other: object) -> bool:
 return conf.lib.clang_equalCursors(self, other)  # type: ignore 
[no-any-return]
 
-def __ne__(self, other):
+def __ne__(self, other: object) -> bool:
 return not self.__eq__(other)
 
 def __hash__(self) -> int:
 return self.hash
 
-def is_definition(self):
+def is_definition(self) -> bool:
 """
 Returns true if the declaration pointed at by the cursor is also a
 definition of that entity.
 """
 return conf.lib.clang_isCursorDefinition(self)  # type: ignore 
[no-any-return]
 
-def is_const_method(self):
+def is_const_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared 'const'.
 """
 return conf.lib.clang_CXXMethod_isConst(self)  # type: ignore 
[no-any-return]
 
-def is_converting_constructor(self):
+def is_converting_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ converting 
constructor."""
 return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)  # 
type: ignore [no-any-return]
 
-def is_copy_constructor(self):
+def is_copy_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ copy constructor."""
 return conf.lib.clang_CXXConstructor_isCopyConstructor(self)  # type: 
ignore [no-any-return]
 
-def is_default_constructor(self):
+def is_default_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ default constructor."""
 return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)  # 
type: ignore [no-any-return]
 
-def is_move_constructor(self):
+def is_move_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ move constructor."""
 return conf.lib.clang_CXXConstructor_isMoveConstructor(self)  # type: 
ignore [no-any-return]
 
-def is_default_method(self):
+def is_default_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared '= default'.
 """
 return conf.lib.clang_CXXMethod_isDefaulted(self)  # type: ignore 
[no-any-return]
 
-def is_deleted_method(self):
+def is_deleted_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared '= delete'.
 """
 return conf.lib.clang_CXXMethod_isDeleted(self)  # type: ignore 
[no-any-return]
 
-def is_copy_assignment_operator_method(self):
+def is_copy_assignment_operator_method(self) -> bool:
 """Returnrs True if the cursor refers to a copy-assignment operator.
 
 A copy-assignment operator `X::operator=` is a non-static,
@@ -1630,7 +1633,7 @@ class Bar {
 """
 return conf.lib.clang_CXXMethod_isCopyAssignmentOperator(self)  # 
type: ignore [no-any-return]
 
-def is_move_assignment_operator_method(self):
+def is_move_assignment_operator_method(self) -> bool:
 """Returnrs True if the cursor refers to a move-assignment operator.
 
 A move-assignment operator `X::operator=` is a non-static,
@@ -1655,7 +1658,7 @@ class Bar {
 """
 return conf.lib.clang_CXXMethod_isMoveAssignmentOperator(self)  # 
type: ignore [no-any-return]
 
-def is_explicit_method(self):
+def is_explicit_method(self) -> bool:
 """Determines if a C++ constructor or conversi

[clang] [libclang/python] Add typing annotations for the Cursor class (PR #138103)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jannick Kremer (DeinAlptraum)


Changes



---

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


1 Files Affected:

- (modified) clang/bindings/python/clang/cindex.py (+80-74) 


``diff
diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index a5227df093e73..bdff8ae9edc7b 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -72,6 +72,7 @@
 Any,
 Callable,
 Generic,
+Iterator,
 Optional,
 Type as TType,
 TypeVar,
@@ -1546,66 +1547,68 @@ class Cursor(Structure):
 
 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
 
+_tu: TranslationUnit
+
 @staticmethod
-def from_location(tu, location):
+def from_location(tu: TranslationUnit, location: SourceLocation) -> Cursor:
 # We store a reference to the TU in the instance so the TU won't get
 # collected before the cursor.
-cursor = conf.lib.clang_getCursor(tu, location)
+cursor: Cursor = conf.lib.clang_getCursor(tu, location)
 cursor._tu = tu
 
 return cursor
 
-def __eq__(self, other):
+def __eq__(self, other: object) -> bool:
 return conf.lib.clang_equalCursors(self, other)  # type: ignore 
[no-any-return]
 
-def __ne__(self, other):
+def __ne__(self, other: object) -> bool:
 return not self.__eq__(other)
 
 def __hash__(self) -> int:
 return self.hash
 
-def is_definition(self):
+def is_definition(self) -> bool:
 """
 Returns true if the declaration pointed at by the cursor is also a
 definition of that entity.
 """
 return conf.lib.clang_isCursorDefinition(self)  # type: ignore 
[no-any-return]
 
-def is_const_method(self):
+def is_const_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared 'const'.
 """
 return conf.lib.clang_CXXMethod_isConst(self)  # type: ignore 
[no-any-return]
 
-def is_converting_constructor(self):
+def is_converting_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ converting 
constructor."""
 return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)  # 
type: ignore [no-any-return]
 
-def is_copy_constructor(self):
+def is_copy_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ copy constructor."""
 return conf.lib.clang_CXXConstructor_isCopyConstructor(self)  # type: 
ignore [no-any-return]
 
-def is_default_constructor(self):
+def is_default_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ default constructor."""
 return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)  # 
type: ignore [no-any-return]
 
-def is_move_constructor(self):
+def is_move_constructor(self) -> bool:
 """Returns True if the cursor refers to a C++ move constructor."""
 return conf.lib.clang_CXXConstructor_isMoveConstructor(self)  # type: 
ignore [no-any-return]
 
-def is_default_method(self):
+def is_default_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared '= default'.
 """
 return conf.lib.clang_CXXMethod_isDefaulted(self)  # type: ignore 
[no-any-return]
 
-def is_deleted_method(self):
+def is_deleted_method(self) -> bool:
 """Returns True if the cursor refers to a C++ member function or member
 function template that is declared '= delete'.
 """
 return conf.lib.clang_CXXMethod_isDeleted(self)  # type: ignore 
[no-any-return]
 
-def is_copy_assignment_operator_method(self):
+def is_copy_assignment_operator_method(self) -> bool:
 """Returnrs True if the cursor refers to a copy-assignment operator.
 
 A copy-assignment operator `X::operator=` is a non-static,
@@ -1630,7 +1633,7 @@ class Bar {
 """
 return conf.lib.clang_CXXMethod_isCopyAssignmentOperator(self)  # 
type: ignore [no-any-return]
 
-def is_move_assignment_operator_method(self):
+def is_move_assignment_operator_method(self) -> bool:
 """Returnrs True if the cursor refers to a move-assignment operator.
 
 A move-assignment operator `X::operator=` is a non-static,
@@ -1655,7 +1658,7 @@ class Bar {
 """
 return conf.lib.clang_CXXMethod_isMoveAssignmentOperator(self)  # 
type: ignore [no-any-return]
 
-def is_explicit_method(self):
+def is_explicit_method(self) -> bool:
 """Determines if a C++ constructor or conversion function is
 explicit, returning 1 if such is the case and 0 otherwise.
 
@@ -1700,41 +1703,41 @@ class 

[clang] [llvm] [clang] Add scoped enum support to `StreamingDiagnostic` (PR #138089)

2025-05-01 Thread Vlad Serebrennikov via cfe-commits


@@ -1429,6 +1429,22 @@ operator<<(const StreamingDiagnostic &DB, T *DC) {
   return DB;
 }
 
+// Convert scope enums to their underlying type, so that we don't have
+// clutter the emitting code with `llvm::to_underlying()`.
+// We also need to disable implicit conversion for the first argument,
+// because classes that derive from StreamingDiagnostic define their own
+// templated operator<< that accept a wide variety of types, leading
+// to ambiguity.
+template 
+inline std::enable_if_t<
+std::is_same_v, StreamingDiagnostic> &&
+llvm::is_scoped_enum_v>,
+const StreamingDiagnostic &>
+operator<<(const T &DB, U &&SE) {

Endilll wrote:

I tried that. First you add an overload, then you need to modify the existing 
overload to not be a viable candidate when a scoped enum is passed. The new 
overload also have to copy any checks or asserts that the old one does, 
otherwise they will be skipped. I wasn't able to make it work, and it would be 
more complicated than the approach here anyway.

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


[clang] [Clang][Cygwin] Disable shared libs on Cygwin by default (PR #138119)

2025-05-01 Thread Mateusz Mikuła via cfe-commits

https://github.com/mati865 created 
https://github.com/llvm/llvm-project/pull/138119

This change follows MinGW decisions, otherwise build with GCC fail with:
```
FAILED: bin/msys-clang-cpp-21.0git.dll lib/libclang-cpp.dll.a
...
/usr/lib/gcc/x86_64-pc-msys/13.3.0/../../../../x86_64-pc-msys/bin/ld: error: 
export ordinal too large: 92250
```

Split out from https://github.com/llvm/llvm-project/pull/134494

From dddb263950fd745d859db3456b1944d64a43d05b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Fri, 4 Apr 2025 15:08:18 +0200
Subject: [PATCH] [Clang][Cygwin] Disable shared libs on Cygwin by default

This change follows MinGW decisions, otherwise build with GCC fail with:
```
FAILED: bin/msys-clang-cpp-21.0git.dll lib/libclang-cpp.dll.a
...
/usr/lib/gcc/x86_64-pc-msys/13.3.0/../../../../x86_64-pc-msys/bin/ld: error: 
export ordinal too large: 92250
```

Co-authored-by: jeremyd2019 
---
 clang/tools/CMakeLists.txt  | 5 +++--
 clang/tools/libclang/CMakeLists.txt | 3 ++-
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/tools/CMakeLists.txt b/clang/tools/CMakeLists.txt
index 9634eb12080c8..50e3d694236ac 100644
--- a/clang/tools/CMakeLists.txt
+++ b/clang/tools/CMakeLists.txt
@@ -26,9 +26,10 @@ endif()
 add_clang_subdirectory(c-index-test)
 
 add_clang_subdirectory(clang-refactor)
-# For MinGW we only enable shared library if LLVM_LINK_LLVM_DYLIB=ON.
+# For MinGW/Cygwin we only enable shared library if LLVM_LINK_LLVM_DYLIB=ON.
 # Without that option resulting library is too close to 2^16 DLL exports limit.
-if(UNIX OR (MSVC AND LLVM_BUILD_LLVM_DYLIB_VIS) OR (MINGW AND 
LLVM_LINK_LLVM_DYLIB))
+if((UNIX AND NOT CYGWIN) OR (MSVC AND LLVM_BUILD_LLVM_DYLIB_VIS) OR
+  ((MINGW OR CYGWIN) AND LLVM_LINK_LLVM_DYLIB))
   add_clang_subdirectory(clang-shlib)
 endif()
 
diff --git a/clang/tools/libclang/CMakeLists.txt 
b/clang/tools/libclang/CMakeLists.txt
index 299c14660f3d4..37a939ffcada7 100644
--- a/clang/tools/libclang/CMakeLists.txt
+++ b/clang/tools/libclang/CMakeLists.txt
@@ -106,7 +106,8 @@ if (LLVM_EXPORTED_SYMBOL_FILE)
  DEPENDS ${LIBCLANG_VERSION_SCRIPT_FILE})
 endif()
 
-if(LLVM_ENABLE_PIC OR (WIN32 AND NOT LIBCLANG_BUILD_STATIC))
+if((NOT (WIN32 OR CYGWIN) AND LLVM_ENABLE_PIC) OR
+  ((WIN32 OR CYGWIN) AND NOT LIBCLANG_BUILD_STATIC))
   set(ENABLE_SHARED SHARED)
 endif()
 

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


[clang] [Clang][Cygwin] Remove erroneous _WIN32 define and clean up Cygwin code (PR #138120)

2025-05-01 Thread Mateusz Mikuła via cfe-commits

https://github.com/mati865 created 
https://github.com/llvm/llvm-project/pull/138120

With this define present and building with Clang the build fails:
```
In file included from 
/h/projects/llvm-project/clang/tools/libclang/CIndexer.cpp:36:
In file included from /usr/include/w32api/windows.h:69:
In file included from /usr/include/w32api/windef.h:9:
In file included from /usr/include/w32api/minwindef.h:163:
In file included from /usr/include/w32api/winnt.h:1658:
In file included from /usr/lib/clang/20/include/x86intrin.h:15:
In file included from /usr/lib/clang/20/include/immintrin.h:24:
In file included from /usr/lib/clang/20/include/xmmintrin.h:31:
/usr/lib/clang/20/include/mm_malloc.h:45:22: error: use of undeclared 
identifier '_aligned_malloc'; did you mean 'aligned_alloc'?
   45 |   __mallocedMemory = _aligned_malloc(__size, __align);
  |  ^
```
Removing it allows the build with Clang to succeed and doesn't break build with 
GCC.

Split out from https://github.com/llvm/llvm-project/pull/134494

From 3dc4b18cc6ecb734fb3ab7fff68f2802149b5007 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Fri, 4 Apr 2025 21:41:50 +0200
Subject: [PATCH] [Clang][Cygwin] Remove erroneous _WIN32 define and clean up
 Cygwin code

With this define present and building with Clang the build fails:
```
In file included from 
/h/projects/llvm-project/clang/tools/libclang/CIndexer.cpp:36:
In file included from /usr/include/w32api/windows.h:69:
In file included from /usr/include/w32api/windef.h:9:
In file included from /usr/include/w32api/minwindef.h:163:
In file included from /usr/include/w32api/winnt.h:1658:
In file included from /usr/lib/clang/20/include/x86intrin.h:15:
In file included from /usr/lib/clang/20/include/immintrin.h:24:
In file included from /usr/lib/clang/20/include/xmmintrin.h:31:
/usr/lib/clang/20/include/mm_malloc.h:45:22: error: use of undeclared 
identifier '_aligned_malloc'; did you mean 'aligned_alloc'?
   45 |   __mallocedMemory = _aligned_malloc(__size, __align);
  |  ^
```
Removing it allows the build with Clang to succeed and doesn't break build with 
GCC.

Co-authored-by: Jeremy Drake 
---
 clang/tools/libclang/CIndexer.cpp | 16 
 1 file changed, 16 deletions(-)

diff --git a/clang/tools/libclang/CIndexer.cpp 
b/clang/tools/libclang/CIndexer.cpp
index 12d9d418dea51..11d9312b64849 100644
--- a/clang/tools/libclang/CIndexer.cpp
+++ b/clang/tools/libclang/CIndexer.cpp
@@ -26,12 +26,6 @@
 #include 
 #include 
 
-#ifdef __CYGWIN__
-#include 
-#include 
-#define _WIN32 1
-#endif
-
 #ifdef _WIN32
 #include 
 #elif defined(_AIX)
@@ -112,16 +106,6 @@ const std::string &CIndexer::getClangResourcesPath() {
sizeof(mbi));
   GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
 
-#ifdef __CYGWIN__
-  char w32path[MAX_PATH];
-  strcpy(w32path, path);
-#if CYGWIN_VERSION_API_MAJOR > 0 || CYGWIN_VERSION_API_MINOR >= 181
-  cygwin_conv_path(CCP_WIN_A_TO_POSIX, w32path, path, MAX_PATH);
-#else
-  cygwin_conv_to_full_posix_path(w32path, path);
-#endif
-#endif
-
   LibClangPath += path;
 #elif defined(_AIX)
   getClangResourcesPathImplAIX(LibClangPath);

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


[clang] [C] Add -Wtentative-definition-compat (PR #137967)

2025-05-01 Thread Aaron Ballman via cfe-commits

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

>From b685a553da0b3f9ecf019ceddb1052de60a9a4e6 Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Wed, 30 Apr 2025 10:11:17 -0400
Subject: [PATCH] [C] Add -Wtentative-definition-compat

This adds a new diagnostic to warn about redeclaration of a tentative
definition in C. This is incompatible with C++, so the new diagnostic
group is under -Wc++-compat.
---
 clang/docs/ReleaseNotes.rst   |  9 
 clang/include/clang/Basic/DiagnosticGroups.td |  4 +++-
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +++
 clang/lib/Sema/SemaDecl.cpp   |  3 +++
 clang/test/Sema/warn-default-const-init.c |  2 +-
 clang/test/Sema/warn-tentative-defn-compat.c  | 23 +++
 6 files changed, 42 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/Sema/warn-tentative-defn-compat.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc68bb8b70b3d..0c667745f2613 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -171,6 +171,15 @@ C Language Changes
   ``-Wenum-conversion`` and ``-Wimplicit-int-enum-cast``. This conversion is an
   int-to-enum conversion because the enumeration on the right-hand side is
   promoted to ``int`` before the assignment.
+- Added ``-Wtentative-definition-compat``, grouped under ``-Wc++-compat``,
+  which diagnoses tentative definitions in C with multiple declarations as
+  being incompatible with C++. e.g.,
+
+  .. code-block:: c
+
+// File scope
+int i;
+int i; // Vaild C, invalid C++, now diagnosed
 
 C2y Feature Support
 ^^^
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index fc1ce197ef134..0ac7b2d39d12e 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -162,8 +162,10 @@ def DefaultConstInit : DiagGroup<"default-const-init", 
[DefaultConstInitUnsafe]>
 def ImplicitVoidPtrCast : DiagGroup<"implicit-void-ptr-cast">;
 def ImplicitIntToEnumCast : DiagGroup<"implicit-int-enum-cast",
   [ImplicitEnumEnumCast]>;
+def TentativeDefnCompat : DiagGroup<"tentative-definition-compat">;
 def CXXCompat: DiagGroup<"c++-compat", [ImplicitVoidPtrCast, DefaultConstInit,
-ImplicitIntToEnumCast, HiddenCppDecl]>;
+ImplicitIntToEnumCast, HiddenCppDecl,
+TentativeDefnCompat]>;
 
 def ExternCCompat : DiagGroup<"extern-c-compat">;
 def KeywordCompat : DiagGroup<"keyword-compat">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ad5bf26be2590..7cba120cbd924 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7443,6 +7443,9 @@ def err_tentative_def_incomplete_type : Error<
 def warn_tentative_incomplete_array : Warning<
   "tentative array definition assumed to have one element">,
   InGroup>;
+def warn_cxx_compat_tentative_definition : Warning<
+  "duplicate declaration of %0 is invalid in C++">,
+  InGroup, DefaultIgnore;
 def err_typecheck_incomplete_array_needs_initializer : Error<
   "definition of variable with array type needs an explicit size "
   "or an initializer">;
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index dfc718eedc1d9..3789eff818e08 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4750,6 +4750,9 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
+  } else {
+Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition) << 
New;
+Diag(Old->getLocation(), diag::note_previous_declaration);
   }
 
   if (haveIncompatibleLanguageLinkages(Old, New)) {
diff --git a/clang/test/Sema/warn-default-const-init.c 
b/clang/test/Sema/warn-default-const-init.c
index b8da41b333f3d..ed211e366428e 100644
--- a/clang/test/Sema/warn-default-const-init.c
+++ b/clang/test/Sema/warn-default-const-init.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify=c,unsafe -Wdefault-const-init %s
-// RUN: %clang_cc1 -fsyntax-only -verify=c,unsafe -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only -verify=c,unsafe -Wc++-compat 
-Wno-tentative-definition-compat %s
 // RUN: %clang_cc1 -fsyntax-only -verify=unsafe %s
 // RUN: %clang_cc1 -fsyntax-only -verify=c -Wdefault-const-init 
-Wno-default-const-init-unsafe %s
 // RUN: %clang_cc1 -fsyntax-only -verify=good -Wno-default-const-init-unsafe %s
diff --git a/clang/test/Sema/warn-tentative-defn-compat.c 
b/clang/test/Sema/warn-tentative-defn-compat.c
new file mode 100644
index 0..02f3db2f1
--- /dev/null
+++ b/clang/test/Sema/warn-tentative-defn-compat.c
@@ -0,0 +1,23

[clang] [Clang] incorrect assertion when checking template template parameter of a lambda (PR #138121)

2025-05-01 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/138121

When a lambda is used in an alias declaration, we were trying to refer to its 
call operator. However, that could happen before (or during) the call operator 
is defined.

So we should not assume a lambda always has a call operator.

Fixes #136432
Fixes #137014
Fixes #138018

>From 34011def1ec643701a84424f0813484efa39a1d1 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 1 May 2025 13:32:00 +0200
Subject: [PATCH] [Clang] incorrect assertion when checking template template
 parameter of a lambda.

When a lamdbda is used in an alias declaration, we were trying
to refer to its call operator. However, that could happen before
(or during) the call operator is defined.

So we should not assume a lambda always has a call operator.

Fixes #136432
Fixes #137014
Fixes #138018
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/AST/DeclCXX.cpp |  6 +-
 clang/test/SemaCXX/lambda-unevaluated.cpp | 16 
 3 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f5cd1fbeabcfe..8a463f9aca0c9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -529,6 +529,8 @@ Bug Fixes to C++ Support
 - Clang now issues an error when placement new is used to modify a 
const-qualified variable
   in a ``constexpr`` function. (#GH131432)
 - Clang now emits a warning when class template argument deduction for alias 
templates is used in C++17. (#GH133806)
+- Fix a crash when checking the template template parameters of a dependent 
lambda appearing in an alias declaration.
+  (#GH136432), (#GH137014), (#GH138018)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 4d07efd58f518..9095575ee1175 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1696,7 +1696,11 @@ static NamedDecl* getLambdaCallOperatorHelper(const 
CXXRecordDecl &RD) {
   RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
 
   DeclContext::lookup_result Calls = RD.lookup(Name);
-  assert(!Calls.empty() && "Missing lambda call operator!");
+
+  // This can happen while building the lambda.
+  if (Calls.empty())
+return nullptr;
+
   assert(allLookupResultsAreTheSame(Calls) &&
  "More than one lambda call operator!");
 
diff --git a/clang/test/SemaCXX/lambda-unevaluated.cpp 
b/clang/test/SemaCXX/lambda-unevaluated.cpp
index a9bcab58464e2..40f8a729fd912 100644
--- a/clang/test/SemaCXX/lambda-unevaluated.cpp
+++ b/clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -266,3 +266,19 @@ void func() {
 }
 
 } // namespace GH88081
+
+namespace GH138018 {
+
+template  struct vec {};
+
+auto structure_to_typelist(auto)  {
+return [] typename T>(T) {
+return 0;
+}(vec{});
+}
+
+template  using helper = decltype(structure_to_typelist(T{}));
+static_assert(__is_same_as(int, helper));
+
+
+} // namespace GH138018

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


[clang] [Clang] incorrect assertion when checking template template parameter of a lambda (PR #138121)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

When a lambda is used in an alias declaration, we were trying to refer to its 
call operator. However, that could happen before (or during) the call operator 
is defined.

So we should not assume a lambda always has a call operator.

Fixes #136432
Fixes #137014
Fixes #138018

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/AST/DeclCXX.cpp (+5-1) 
- (modified) clang/test/SemaCXX/lambda-unevaluated.cpp (+16) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f5cd1fbeabcfe..8a463f9aca0c9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -529,6 +529,8 @@ Bug Fixes to C++ Support
 - Clang now issues an error when placement new is used to modify a 
const-qualified variable
   in a ``constexpr`` function. (#GH131432)
 - Clang now emits a warning when class template argument deduction for alias 
templates is used in C++17. (#GH133806)
+- Fix a crash when checking the template template parameters of a dependent 
lambda appearing in an alias declaration.
+  (#GH136432), (#GH137014), (#GH138018)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 4d07efd58f518..9095575ee1175 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1696,7 +1696,11 @@ static NamedDecl* getLambdaCallOperatorHelper(const 
CXXRecordDecl &RD) {
   RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
 
   DeclContext::lookup_result Calls = RD.lookup(Name);
-  assert(!Calls.empty() && "Missing lambda call operator!");
+
+  // This can happen while building the lambda.
+  if (Calls.empty())
+return nullptr;
+
   assert(allLookupResultsAreTheSame(Calls) &&
  "More than one lambda call operator!");
 
diff --git a/clang/test/SemaCXX/lambda-unevaluated.cpp 
b/clang/test/SemaCXX/lambda-unevaluated.cpp
index a9bcab58464e2..40f8a729fd912 100644
--- a/clang/test/SemaCXX/lambda-unevaluated.cpp
+++ b/clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -266,3 +266,19 @@ void func() {
 }
 
 } // namespace GH88081
+
+namespace GH138018 {
+
+template  struct vec {};
+
+auto structure_to_typelist(auto)  {
+return [] typename T>(T) {
+return 0;
+}(vec{});
+}
+
+template  using helper = decltype(structure_to_typelist(T{}));
+static_assert(__is_same_as(int, helper));
+
+
+} // namespace GH138018

``




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


[clang] Fix missing initializer for inline static template member with auto caused by delayed template instantiation. (PR #138122)

2025-05-01 Thread via cfe-commits

https://github.com/dty2 created https://github.com/llvm/llvm-project/pull/138122

Try to fix missing initializer for inline static template member with auto 
caused by delayed template instantiation.

Bug Fix: [Bug 135032](https://github.com/llvm/llvm-project/issues/135032)
Problem Description:
Due to nested templates, when instantiating the outer layer (the template 
class), the inner layer (the template variable) uses delayed instantiation.
This causes the declaration (VarDecl) of the template variable to retain the 
type from the original template declaration (i.e., auto), and it loses the 
initializer.
Later, when instantiating the template variable, its 
VarTemplateSpecializationDecl type depends on the VarDecl type.
Thus, the VarTemplateSpecializationDecl also has no initializer, and its type 
remains auto.
Ultimately, when building the reference expression in 
Sema::BuildDeclarationNameExpr, the expression's type is auto and stays as auto 
until code generation, triggering llvm_unreachable in CodeGenTypes::ConvertType.

Reproduction Steps:
Test Code:
``` cxx
template  struct B {
  template  inline static auto var = 5;
};

int main() {
  int bb = B::var;
  return 0;
}
```
GDB Breakpoints for Debugging:
Annotations like #(1) mark the call order in a tree structure. For example, two 
#(3) entries mean Sema::CheckVarTemplateId calls Sema::BuildDeclarationNameExpr 
after its own execution.
``` gdb
#(1)
b Sema::BuildTemplateIdExpr
#(2)
b Sema::CheckVarTemplateId
#(3)
b Sema::CheckVarTemplateId
#(4)
b Sema::BuildVarTemplateInstantiation
#(5)
b TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl
#(6)
b VarTemplateSpecializationDecl::Create
#(7)
b VarTemplateSpecializationDecl::VarTemplateSpecializationDecl
#(8)
b VarDecl::VarDecl
#(6)
b Sema::BuildVariableInstantiation
#(7)
b Sema::InstantiateVariableInitializer
#(3)
b Sema::BuildDeclarationNameExpr
#(4)
b Sema::BuildDeclRefExpr
```
Key Observations:
While debugging, I generated the AST for the test code and noticed a 
contradiction:

The AST shows VarTemplateSpecializationDecl as int (correct), but GDB reveals 
its type is actually auto during execution.

Example from AST:

DeclRefExpr 0x598f651f5a60  'auto' lvalue 
VarTemplateSpecialization 0x598f651f5980 'var' 'int' (VarTemplate 
0x598f651d1938 'var')
The DeclRefExpr has type auto, while its referenced VarTemplateSpecialization 
claims to be int—a clear inconsistency.

Solution:
Since I noticed that the deduction of auto type is caused by the initializer
I plan to do special processing for template variables of type auto, that is, 
to prevent their delayed instantiation
so that their initializers will not be lost when the outer template class is 
instantiated

From f9bdf07f09d7a04c190ae4d77c4983d4b7fa4936 Mon Sep 17 00:00:00 2001
From: hunter <284050...@qq.com>
Date: Thu, 1 May 2025 18:52:34 +0800
Subject: [PATCH] [clang] Fix missing initializer for inline static template
 member with auto caused by delayed template instantiation.

---
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 8 +++-
 clang/test/CodeGenCXX/cxx1z-inline-variables.cpp   | 8 
 clang/test/SemaTemplate/cxx17-inline-variables.cpp | 6 ++
 3 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 76c055d28f091..eb66ec34a956f 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6027,8 +6027,14 @@ void Sema::BuildVariableInstantiation(
   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
 
+  bool VarTemplateWithAutoType = false;
+  QualType VarSourceType = OldVar->getTypeSourceInfo()->getType();
+  if (VarSourceType->getAs()) {
+VarTemplateWithAutoType = true;
+  }
+
   // Figure out whether to eagerly instantiate the initializer.
-  if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
+  if ((InstantiatingVarTemplate && !VarTemplateWithAutoType) || 
InstantiatingVarTemplatePartialSpec) {
 // We're producing a template. Don't instantiate the initializer yet.
   } else if (NewVar->getType()->isUndeducedType()) {
 // We need the type to complete the declaration of the variable.
diff --git a/clang/test/CodeGenCXX/cxx1z-inline-variables.cpp 
b/clang/test/CodeGenCXX/cxx1z-inline-variables.cpp
index 812e438f30c9a..b1d8e376b826f 100644
--- a/clang/test/CodeGenCXX/cxx1z-inline-variables.cpp
+++ b/clang/test/CodeGenCXX/cxx1z-inline-variables.cpp
@@ -1,5 +1,13 @@
 // RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - -triple x86_64-linux-gnu | 
FileCheck %s
 
+template  struct B {
+  template  inline static auto var = 5;
+};
+
+int inlinevartemplate = B::var;
+// CHECK: @_ZN1BIiE3varIiEE = {{.*}}global i32 5{{.*}}comdat
+// CHECK-NOT: @_ZN1BIiE3varIfEE
+
 struct Q {
   // CHECK: @_ZN1Q1kE = linkonce_odr constant i32 5, comdat
  

[clang] Fix missing initializer for inline static template member with auto caused by delayed template instantiation. (PR #138122)

2025-05-01 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/Sema/SemaTemplateInstantiateDecl.cpp 
clang/test/CodeGenCXX/cxx1z-inline-variables.cpp 
clang/test/SemaTemplate/cxx17-inline-variables.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index eb66ec34a..c0a0feda6 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6034,7 +6034,8 @@ void Sema::BuildVariableInstantiation(
   }
 
   // Figure out whether to eagerly instantiate the initializer.
-  if ((InstantiatingVarTemplate && !VarTemplateWithAutoType) || 
InstantiatingVarTemplatePartialSpec) {
+  if ((InstantiatingVarTemplate && !VarTemplateWithAutoType) ||
+  InstantiatingVarTemplatePartialSpec) {
 // We're producing a template. Don't instantiate the initializer yet.
   } else if (NewVar->getType()->isUndeducedType()) {
 // We need the type to complete the declaration of the variable.

``




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


[clang] [Clang] Warning as error for fold expressions over comparison operators (PR #136836)

2025-05-01 Thread via cfe-commits


@@ -132,3 +132,30 @@ bool f();
 template 
 void g(bool = (f() || ...));
 }
+
+
+namespace comparison_warning {
+  struct S {
+bool operator<(const S&) const;
+bool operator<(int) const;
+bool operator==(const S&) const;
+  };
+
+  template 
+  void f(T... ts) {
+(void)(ts == ...);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X == Y) == Z'}}
+(void)(ts < ...);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X < Y) < Z'}}
+(void)(... < ts);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X < Y) < Z'}}
+  }
+
+  void test() {
+f(0, 1, 2); // expected-note{{in instantiation}}
+f(0, 1); // expected-note{{in instantiation}}

cor3ntin wrote:

This is intended -, ideally, we would even warn when `n <= 1` (ie, the size of 
the pack should not affect the warning) - but that would be annoying because 
there could be user-defined operators, and we only discover that for n >=2.

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


[clang] [Clang] Warning as error for fold expressions over comparison operators (PR #136836)

2025-05-01 Thread Younan Zhang via cfe-commits


@@ -132,3 +132,30 @@ bool f();
 template 
 void g(bool = (f() || ...));
 }
+
+
+namespace comparison_warning {
+  struct S {
+bool operator<(const S&) const;
+bool operator<(int) const;
+bool operator==(const S&) const;
+  };
+
+  template 
+  void f(T... ts) {
+(void)(ts == ...);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X == Y) == Z'}}
+(void)(ts < ...);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X < Y) < Z'}}
+(void)(... < ts);
+// expected-error@-1 2{{comparison in fold expression would evaluate to 
'(X < Y) < Z'}}
+  }
+
+  void test() {
+f(0, 1, 2); // expected-note{{in instantiation}}
+f(0, 1); // expected-note{{in instantiation}}

zyn0217 wrote:

Hmmm. It looks strange to me if we warn for '0 < 1'

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


[clang] [Clang][CodeGen] Add workaround for old glibc `__PTR_ALIGN` macro (PR #137851)

2025-05-01 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/137851

>From f1db3a540ec1383451955efab62b64ed8d180349 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Wed, 30 Apr 2025 01:26:41 +0800
Subject: [PATCH 1/5] [Clang][CodeGen] Check
 `isUnderlyingBasePointerConstantNull` in `emitPointerArithmetic`

---
 clang/lib/CodeGen/CGExprScalar.cpp   |  3 ++-
 .../test/CodeGen/catch-nullptr-and-nonzero-offset.c  | 12 
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 8dbbcdaef25d8..d214d2af52563 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4238,7 +4238,8 @@ static Value *emitPointerArithmetic(CodeGenFunction &CGF,
   else
 elemTy = CGF.ConvertTypeForMem(elementType);
 
-  if (CGF.getLangOpts().PointerOverflowDefined)
+  if (CGF.getLangOpts().PointerOverflowDefined ||
+  CGF.isUnderlyingBasePointerConstantNull(pointerOperand))
 return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
 
   return CGF.EmitCheckedInBoundsGEP(
diff --git a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c 
b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
index 63b6db2c2adeb..c5ae3f8bcc368 100644
--- a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
+++ b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
@@ -431,6 +431,18 @@ char *void_ptr(void *base, unsigned long offset) {
   return base + offset;
 }
 
+int *constant_null_add(long offset) {
+  // CHECK: define{{.*}} ptr @constant_null_add(i64 noundef %[[OFFSET:.*]])
+  // CHECK-NEXT: [[ENTRY:.*]]:
+  // CHECK-NEXT:   %[[OFFSET_ADDR:.*]] = alloca i64, align 8
+  // CHECK-NEXT:   store i64 %[[OFFSET]], ptr %[[OFFSET_ADDR]], align 8
+  // CHECK-NEXT:   %[[OFFSET_RELOADED:.*]] = load i64, ptr %[[OFFSET_ADDR]], 
align 8
+  // CHECK-NEXT:   %[[ADD_PTR:.*]] = getelementptr i32, ptr null, i64 
%[[OFFSET_RELOADED]]
+  // CHECK-NEXT:   ret ptr %[[ADD_PTR]]
+#line 1800
+  return (int *)0 + offset;
+}
+
 #ifdef __cplusplus
 }
 #endif

>From 630ce89088ef4978eafe884766712279a0d8fd56 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Wed, 30 Apr 2025 01:47:45 +0800
Subject: [PATCH 2/5] [Clang][CodeGen] Add pre-commit tests. NFC.

---
 clang/test/CodeGen/glibc_ptr_align.c | 17 +
 1 file changed, 17 insertions(+)
 create mode 100644 clang/test/CodeGen/glibc_ptr_align.c

diff --git a/clang/test/CodeGen/glibc_ptr_align.c 
b/clang/test/CodeGen/glibc_ptr_align.c
new file mode 100644
index 0..ebdb53cf7b53d
--- /dev/null
+++ b/clang/test/CodeGen/glibc_ptr_align.c
@@ -0,0 +1,17 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -triple=x86_64-unknown-unknown -O3 -o - -emit-llvm %s | 
FileCheck %s
+
+// Make sure that we do not set inbounds flag if the base pointer may be a 
constant null.
+
+// CHECK-LABEL: define dso_local noalias noundef ptr @glibc_ptr_align(
+// CHECK-SAME: ptr noundef readnone captures(none) [[BASE:%.*]], ptr noundef 
readnone captures(none) [[POINTER:%.*]], i64 noundef [[ALIGN_MASK:%.*]]) 
local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:ret ptr null
+//
+char *glibc_ptr_align(char *base, char *pointer, long align_mask) {
+  return (sizeof(long int) < sizeof(void *) ? (base) : (char *)0) +
+ (((pointer) -
+   (sizeof(long int) < sizeof(void *) ? (base) : (char *)0) +
+   (align_mask)) &
+  ~(align_mask));
+}

>From ff88c23843d07a1c3142294a3d7c0894f0267a48 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Wed, 30 Apr 2025 01:49:10 +0800
Subject: [PATCH 3/5] [Clang][CodeGen] Add workaround for old glibc
 `__PTR_ALIGN` macro

---
 clang/lib/CodeGen/CGExpr.cpp |  3 +++
 clang/test/CodeGen/glibc_ptr_align.c | 11 ---
 2 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index bba7d1e805f3f..e9e22321e2634 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4820,6 +4820,9 @@ bool 
CodeGenFunction::isUnderlyingBasePointerConstantNull(const Expr *E) {
   const Expr *UnderlyingBaseExpr = E->IgnoreParens();
   while (auto *BaseMemberExpr = dyn_cast(UnderlyingBaseExpr))
 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
+  if (auto *Select = dyn_cast(UnderlyingBaseExpr))
+return isUnderlyingBasePointerConstantNull(Select->getTrueExpr()) ||
+   isUnderlyingBasePointerConstantNull(Select->getFalseExpr());
   return getContext().isSentinelNullExpr(UnderlyingBaseExpr);
 }
 
diff --git a/clang/test/CodeGen/glibc_ptr_align.c 
b/clang/test/CodeGen/glibc_ptr_align.c
index ebdb53cf7b53d..14968a8326509 100644
--- a/clang/test/CodeGen/glibc_ptr_align.c
+++ b/clang/test/CodeGen/glibc_ptr_align.c
@@ -3,10 +3,15 @@
 
 // Make sure that we do not set inbounds flag i

[clang] [llvm] [clang] Add scoped enum support to `StreamingDiagnostic` (PR #138089)

2025-05-01 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clangd-ubuntu-tsan` 
running on `clangd-ubuntu-clang` while building `clang,llvm` at step 5 
"build-clangd-clangd-index-server-clangd-indexer".

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


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

```
Step 5 (build-clangd-clangd-index-server-clangd-indexer) failure: build 
(failure)
...
454.792 [1420/18/1842] Building CXX object 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesTypes.cpp.o
455.305 [1419/18/1843] Building CXX object 
lib/Target/XCore/TargetInfo/CMakeFiles/LLVMXCoreInfo.dir/XCoreTargetInfo.cpp.o
455.375 [1418/18/1844] Building X86GenGlobalISel.inc...
455.387 [1417/18/1845] Linking CXX static library lib/libLLVMXCoreInfo.a
455.423 [1416/18/1846] Building CXX object 
tools/clang/lib/Basic/CMakeFiles/obj.clangBasic.dir/CLWarnings.cpp.o
455.859 [1415/18/1847] Building CXX object 
tools/clang/lib/Basic/CMakeFiles/obj.clangBasic.dir/ASTSourceDescriptor.cpp.o
456.604 [1414/18/1848] Building X86GenDAGISel.inc...
456.730 [1413/18/1849] Building CXX object 
tools/clang/lib/Basic/CMakeFiles/obj.clangBasic.dir/CharInfo.cpp.o
457.079 [1412/18/1850] Building RISCVGenGlobalISel.inc...
457.708 [1411/18/1851] Building CXX object 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesManager.cpp.o
FAILED: 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesManager.cpp.o 
ccache /usr/bin/clang++ -DCLANG_EXPORTS -DGTEST_HAS_RTTI=0 -D_DEBUG 
-D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS 
-D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/build/tools/clang/lib/APINotes
 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/lib/APINotes
 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/build/tools/clang/include 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/build/include 
-I/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/llvm/include 
-fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time 
-Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter 
-Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic 
-Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough 
-Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion 
-Wmisleading-indentation -Wctad-maybe-unsupported -fno-omit-frame-pointer 
-gline-tables-only -fsanitize=thread -fdiagnostics-color -ffunction-sections 
-fdata-sections -fno-common -Woverloaded-virtual -Wno-nested-anon-types -O3 
-DNDEBUG  -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -std=c++17 -MD -MT 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesManager.cpp.o 
-MF 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesManager.cpp.o.d
 -o 
tools/clang/lib/APINotes/CMakeFiles/obj.clangAPINotes.dir/APINotesManager.cpp.o 
-c 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/lib/APINotes/APINotesManager.cpp
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/lib/APINotes/APINotesManager.cpp:9:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include/clang/APINotes/APINotesManager.h:12:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include/clang/Basic/SourceLocation.h:17:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include/clang/Basic/FileEntry.h:17:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include/clang/Basic/CustomizableOptional.h:12:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/llvm/include/llvm/ADT/Hashing.h:47:
In file included from 
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/llvm/include/llvm/ADT/ADL.h:12:
/usr/bin/../lib/gcc/x86_64-linux-gnu/7/../../../../include/c++/7/type_traits:2242:15:
 error: only enumeration types have underlying types
 2242 |   typedef __underlying_type(_Tp) type;
  |   ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/7/../../../../include/c++/7/type_traits:2488:5:
 note: in instantiation of template class 'std::underlying_type' requested here
 2488 | using underlying_type_t = typename underlying_type<_Tp>::type;
  | ^
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/llvm/include/llvm/ADT/STLForwardCompat.h:76:51:
 note: in instantiation of template type alias 'underlying_type_t' requested 
here
   76 | template >
  |   ^
/vol/worker/clangd-ubuntu-clang/clangd-ubuntu-tsan/llvm-project/clang/include/clang/Basic/Di

[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits

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

>From e5e7bd931dd409546d04237bd61eab67d6ba6451 Mon Sep 17 00:00:00 2001
From: Sirui Mu 
Date: Fri, 2 May 2025 00:31:08 +0800
Subject: [PATCH] [CIR] Upstream cir.call with scalar arguments

---
 .../CIR/Dialect/Builder/CIRBaseBuilder.h  |  10 +-
 .../include/clang/CIR/Dialect/IR/CIRDialect.h |   1 +
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  49 +++-
 .../clang/CIR/Interfaces/CIROpInterfaces.td   |  13 +-
 clang/include/clang/CIR/MissingFeatures.h |  15 +-
 clang/lib/CIR/CodeGen/CIRGenCall.cpp  | 275 +-
 clang/lib/CIR/CodeGen/CIRGenCall.h|  32 +-
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp  |  13 +-
 clang/lib/CIR/CodeGen/CIRGenFunction.h|  45 ++-
 clang/lib/CIR/CodeGen/CIRGenFunctionInfo.h|  27 +-
 clang/lib/CIR/CodeGen/CIRGenTypes.cpp |  15 +-
 clang/lib/CIR/CodeGen/CIRGenTypes.h   |   7 +-
 clang/lib/CIR/CodeGen/TargetInfo.cpp  |   7 +-
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp   |  49 +++-
 clang/test/CIR/CodeGen/call.cpp   |  12 +
 clang/test/CIR/IR/call.cir|  15 +
 clang/test/CIR/IR/invalid-call.cir|  27 ++
 17 files changed, 564 insertions(+), 48 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h 
b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index d58ced6ec8bff..d96a1394b97f2 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -215,14 +215,14 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   
//======//
 
   cir::CallOp createCallOp(mlir::Location loc, mlir::SymbolRefAttr callee,
-   mlir::Type returnType) {
-auto op = create(loc, callee, returnType);
-return op;
+   mlir::Type returnType, mlir::ValueRange operands) {
+return create(loc, callee, returnType, operands);
   }
 
-  cir::CallOp createCallOp(mlir::Location loc, cir::FuncOp callee) {
+  cir::CallOp createCallOp(mlir::Location loc, cir::FuncOp callee,
+   mlir::ValueRange operands) {
 return createCallOp(loc, mlir::SymbolRefAttr::get(callee),
-callee.getFunctionType().getReturnType());
+callee.getFunctionType().getReturnType(), operands);
   }
 
   
//======//
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
index ffa727cca4064..aa1494ab4df1e 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
@@ -31,6 +31,7 @@
 #include "clang/CIR/Dialect/IR/CIROpsEnums.h"
 #include "clang/CIR/Interfaces/CIRLoopOpInterface.h"
 #include "clang/CIR/Interfaces/CIROpInterfaces.h"
+#include "clang/CIR/MissingFeatures.h"
 
 namespace mlir {
 namespace OpTrait {
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 8319364b9e5e3..c9f4be61b2666 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -1769,6 +1769,13 @@ def FuncOp : CIR_Op<"func", [
return getFunctionType().getReturnTypes();
 }
 
+// TODO(cir): this should be an operand attribute, but for now we just 
hard-
+// wire this as a function. Will later add a $no_proto argument to this op.
+bool getNoProto() {
+  assert(!cir::MissingFeatures::opFuncNoProto());
+  return false;
+}
+
 
//===--===//
 // SymbolOpInterface Methods
 
//===--===//
@@ -1789,6 +1796,41 @@ class CIR_CallOpBase 
extra_traits = []>
  !listconcat(extra_traits,
  [DeclareOpInterfaceMethods,
   DeclareOpInterfaceMethods])> {
+  let extraClassDeclaration = [{
+/// Get the argument operands to the called function.
+mlir::OperandRange getArgOperands() {
+  return getArgs();
+}
+
+mlir::MutableOperandRange getArgOperandsMutable() {
+  return getArgsMutable();
+}
+
+/// Return the callee of this operation
+mlir::CallInterfaceCallable getCallableForCallee() {
+  return (*this)->getAttrOfType("callee");
+}
+
+/// Set the callee for this operation.
+void setCalleeFromCallable(::mlir::CallInterfaceCallable callee) {
+  (*this)->setAttr(getCalleeAttrName(),
+   mlir::cast(callee));
+}
+
+mlir::ArrayAttr getArgAttrsAttr() { return {}; }
+::mlir::ArrayAttr getResAttrsAttr() { return {}; }
+
+void setResAttrsAttr(::mlir::ArrayAttr attrs) {}
+void setArgAttrsAttr(::mlir::ArrayAttr at

[clang] [llvm] [mlir] [AMDGPU] Generalize global.load.lds to buffer fat pointers (PR #134911)

2025-05-01 Thread Matt Arsenault via cfe-commits

arsenm wrote:

Close in favor of #137425?

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


[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits


@@ -446,8 +446,31 @@ OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
 // CallOp
 
//===--===//
 
+mlir::Operation::operand_iterator cir::CallOp::arg_operand_begin() {
+  assert(!cir::MissingFeatures::opCallIndirect());

Lancern wrote:

This function has been removed in the latest change.

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


[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits


@@ -21,9 +21,24 @@ let cppNamespace = "::cir" in {
   // The CIRCallOpInterface must be used instead of CallOpInterface when 
looking
   // at arguments and other bits of CallOp. This creates a level of abstraction
   // that's useful for handling indirect calls and other details.
-  def CIRCallOpInterface : OpInterface<"CIRCallOpInterface", []> {
+  def CIRCallOpInterface : OpInterface<"CIRCallOpInterface", 
[CallOpInterface]> {
 // Currently we don't have any methods defined in CIRCallOpInterface. We'll
 // add more methods as the upstreaming proceeds.
+let methods = [
+  InterfaceMethod<"", "mlir::Operation::operand_iterator",
+  "arg_operand_begin", (ins)>,
+  InterfaceMethod<"", "mlir::Operation::operand_iterator",
+  "arg_operand_end", (ins)>,

Lancern wrote:

I have confirmed that these two functions are not used in this PR and I removed 
them for now. We could add them back if they're proven necessary in future 
upstreaming works.

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


[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits


@@ -1516,6 +1520,41 @@ class CIR_CallOpBase 
extra_traits = []>
  !listconcat(extra_traits,
  [DeclareOpInterfaceMethods,
   DeclareOpInterfaceMethods])> {
+  let extraClassDeclaration = [{
+/// Get the argument operands to the called function.
+mlir::OperandRange getArgOperands() {
+  return {arg_operand_begin(), arg_operand_end()};
+}
+
+mlir::MutableOperandRange getArgOperandsMutable() {
+  llvm_unreachable("NYI");

Lancern wrote:

This function is required by `CallOpInterface` and we have to keep it here. I 
have added the implementation for this function in the latest change, though.

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


[clang] [Clang][SYCL] Add initial set of Intel OffloadArch values (PR #138158)

2025-05-01 Thread Justin Cai via cfe-commits

https://github.com/jzc updated https://github.com/llvm/llvm-project/pull/138158

>From f1b0e2cbe8229ba00956e0eac58f97d71995b0dd Mon Sep 17 00:00:00 2001
From: "Cai, Justin" 
Date: Mon, 14 Apr 2025 21:30:39 +
Subject: [PATCH 1/2] [Clang][SYCL] Add initial set of Intel OffloadArch values

---
 clang/include/clang/Basic/OffloadArch.h   | 19 
 clang/lib/Basic/OffloadArch.cpp   |  4 +++
 clang/lib/Basic/Targets/NVPTX.cpp |  2 ++
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |  2 ++
 clang/unittests/Basic/CMakeLists.txt  |  1 +
 clang/unittests/Basic/OffloadArchTest.cpp | 36 +++
 6 files changed, 64 insertions(+)
 create mode 100644 clang/unittests/Basic/OffloadArchTest.cpp

diff --git a/clang/include/clang/Basic/OffloadArch.h 
b/clang/include/clang/Basic/OffloadArch.h
index c5ccd17e7a8be..c681f99f2e146 100644
--- a/clang/include/clang/Basic/OffloadArch.h
+++ b/clang/include/clang/Basic/OffloadArch.h
@@ -101,6 +101,13 @@ enum class OffloadArch {
   AMDGCNSPIRV,
   Generic, // A processor model named 'generic' if the target backend defines a
// public one.
+  // Note: this is an initial list of Intel GPU and GPU offloading
+  // architectures. The list will be expanded later as support for more
+  // architectures is added.
+  // Intel CPUs
+  GRANITERAPIDS,
+  // Intel GPUs
+  BMG_G21,
   LAST,
 
   CudaDefault = OffloadArch::SM_52,
@@ -116,6 +123,18 @@ static inline bool IsAMDOffloadArch(OffloadArch A) {
   return A >= OffloadArch::GFX600 && A < OffloadArch::Generic;
 }
 
+static inline bool IsIntelCPUOffloadArch(OffloadArch Arch) {
+  return Arch >= OffloadArch::GRANITERAPIDS && Arch < OffloadArch::BMG_G21;
+}
+
+static inline bool IsIntelGPUOffloadArch(OffloadArch Arch) {
+  return Arch >= OffloadArch::BMG_G21 && Arch < OffloadArch::LAST;
+}
+
+static inline bool IsIntelOffloadArch(OffloadArch Arch) {
+  return IsIntelCPUOffloadArch(Arch) || IsIntelGPUOffloadArch(Arch);
+}
+
 const char *OffloadArchToString(OffloadArch A);
 const char *OffloadArchToVirtualArchString(OffloadArch A);
 
diff --git a/clang/lib/Basic/OffloadArch.cpp b/clang/lib/Basic/OffloadArch.cpp
index 5e29742478b99..a019f0ac18c84 100644
--- a/clang/lib/Basic/OffloadArch.cpp
+++ b/clang/lib/Basic/OffloadArch.cpp
@@ -87,6 +87,10 @@ static const OffloadArchToStringMap ArchNames[] = {
 GFX(1200), // gfx1200
 GFX(1201), // gfx1201
 {OffloadArch::AMDGCNSPIRV, "amdgcnspirv", "compute_amdgcn"},
+// Intel CPUs
+{OffloadArch::GRANITERAPIDS, "graniterapids", ""},
+// Intel GPUS
+{OffloadArch::BMG_G21, "bmg_g21", ""},
 {OffloadArch::Generic, "generic", ""},
 // clang-format on
 };
diff --git a/clang/lib/Basic/Targets/NVPTX.cpp 
b/clang/lib/Basic/Targets/NVPTX.cpp
index 08c8460045c6a..42b66d3559f6a 100644
--- a/clang/lib/Basic/Targets/NVPTX.cpp
+++ b/clang/lib/Basic/Targets/NVPTX.cpp
@@ -241,6 +241,8 @@ void NVPTXTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   case OffloadArch::GFX1201:
   case OffloadArch::AMDGCNSPIRV:
   case OffloadArch::Generic:
+  case OffloadArch::GRANITERAPIDS:
+  case OffloadArch::BMG_G21:
   case OffloadArch::LAST:
 break;
   case OffloadArch::UNKNOWN:
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 59a5f7b914ce5..aa97422d54ede 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -2334,6 +2334,8 @@ void CGOpenMPRuntimeGPU::processRequiresDirective(const 
OMPRequiresDecl *D) {
   case OffloadArch::GFX1201:
   case OffloadArch::AMDGCNSPIRV:
   case OffloadArch::Generic:
+  case OffloadArch::GRANITERAPIDS:
+  case OffloadArch::BMG_G21:
   case OffloadArch::UNUSED:
   case OffloadArch::UNKNOWN:
 break;
diff --git a/clang/unittests/Basic/CMakeLists.txt 
b/clang/unittests/Basic/CMakeLists.txt
index b0e0a97168757..8c8baa57b64e7 100644
--- a/clang/unittests/Basic/CMakeLists.txt
+++ b/clang/unittests/Basic/CMakeLists.txt
@@ -7,6 +7,7 @@ add_distinct_clang_unittest(BasicTests
   FileEntryTest.cpp
   FileManagerTest.cpp
   LineOffsetMappingTest.cpp
+  OffloadArchTest.cpp
   SanitizersTest.cpp
   SarifTest.cpp
   SourceManagerTest.cpp
diff --git a/clang/unittests/Basic/OffloadArchTest.cpp 
b/clang/unittests/Basic/OffloadArchTest.cpp
new file mode 100644
index 0..c19ad0043d774
--- /dev/null
+++ b/clang/unittests/Basic/OffloadArchTest.cpp
@@ -0,0 +1,36 @@
+//===- unittests/Basic/OffloadArchTest.cpp - Test OffloadArch ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Basic/OffloadArch.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+TEST(OffloadArchTest, basic) {
+  E

[clang] [CIR] Upstream cir.call with scalar arguments (PR #136810)

2025-05-01 Thread Sirui Mu via cfe-commits

Lancern wrote:

Rebased onto the latest `main`. Will land later if no one have more comments.

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


[clang] 334e05b - [nfc] Fix formatting in clang release notes (#138172)

2025-05-01 Thread via cfe-commits

Author: Alan Zhao
Date: 2025-05-01T10:58:29-07:00
New Revision: 334e05b4b78a5de6efdcb23f208f3453a5b364a0

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

LOG: [nfc] Fix formatting in clang release notes (#138172)

`-ftime-report` was supposed to be an inline code section, which
requires two backticks instead of one.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b1bc087322c72..76e811653aa9b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,7 +281,7 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
-- New option ``-ftime-report-json`` added which outputs the same timing data 
as `-ftime-report` but formatted as JSON.
+- New option ``-ftime-report-json`` added which outputs the same timing data 
as ``-ftime-report`` but formatted as JSON.
 
 Deprecated Compiler Flags
 -



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


[clang] [nfc] Fix formatting in clang release notes (PR #138172)

2025-05-01 Thread Arthur Eubanks via cfe-commits

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


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


[clang] [nfc] Fix formatting in clang release notes (PR #138172)

2025-05-01 Thread Alan Zhao via cfe-commits

https://github.com/alanzhao1 created 
https://github.com/llvm/llvm-project/pull/138172

`-ftime-report` was supposed to be an inline code section, which requires two 
backticks instead of one.

>From da4f614cb810cb668c53ba1806802b8b01e4960b Mon Sep 17 00:00:00 2001
From: Alan Zhao 
Date: Thu, 1 May 2025 10:52:07 -0700
Subject: [PATCH] [nfc] Fix formatting in clang release notes

`-ftime-report` was supposed to be an inline code section, which
requires two backticks instead of one.
---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b1bc087322c72..76e811653aa9b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,7 +281,7 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
-- New option ``-ftime-report-json`` added which outputs the same timing data 
as `-ftime-report` but formatted as JSON.
+- New option ``-ftime-report-json`` added which outputs the same timing data 
as ``-ftime-report`` but formatted as JSON.
 
 Deprecated Compiler Flags
 -

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


[clang] [llvm] [mlir] [AMDGPU] Generalize global.load.lds to buffer fat pointers (PR #134911)

2025-05-01 Thread Krzysztof Drewniak via cfe-commits

krzysz00 wrote:

Closing in favor of #137425

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


[clang] [llvm] [mlir] [AMDGPU] Generalize global.load.lds to buffer fat pointers (PR #134911)

2025-05-01 Thread Krzysztof Drewniak via cfe-commits

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


[clang] [OpenMP 6.0 ]Codegen for Reduction over private variables with reduction clause (PR #134709)

2025-05-01 Thread CHANDRA GHALE via cfe-commits

https://github.com/chandraghale updated 
https://github.com/llvm/llvm-project/pull/134709

>From a05af192052de8503fb4945bfb853b3f2c14e4c9 Mon Sep 17 00:00:00 2001
From: Chandra Ghale 
Date: Mon, 7 Apr 2025 13:58:25 -0500
Subject: [PATCH 1/6] Codegen for Reduction over private variables with
 reduction clause

---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 147 +++
 clang/lib/CodeGen/CGOpenMPRuntime.h   |  14 ++
 clang/lib/CodeGen/CGStmtOpenMP.cpp|  12 +-
 .../OpenMP/for_private_reduction_codegen.cpp  | 236 ++
 4 files changed, 406 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/OpenMP/for_private_reduction_codegen.cpp

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 06a652c146fb9..3424227e5da79 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -4899,6 +4899,150 @@ void 
CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
   }
 }
 
+void CGOpenMPRuntime::emitPrivateReduction(
+CodeGenFunction &CGF, SourceLocation Loc, ArrayRef Privates,
+ArrayRef LHSExprs, ArrayRef RHSExprs,
+ArrayRef ReductionOps) {
+
+  if (LHSExprs.empty() || Privates.empty() || ReductionOps.empty())
+return;
+
+  if (LHSExprs.size() != Privates.size() ||
+  LHSExprs.size() != ReductionOps.size())
+return;
+
+  QualType PrivateType = Privates[0]->getType();
+  llvm::Type *LLVMType = CGF.ConvertTypeForMem(PrivateType);
+
+  BinaryOperatorKind MainBO = BO_Comma;
+  if (const auto *BinOp = dyn_cast(ReductionOps[0])) {
+if (const auto *RHSExpr = BinOp->getRHS()) {
+  if (const auto *BORHS =
+  dyn_cast(RHSExpr->IgnoreParenImpCasts())) {
+MainBO = BORHS->getOpcode();
+  }
+}
+  }
+
+  llvm::Constant *InitVal = llvm::Constant::getNullValue(LLVMType);
+  const Expr *Private = Privates[0];
+
+  if (const auto *DRE = dyn_cast(Private)) {
+if (const auto *VD = dyn_cast(DRE->getDecl())) {
+  if (const Expr *Init = VD->getInit()) {
+if (Init->isConstantInitializer(CGF.getContext(), false)) {
+  Expr::EvalResult Result;
+  if (Init->EvaluateAsRValue(Result, CGF.getContext())) {
+APValue &InitValue = Result.Val;
+if (InitValue.isInt()) {
+  InitVal = llvm::ConstantInt::get(LLVMType, InitValue.getInt());
+}
+  }
+}
+  }
+}
+  }
+
+  // Create an internal shared variable
+  std::string SharedName = getName({"internal_private_var"});
+  llvm::GlobalVariable *SharedVar = new llvm::GlobalVariable(
+  CGM.getModule(), LLVMType, false, llvm::GlobalValue::CommonLinkage,
+  InitVal, ".omp.reduction." + SharedName, nullptr,
+  llvm::GlobalVariable::NotThreadLocal);
+
+  SharedVar->setAlignment(
+  llvm::MaybeAlign(CGF.getContext().getTypeAlign(PrivateType) / 8));
+
+  Address SharedResult(SharedVar, SharedVar->getValueType(),
+   CGF.getContext().getTypeAlignInChars(PrivateType));
+
+  llvm::Value *ThreadId = getThreadID(CGF, Loc);
+  llvm::Value *BarrierLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
+  llvm::Value *BarrierArgs[] = {BarrierLoc, ThreadId};
+
+  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
+  CGM.getModule(), OMPRTL___kmpc_barrier),
+  BarrierArgs);
+
+  llvm::BasicBlock *InitBB = CGF.createBasicBlock("init");
+  llvm::BasicBlock *InitEndBB = CGF.createBasicBlock("init.end");
+
+  llvm::Value *IsWorker = CGF.Builder.CreateICmpEQ(
+  ThreadId, llvm::ConstantInt::get(ThreadId->getType(), 0));
+  CGF.Builder.CreateCondBr(IsWorker, InitBB, InitEndBB);
+
+  CGF.EmitBlock(InitBB);
+  CGF.Builder.CreateStore(InitVal, SharedResult);
+  CGF.Builder.CreateBr(InitEndBB);
+
+  CGF.EmitBlock(InitEndBB);
+
+  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
+  CGM.getModule(), OMPRTL___kmpc_barrier),
+  BarrierArgs);
+
+  for (unsigned I = 0; I < ReductionOps.size(); ++I) {
+if (I >= LHSExprs.size()) {
+  break;
+}
+
+const auto *BinOp = dyn_cast(ReductionOps[I]);
+if (!BinOp || BinOp->getOpcode() != BO_Assign)
+  continue;
+
+const Expr *RHSExpr = BinOp->getRHS();
+if (!RHSExpr)
+  continue;
+
+BinaryOperatorKind BO = BO_Comma;
+if (const auto *BORHS =
+dyn_cast(RHSExpr->IgnoreParenImpCasts())) {
+  BO = BORHS->getOpcode();
+}
+
+LValue SharedLV = CGF.MakeAddrLValue(SharedResult, PrivateType);
+LValue LHSLV = CGF.EmitLValue(LHSExprs[I]);
+RValue PrivateRV = CGF.EmitLoadOfLValue(LHSLV, Loc);
+auto &&UpdateOp = [&CGF, PrivateRV, BinOp, BO](RValue OldVal) {
+  if (BO == BO_Mul) {
+llvm::Value *OldScalar = OldVal.getScalarVal();
+llvm::Value *PrivateScalar = PrivateRV.getScalarVal();
+llvm::Value *Result = CGF.Builder.CreateMul(OldScalar, PrivateScalar);
+ret

[clang] [nfc] Fix formatting in clang release notes (PR #138172)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alan Zhao (alanzhao1)


Changes

`-ftime-report` was supposed to be an inline code section, which requires two 
backticks instead of one.

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


1 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b1bc087322c72..76e811653aa9b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,7 +281,7 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
-- New option ``-ftime-report-json`` added which outputs the same timing data 
as `-ftime-report` but formatted as JSON.
+- New option ``-ftime-report-json`` added which outputs the same timing data 
as ``-ftime-report`` but formatted as JSON.
 
 Deprecated Compiler Flags
 -

``




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


[clang] [nfc] Fix formatting in clang release notes (PR #138172)

2025-05-01 Thread Alan Zhao via cfe-commits

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


[clang] [OpenMP 6.0 ]Codegen for Reduction over private variables with reduction clause (PR #134709)

2025-05-01 Thread CHANDRA GHALE via cfe-commits

https://github.com/chandraghale updated 
https://github.com/llvm/llvm-project/pull/134709

>From a05af192052de8503fb4945bfb853b3f2c14e4c9 Mon Sep 17 00:00:00 2001
From: Chandra Ghale 
Date: Mon, 7 Apr 2025 13:58:25 -0500
Subject: [PATCH 1/7] Codegen for Reduction over private variables with
 reduction clause

---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 147 +++
 clang/lib/CodeGen/CGOpenMPRuntime.h   |  14 ++
 clang/lib/CodeGen/CGStmtOpenMP.cpp|  12 +-
 .../OpenMP/for_private_reduction_codegen.cpp  | 236 ++
 4 files changed, 406 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/OpenMP/for_private_reduction_codegen.cpp

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 06a652c146fb9..3424227e5da79 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -4899,6 +4899,150 @@ void 
CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
   }
 }
 
+void CGOpenMPRuntime::emitPrivateReduction(
+CodeGenFunction &CGF, SourceLocation Loc, ArrayRef Privates,
+ArrayRef LHSExprs, ArrayRef RHSExprs,
+ArrayRef ReductionOps) {
+
+  if (LHSExprs.empty() || Privates.empty() || ReductionOps.empty())
+return;
+
+  if (LHSExprs.size() != Privates.size() ||
+  LHSExprs.size() != ReductionOps.size())
+return;
+
+  QualType PrivateType = Privates[0]->getType();
+  llvm::Type *LLVMType = CGF.ConvertTypeForMem(PrivateType);
+
+  BinaryOperatorKind MainBO = BO_Comma;
+  if (const auto *BinOp = dyn_cast(ReductionOps[0])) {
+if (const auto *RHSExpr = BinOp->getRHS()) {
+  if (const auto *BORHS =
+  dyn_cast(RHSExpr->IgnoreParenImpCasts())) {
+MainBO = BORHS->getOpcode();
+  }
+}
+  }
+
+  llvm::Constant *InitVal = llvm::Constant::getNullValue(LLVMType);
+  const Expr *Private = Privates[0];
+
+  if (const auto *DRE = dyn_cast(Private)) {
+if (const auto *VD = dyn_cast(DRE->getDecl())) {
+  if (const Expr *Init = VD->getInit()) {
+if (Init->isConstantInitializer(CGF.getContext(), false)) {
+  Expr::EvalResult Result;
+  if (Init->EvaluateAsRValue(Result, CGF.getContext())) {
+APValue &InitValue = Result.Val;
+if (InitValue.isInt()) {
+  InitVal = llvm::ConstantInt::get(LLVMType, InitValue.getInt());
+}
+  }
+}
+  }
+}
+  }
+
+  // Create an internal shared variable
+  std::string SharedName = getName({"internal_private_var"});
+  llvm::GlobalVariable *SharedVar = new llvm::GlobalVariable(
+  CGM.getModule(), LLVMType, false, llvm::GlobalValue::CommonLinkage,
+  InitVal, ".omp.reduction." + SharedName, nullptr,
+  llvm::GlobalVariable::NotThreadLocal);
+
+  SharedVar->setAlignment(
+  llvm::MaybeAlign(CGF.getContext().getTypeAlign(PrivateType) / 8));
+
+  Address SharedResult(SharedVar, SharedVar->getValueType(),
+   CGF.getContext().getTypeAlignInChars(PrivateType));
+
+  llvm::Value *ThreadId = getThreadID(CGF, Loc);
+  llvm::Value *BarrierLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
+  llvm::Value *BarrierArgs[] = {BarrierLoc, ThreadId};
+
+  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
+  CGM.getModule(), OMPRTL___kmpc_barrier),
+  BarrierArgs);
+
+  llvm::BasicBlock *InitBB = CGF.createBasicBlock("init");
+  llvm::BasicBlock *InitEndBB = CGF.createBasicBlock("init.end");
+
+  llvm::Value *IsWorker = CGF.Builder.CreateICmpEQ(
+  ThreadId, llvm::ConstantInt::get(ThreadId->getType(), 0));
+  CGF.Builder.CreateCondBr(IsWorker, InitBB, InitEndBB);
+
+  CGF.EmitBlock(InitBB);
+  CGF.Builder.CreateStore(InitVal, SharedResult);
+  CGF.Builder.CreateBr(InitEndBB);
+
+  CGF.EmitBlock(InitEndBB);
+
+  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
+  CGM.getModule(), OMPRTL___kmpc_barrier),
+  BarrierArgs);
+
+  for (unsigned I = 0; I < ReductionOps.size(); ++I) {
+if (I >= LHSExprs.size()) {
+  break;
+}
+
+const auto *BinOp = dyn_cast(ReductionOps[I]);
+if (!BinOp || BinOp->getOpcode() != BO_Assign)
+  continue;
+
+const Expr *RHSExpr = BinOp->getRHS();
+if (!RHSExpr)
+  continue;
+
+BinaryOperatorKind BO = BO_Comma;
+if (const auto *BORHS =
+dyn_cast(RHSExpr->IgnoreParenImpCasts())) {
+  BO = BORHS->getOpcode();
+}
+
+LValue SharedLV = CGF.MakeAddrLValue(SharedResult, PrivateType);
+LValue LHSLV = CGF.EmitLValue(LHSExprs[I]);
+RValue PrivateRV = CGF.EmitLoadOfLValue(LHSLV, Loc);
+auto &&UpdateOp = [&CGF, PrivateRV, BinOp, BO](RValue OldVal) {
+  if (BO == BO_Mul) {
+llvm::Value *OldScalar = OldVal.getScalarVal();
+llvm::Value *PrivateScalar = PrivateRV.getScalarVal();
+llvm::Value *Result = CGF.Builder.CreateMul(OldScalar, PrivateScalar);
+ret

[clang] bc9aa0f - [C] Add -Wtentative-definition-compat (#137967)

2025-05-01 Thread via cfe-commits

Author: Aaron Ballman
Date: 2025-05-01T07:31:48-04:00
New Revision: bc9aa0f4c4c6ad9dd6207097478f4e461a8fe5cb

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

LOG: [C] Add -Wtentative-definition-compat (#137967)

This adds a new diagnostic to warn about redeclaration of a tentative
definition in C. This is incompatible with C++, so the new diagnostic
group is under -Wc++-compat.

Added: 
clang/test/Sema/warn-tentative-defn-compat.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/warn-default-const-init.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65ae5945ca27c..1dd97bcc67364 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -175,6 +175,15 @@ C Language Changes
   ``-Wenum-conversion`` and ``-Wimplicit-int-enum-cast``. This conversion is an
   int-to-enum conversion because the enumeration on the right-hand side is
   promoted to ``int`` before the assignment.
+- Added ``-Wtentative-definition-compat``, grouped under ``-Wc++-compat``,
+  which diagnoses tentative definitions in C with multiple declarations as
+  being incompatible with C++. e.g.,
+
+  .. code-block:: c
+
+// File scope
+int i;
+int i; // Vaild C, invalid C++, now diagnosed
 - Added ``-Wunterminated-string-initialization``, grouped under ``-Wextra``,
   which diagnoses an initialization from a string literal where only the null
   terminator cannot be stored. e.g.,

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 21d5d54e9c8c5..4f235fecf4cf9 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -176,9 +176,11 @@ def DefaultConstInit : DiagGroup<"default-const-init",
 def ImplicitVoidPtrCast : DiagGroup<"implicit-void-ptr-cast">;
 def ImplicitIntToEnumCast : DiagGroup<"implicit-int-enum-cast",
   [ImplicitEnumEnumCast]>;
+def TentativeDefnCompat : DiagGroup<"tentative-definition-compat">;
 def CXXCompat: DiagGroup<"c++-compat", [ImplicitVoidPtrCast, DefaultConstInit,
 ImplicitIntToEnumCast, HiddenCppDecl,
 InitStringTooLongForCpp,
+TentativeDefnCompat,
 DuplicateDeclSpecifier]>;
 
 def ExternCCompat : DiagGroup<"extern-c-compat">;

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c6c52f471479e..bf7017436f38c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7455,6 +7455,9 @@ def err_tentative_def_incomplete_type : Error<
 def warn_tentative_incomplete_array : Warning<
   "tentative array definition assumed to have one element">,
   InGroup>;
+def warn_cxx_compat_tentative_definition : Warning<
+  "duplicate declaration of %0 is invalid in C++">,
+  InGroup, DefaultIgnore;
 def err_typecheck_incomplete_array_needs_initializer : Error<
   "definition of variable with array type needs an explicit size "
   "or an initializer">;

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 25ee19e0ba5f1..517b3067696a0 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4750,6 +4750,9 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
+  } else {
+Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition) << 
New;
+Diag(Old->getLocation(), diag::note_previous_declaration);
   }
 
   if (haveIncompatibleLanguageLinkages(Old, New)) {

diff  --git a/clang/test/Sema/warn-default-const-init.c 
b/clang/test/Sema/warn-default-const-init.c
index da11f4189047f..ddd4aba2b5de3 100644
--- a/clang/test/Sema/warn-default-const-init.c
+++ b/clang/test/Sema/warn-default-const-init.c
@@ -1,5 +1,5 @@
 // Both of these should enable everything.
-// RUN: %clang_cc1 -fsyntax-only 
-verify=unsafe-var,unsafe-field,zero-init-var,zero-init-field -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only 
-verify=unsafe-var,unsafe-field,zero-init-var,zero-init-field -Wc++-compat 
-Wno-tentative-definition-compat %s
 // RUN: %clang_cc1 -fsyntax-only 
-verify=unsafe-var,unsafe-field,zero-init-var,zero-init-field 
-Wdefault-const-init %s
 
 // This should enable nothing.

diff  --git a/clang/test/Sema/warn-tentative-defn-compat.c 
b/clang/test/Sema/warn-tentative-defn-compat.c
new file mode 100644
index 0

[clang] [C] Add -Wtentative-definition-compat (PR #137967)

2025-05-01 Thread Aaron Ballman via cfe-commits

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


[clang-tools-extra] 212f245 - [include-cleaner] rename enabled flags to `disable-*` (#132991)

2025-05-01 Thread via cfe-commits

Author: Mohamed Emad
Date: 2025-05-01T07:21:50-04:00
New Revision: 212f2456fcde822fad37bfa4e69ced1a51a4c19d

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

LOG: [include-cleaner] rename enabled flags to `disable-*` (#132991)

Closes #132983

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/include-cleaner/test/tool.cpp
clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 8f61839af2c80..579fca54924d5 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -88,6 +88,14 @@ Improvements to clang-doc
 Improvements to clang-query
 ---
 
+Improvements to include-cleaner
+---
+- Deprecated the ``-insert`` and ``-remove`` command line options, and added
+  the ``-disable-remove`` and ``-disable-insert`` command line options as
+  replacements. The previous command line options were confusing because they
+  did not imply the default state of the option (which is inserts and removes
+  being enabled). The new options are easier to understand the semantics of.
+
 Improvements to clang-tidy
 --
 

diff  --git a/clang-tools-extra/include-cleaner/test/tool.cpp 
b/clang-tools-extra/include-cleaner/test/tool.cpp
index d72d2317ce2b1..b0a47b5ef0a14 100644
--- a/clang-tools-extra/include-cleaner/test/tool.cpp
+++ b/clang-tools-extra/include-cleaner/test/tool.cpp
@@ -6,11 +6,11 @@ int x = foo();
 //  CHANGE: - "foobar.h"
 // CHANGE-NEXT: + "foo.h"
 
-// RUN: clang-include-cleaner -remove=0 -print=changes %s -- 
-I%S/Inputs/ | FileCheck --check-prefix=INSERT %s
+// RUN: clang-include-cleaner -disable-remove -print=changes %s -- 
-I%S/Inputs/ | FileCheck --check-prefix=INSERT %s
 //  INSERT-NOT: - "foobar.h"
 //  INSERT: + "foo.h"
 
-// RUN: clang-include-cleaner -insert=0 -print=changes %s -- 
-I%S/Inputs/ | FileCheck --check-prefix=REMOVE %s
+// RUN: clang-include-cleaner -disable-insert -print=changes %s -- 
-I%S/Inputs/ | FileCheck --check-prefix=REMOVE %s
 //  REMOVE: - "foobar.h"
 //  REMOVE-NOT: + "foo.h"
 
@@ -58,3 +58,16 @@ int x = foo();
 //RUN: FileCheck --match-full-lines --check-prefix=EDIT3 %s < %t.cpp
 //  EDIT3: #include "foo.h"
 //  EDIT3-NOT: {{^}}#include "foobar.h"{{$}}
+
+//RUN: clang-include-cleaner -insert=false -print=changes %s -- 
-I%S/Inputs/ 2>&1 | \
+//RUN: FileCheck --check-prefix=DEPRECATED-INSERT %s
+// DEPRECATED-INSERT: warning: '-insert=0' is deprecated in favor of 
'-disable-insert'. The old flag was confusing since it suggested that inserts 
were disabled by default, when they were actually enabled.
+
+//   RUN: clang-include-cleaner -remove=false -print=changes %s -- 
-I%S/Inputs/ 2>&1 | \
+//   RUN: FileCheck --check-prefix=DEPRECATED-REMOVE %s
+// DEPRECATED-REMOVE: warning: '-remove=0' is deprecated in favor of 
'-disable-remove'. The old flag was confusing since it suggested that removes 
were disabled by default, when they were actually enabled.
+
+//   RUN: clang-include-cleaner -insert=false -remove=false -print=changes 
%s -- -I%S/Inputs/ 2>&1 | \
+//   RUN: FileCheck --check-prefix=DEPRECATED-BOTH %s
+// DEPRECATED-BOTH: warning: '-insert=0' is deprecated in favor of 
'-disable-insert'. The old flag was confusing since it suggested that inserts 
were disabled by default, when they were actually enabled.
+// DEPRECATED-BOTH: warning: '-remove=0' is deprecated in favor of 
'-disable-remove'. The old flag was confusing since it suggested that removes 
were disabled by default, when they were actually enabled.

diff  --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 1d9458ffc4d32..33490de9b0f6c 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -90,19 +90,31 @@ cl::opt Edit{
 cl::desc("Apply edits to analyzed source files"),
 cl::cat(IncludeCleaner),
 };
-
 cl::opt Insert{
 "insert",
-cl::desc("Allow header insertions"),
+cl::desc(
+"Allow header insertions (deprecated. Use -disable-insert instead)"),
 cl::init(true),
 cl::cat(IncludeCleaner),
 };
 cl::opt Remove{
 "remove",
-cl::desc("Allow header removals"),
+cl::desc("Allow header removals (deprecated. Use -disable-remove 
instead)"),
 cl::init(true),
 cl::cat(IncludeCleaner),
 };
+cl::opt DisableInsert{
+"disable-insert",
+cl::desc("Disable header insertions"),
+cl::init(false),
+cl::cat(IncludeClean

[clang] [OpenMP 6.0 ]Codegen for Reduction over private variables with reduction clause (PR #134709)

2025-05-01 Thread CHANDRA GHALE via cfe-commits

chandraghale wrote:

Refactored code to look up the expression and handle UDR, emitting it as is.  
updated the lit test.

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


[clang-tools-extra] [include-cleaner] rename enabled flags to `disable-*` (PR #132991)

2025-05-01 Thread Aaron Ballman via cfe-commits

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


[clang] [llvm] [LLVM][Clang][Cygwin] Fix building Clang for Cygwin (PR #134494)

2025-05-01 Thread Mateusz Mikuła via cfe-commits

https://github.com/mati865 updated 
https://github.com/llvm/llvm-project/pull/134494

From b7a5fab29b810f72f2ffa65fb0945abd302c2411 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Sat, 5 Apr 2025 13:18:35 +0200
Subject: [PATCH 1/4] [LLVM][Cygwin] Fix Signals compatibility with Cygwin API
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Cygwin types sometimes do not match Linux exactly. Like in this case:
```
In file included from 
/h/projects/llvm-project/llvm/include/llvm/Support/Error.h:23,
 from 
/h/projects/llvm-project/llvm/include/llvm/Support/FileSystem.h:34,
 from /h/projects/llvm-project/llvm/lib/Support/Signals.cpp:22:
/h/projects/llvm-project/llvm/include/llvm/Support/Format.h: In instantiation 
of ‘llvm::format_object::format_object(const char*, const Ts& ...) [with Ts 
= {int, char [4096]}]’:
/h/projects/llvm-project/llvm/include/llvm/Support/Format.h:126:10:   required 
from ‘llvm::format_object llvm::format(const char*, const Ts& ...) 
[with Ts = {int, char [4096]}]’
/h/projects/llvm-project/llvm/lib/Support/Unix/Signals.inc:850:19:   required 
from here
/h/projects/llvm-project/llvm/include/llvm/Support/Format.h:106:34: error: no 
matching function for call to ‘std::tuple::tuple(const int&, 
const char [4096])’
  106 |   : format_object_base(fmt), Vals(vals...) {
  |  ^
```
Casting here is safe and solves the issue.
---
 llvm/lib/Support/Unix/Signals.inc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/Support/Unix/Signals.inc 
b/llvm/lib/Support/Unix/Signals.inc
index 30e5f40193974..691e1014f18e8 100644
--- a/llvm/lib/Support/Unix/Signals.inc
+++ b/llvm/lib/Support/Unix/Signals.inc
@@ -847,7 +847,7 @@ void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) 
{
 
 const char *name = strrchr(dlinfo.dli_fname, '/');
 if (!name)
-  OS << format(" %-*s", width, dlinfo.dli_fname);
+  OS << format(" %-*s", width, static_cast(dlinfo.dli_fname));
 else
   OS << format(" %-*s", width, name + 1);
 

From a04d045f298970e9d8a391100071125a97264196 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Sat, 8 Feb 2025 13:57:49 +0100
Subject: [PATCH 2/4] [Clang][Cygwin] Fix symbol visibility definition
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Currently building for Cygwin hits this error:
```
In file included from 
/h/projects/llvm-project/clang/lib/Basic/Attributes.cpp:17:
/h/projects/llvm-project/clang/include/clang/Basic/ParsedAttrInfo.h:180:73: 
error: invalid declarator before ‘;’ token
  180 | extern template class CLANG_TEMPLATE_ABI 
Registry;
```
That's because `CLANG_TEMPLATE_ABI` ends up not being defined.
The solution here is to follow MinGW case.
---
 clang/include/clang/Support/Compiler.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Support/Compiler.h 
b/clang/include/clang/Support/Compiler.h
index 5a74f8e3b6723..e1ae3eda4ccc2 100644
--- a/clang/include/clang/Support/Compiler.h
+++ b/clang/include/clang/Support/Compiler.h
@@ -50,7 +50,7 @@
 #define CLANG_EXPORT_TEMPLATE
 #endif
 #elif defined(__ELF__) || defined(__MINGW32__) || defined(_AIX) || 
\
-defined(__MVS__)
+defined(__MVS__) || defined(__CYGWIN__)
 #define CLANG_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_TEMPLATE_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_EXPORT_TEMPLATE

From 94ec9d3f52024c671915ad0a1988c5dd6778eb05 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Fri, 4 Apr 2025 15:08:18 +0200
Subject: [PATCH 3/4] [Clang][Cygwin] Disable shared libs on Cygwin by default

This change follows MinGW decisions, otherwise build with GCC fail with:
```
FAILED: bin/msys-clang-cpp-21.0git.dll lib/libclang-cpp.dll.a
...
/usr/lib/gcc/x86_64-pc-msys/13.3.0/../../../../x86_64-pc-msys/bin/ld: error: 
export ordinal too large: 92250
```

Co-authored-by: jeremyd2019 
---
 clang/tools/CMakeLists.txt  | 5 +++--
 clang/tools/libclang/CMakeLists.txt | 3 ++-
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/tools/CMakeLists.txt b/clang/tools/CMakeLists.txt
index 9634eb12080c8..50e3d694236ac 100644
--- a/clang/tools/CMakeLists.txt
+++ b/clang/tools/CMakeLists.txt
@@ -26,9 +26,10 @@ endif()
 add_clang_subdirectory(c-index-test)
 
 add_clang_subdirectory(clang-refactor)
-# For MinGW we only enable shared library if LLVM_LINK_LLVM_DYLIB=ON.
+# For MinGW/Cygwin we only enable shared library if LLVM_LINK_LLVM_DYLIB=ON.
 # Without that option resulting library is too close to 2^16 DLL exports limit.
-if(UNIX OR (MSVC AND LLVM_BUILD_LLVM_DYLIB_VIS) OR (MINGW AND 
LLVM_LINK_LLVM_DYLIB))
+if((UNIX AND NOT CYGWIN) OR (MSVC AND LLVM_BUILD_LLVM_DYLIB_VIS) OR
+  ((MINGW OR CYGWIN) AND LLVM_LINK_LLVM_DYLIB))
   add_clang_subdirectory(clang-shlib)
 endif()
 
diff --git

[clang] 75d1cce - Add missing RUN lines to test

2025-05-01 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2025-05-01T07:25:28-04:00
New Revision: 75d1cceb948666af9b2cb26fc3933d4176a2806d

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

LOG: Add missing RUN lines to test

These were intended to be present when 00f9ef282c7482754a0fea497417604d1deca9fa
landed

Added: 


Modified: 
clang/test/Sema/warn-default-const-init.c

Removed: 




diff  --git a/clang/test/Sema/warn-default-const-init.c 
b/clang/test/Sema/warn-default-const-init.c
index b6c593e578bd5..da11f4189047f 100644
--- a/clang/test/Sema/warn-default-const-init.c
+++ b/clang/test/Sema/warn-default-const-init.c
@@ -1,5 +1,28 @@
+// Both of these should enable everything.
+// RUN: %clang_cc1 -fsyntax-only 
-verify=unsafe-var,unsafe-field,zero-init-var,zero-init-field -Wc++-compat %s
+// RUN: %clang_cc1 -fsyntax-only 
-verify=unsafe-var,unsafe-field,zero-init-var,zero-init-field 
-Wdefault-const-init %s
+
+// This should enable nothing.
+// RUN: %clang_cc1 -fsyntax-only -verify=good -Wno-default-const-init-unsafe %s
+
+// Only unsafe field and variable diagnostics
+// RUN: %clang_cc1 -fsyntax-only -verify=unsafe-var,unsafe-field %s
 // RUN: %clang_cc1 -fsyntax-only -verify=unsafe-var,unsafe-field 
-Wdefault-const-init-unsafe %s
 
+// Only zero init field and variable diagnostics
+// RUN: %clang_cc1 -fsyntax-only -verify=zero-init-var,zero-init-field 
-Wdefault-const-init -Wno-default-const-init-unsafe %s
+
+// Only zero init and unsafe field diagnostics
+// RUN: %clang_cc1 -fsyntax-only -verify=zero-init-field,unsafe-field 
-Wno-default-const-init-var-unsafe -Wdefault-const-init-field %s
+
+// Only zero init and unsafe variable diagnostics
+// RUN: %clang_cc1 -fsyntax-only -verify=zero-init-var,unsafe-var 
-Wno-default-const-init-field-unsafe -Wdefault-const-init-var %s
+
+// C++ tests
+// RUN: %clang_cc1 -fsyntax-only -verify=cxx -x c++ %s
+
+// good-no-diagnostics
+
 struct A { int i; };
 struct S{ const int i; };  // unsafe-field-note 2 {{member 'i' 
declared 'const' here}} \
   cxx-note 3 {{default constructor of 
'S' is implicitly deleted because field 'i' of const-qualified type 'const int' 
would not be initialized}}
@@ -45,7 +68,7 @@ static const int j; // zero-init-var-warning {{default 
initialization of an obje
cxx-error {{default initialization of an object of 
const type 'const int'}}
 const int k;// zero-init-var-warning {{default initialization of an 
object of type 'const int' is incompatible with C++}} \
cxx-error {{default initialization of an object of 
const type 'const int'}}
-const struct S s;   // zero-init-field-warning {{default initialization of an 
object of type 'const struct S' is incompatible with C++}} \
+const struct S s;   // zero-init-var-warning {{default initialization of an 
object of type 'const struct S' is incompatible with C++}} \
cxx-error {{call to implicitly-deleted default 
constructor of 'const struct S'}}
 
 void func() {



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


[clang] [llvm] [LLVM][Clang][Cygwin] Fix building Clang for Cygwin (PR #134494)

2025-05-01 Thread Mateusz Mikuła via cfe-commits

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


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

2025-05-01 Thread Matt Arsenault via cfe-commits


@@ -23,4 +23,20 @@
 #define _CLC_DEF __attribute__((always_inline))
 #endif
 
+#if __OPENCL_C_VERSION__ == CL_VERSION_2_0 ||  
\
+(__OPENCL_C_VERSION__ >= CL_VERSION_3_0 && 
\
+ defined(__opencl_c_generic_address_space))
+#define _CLC_GENERIC_AS_SUPPORTED 1
+// Note that we hard-code the assumption that a non-distinct address space 
means
+// that the target maps the generic address space to the private address space.
+#ifdef __CLC_DISTINCT_GENERIC_ADDRSPACE__
+#define _CLC_DISTINCT_GENERIC_AS_SUPPORTED 1
+#else
+#define _CLC_DISTINCT_GENERIC_AS_SUPPORTED 0
+#endif
+#else

arsenm wrote:

This is ultimately a clang bug. The two functions are different symbols. 
addressSpaceMapManglingFor shouldn't be reporting true in the colliding cases 

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


[clang] [Clang][Cygwin] Fix symbol visibility definition (PR #138118)

2025-05-01 Thread Mateusz Mikuła via cfe-commits

https://github.com/mati865 created 
https://github.com/llvm/llvm-project/pull/138118

Currently building for Cygwin hits this error:
```
In file included from 
/h/projects/llvm-project/clang/lib/Basic/Attributes.cpp:17:
/h/projects/llvm-project/clang/include/clang/Basic/ParsedAttrInfo.h:180:73: 
error: invalid declarator before ‘;’ token
  180 | extern template class CLANG_TEMPLATE_ABI 
Registry;
```
That's because `CLANG_TEMPLATE_ABI` ends up not being defined. The solution 
here is to follow MinGW case.

Split out from https://github.com/llvm/llvm-project/pull/134494

From 41a22fcdb5d1c62ca47825039230c3dc03ccaf5e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= 
Date: Sat, 8 Feb 2025 13:57:49 +0100
Subject: [PATCH] [Clang][Cygwin] Fix symbol visibility definition
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Currently building for Cygwin hits this error:
```
In file included from 
/h/projects/llvm-project/clang/lib/Basic/Attributes.cpp:17:
/h/projects/llvm-project/clang/include/clang/Basic/ParsedAttrInfo.h:180:73: 
error: invalid declarator before ‘;’ token
  180 | extern template class CLANG_TEMPLATE_ABI 
Registry;
```
That's because `CLANG_TEMPLATE_ABI` ends up not being defined.
The solution here is to follow MinGW case.
---
 clang/include/clang/Support/Compiler.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Support/Compiler.h 
b/clang/include/clang/Support/Compiler.h
index 5a74f8e3b6723..e1ae3eda4ccc2 100644
--- a/clang/include/clang/Support/Compiler.h
+++ b/clang/include/clang/Support/Compiler.h
@@ -50,7 +50,7 @@
 #define CLANG_EXPORT_TEMPLATE
 #endif
 #elif defined(__ELF__) || defined(__MINGW32__) || defined(_AIX) || 
\
-defined(__MVS__)
+defined(__MVS__) || defined(__CYGWIN__)
 #define CLANG_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_TEMPLATE_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_EXPORT_TEMPLATE

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


[clang] [flang] [llvm] [TargetVerifier][AMDGPU] Add TargetVerifier. (PR #123609)

2025-05-01 Thread via cfe-commits

https://github.com/jofrn updated 
https://github.com/llvm/llvm-project/pull/123609



  



Rate limit · GitHub


  body {
background-color: #f6f8fa;
color: #24292e;
font-family: -apple-system,BlinkMacSystemFont,Segoe 
UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
font-size: 14px;
line-height: 1.5;
margin: 0;
  }

  .container { margin: 50px auto; max-width: 600px; text-align: center; 
padding: 0 24px; }

  a { color: #0366d6; text-decoration: none; }
  a:hover { text-decoration: underline; }

  h1 { line-height: 60px; font-size: 48px; font-weight: 300; margin: 0px; 
text-shadow: 0 1px 0 #fff; }
  p { color: rgba(0, 0, 0, 0.5); margin: 20px 0 40px; }

  ul { list-style: none; margin: 25px 0; padding: 0; }
  li { display: table-cell; font-weight: bold; width: 1%; }

  .logo { display: inline-block; margin-top: 35px; }
  .logo-img-2x { display: none; }
  @media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and ( -o-min-device-pixel-ratio: 2/1),
  only screen and (min-device-pixel-ratio: 2),
  only screen and (min-resolution: 192dpi),
  only screen and (min-resolution: 2dppx) {
.logo-img-1x { display: none; }
.logo-img-2x { display: inline-block; }
  }

  #suggestions {
margin-top: 35px;
color: #ccc;
  }
  #suggestions a {
color: #66;
font-weight: 200;
font-size: 14px;
margin: 0 10px;
  }


  
  



  Whoa there!
  You have exceeded a secondary rate limit.
Please wait a few minutes before you try again;
in some cases this may take up to an hour.
  
  
https://support.github.com/contact";>Contact Support —
https://githubstatus.com";>GitHub Status —
https://twitter.com/githubstatus";>@githubstatus
  

  

  

  

  

  


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


[clang] [CIR] Upstream pointer arithmetic support (PR #138041)

2025-05-01 Thread Henrich Lauko via cfe-commits

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

lgtm, besides Erich's comments

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


[clang] [CIR] Upstream pointer arithmetic support (PR #138041)

2025-05-01 Thread Henrich Lauko via cfe-commits

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


[clang] [CIR] Upstream pointer arithmetic support (PR #138041)

2025-05-01 Thread Henrich Lauko via cfe-commits


@@ -185,6 +185,15 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
   }
   bool isInt(mlir::Type i) { return mlir::isa(i); }
 
+  //
+  // Constant creation helpers
+  // -
+  //
+  cir::ConstantOp getSInt32(int32_t c, mlir::Location loc) {
+auto sInt32Ty = getSInt32Ty();
+return create(loc, cir::IntAttr::get(sInt32Ty, c));

xlauko wrote:

```suggestion
return getConstantInt(loc, getSInt32Ty(), c);
```

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


[clang] [Clang] Do not warn for serialized builtin or command-line definitions (PR #137306)

2025-05-01 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [Clang] Do not warn for serialized builtin or command-line definitions (PR #137306)

2025-05-01 Thread Juan Manuel Martinez Caamaño via cfe-commits

jmmartinez wrote:

Thanks !

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


[clang] 0d3d2f6 - [Clang] Do not warn for serialized builtin or command-line definitions (#137306)

2025-05-01 Thread via cfe-commits

Author: Juan Manuel Martinez Caamaño
Date: 2025-05-01T09:55:46+02:00
New Revision: 0d3d2f639c42b22fc1b9453c7b834dbb0f16c0dc

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

LOG: [Clang] Do not warn for serialized builtin or command-line definitions 
(#137306)

When using `-dD` to generate a preprocessed output, the `#define`
directives
are preserved. This includes built-in and command-line definitions.

Before, clang would warn for reserved identifiers for serialized
built-in
and command-line definitions.
This patch adds an exception to these cases.

Added: 
clang/test/Preprocessor/macro_reserved.i

Modified: 
clang/lib/Lex/PPDirectives.cpp

Removed: 




diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 6c337801a8435..6468e62889413 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -371,8 +371,12 @@ bool Preprocessor::CheckMacroName(Token &MacroNameTok, 
MacroUse isDefineUndef,
   SourceLocation MacroNameLoc = MacroNameTok.getLocation();
   if (ShadowFlag)
 *ShadowFlag = false;
-  if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
-  (SourceMgr.getBufferName(MacroNameLoc) != "")) {
+  // Macro names with reserved identifiers are accepted if built-in or passed
+  // through the command line (the later may be present if -dD was used to
+  // generate the preprocessed file).
+  bool IsBuiltinOrCmd = SourceMgr.isWrittenInBuiltinFile(MacroNameLoc) ||
+SourceMgr.isWrittenInCommandLineFile(MacroNameLoc);
+  if (!IsBuiltinOrCmd && !SourceMgr.isInSystemHeader(MacroNameLoc)) {
 MacroDiag D = MD_NoWarn;
 if (isDefineUndef == MU_Define) {
   D = shouldWarnOnMacroDef(*this, II);

diff  --git a/clang/test/Preprocessor/macro_reserved.i 
b/clang/test/Preprocessor/macro_reserved.i
new file mode 100644
index 0..c9ed044e4c931
--- /dev/null
+++ b/clang/test/Preprocessor/macro_reserved.i
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -x cpp-output %s
+#pragma clang diagnostic push
+#pragma clang diagnostic warning "-Wreserved-macro-identifier"
+# 1 "" 1
+#define __BUILTIN__
+# 2 "" 1
+#define __CMD__
+# 3 "biz.cpp" 1
+#define __SOME_FILE__ // expected-warning {{macro name is a reserved 
identifier}}
+int v;
+#pragma clang diagnostic pop



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


[clang] [Clang][NFC] Use std::move to avoid copy (PR #138073)

2025-05-01 Thread via cfe-commits

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


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


[clang] [Clang] Warning as error for fold expressions over comparison operators (PR #136836)

2025-05-01 Thread Younan Zhang via cfe-commits

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

Okay, let's go ahead as is. Though I feel it's unfortunate that the warnings 
for left fold and right fold are scattered - maybe we could clean them up in 
future

Thanks for working on this.

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


[clang] [libclang/python] Add some logical typing changes. (PR #138074)

2025-05-01 Thread Jannick Kremer via cfe-commits

DeinAlptraum wrote:

Which parts do you mean? The `__eq__` operators for other objects?

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


[clang] [Clang][Cygwin] Fix symbol visibility definition (PR #138118)

2025-05-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mateusz Mikuła (mati865)


Changes

Currently building for Cygwin hits this error:
```
In file included from 
/h/projects/llvm-project/clang/lib/Basic/Attributes.cpp:17:
/h/projects/llvm-project/clang/include/clang/Basic/ParsedAttrInfo.h:180:73: 
error: invalid declarator before ‘;’ token
  180 | extern template class CLANG_TEMPLATE_ABI 
Registry;
```
That's because `CLANG_TEMPLATE_ABI` ends up not being defined. The solution 
here is to follow MinGW case.

Split out from https://github.com/llvm/llvm-project/pull/134494

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


1 Files Affected:

- (modified) clang/include/clang/Support/Compiler.h (+1-1) 


``diff
diff --git a/clang/include/clang/Support/Compiler.h 
b/clang/include/clang/Support/Compiler.h
index 5a74f8e3b6723..e1ae3eda4ccc2 100644
--- a/clang/include/clang/Support/Compiler.h
+++ b/clang/include/clang/Support/Compiler.h
@@ -50,7 +50,7 @@
 #define CLANG_EXPORT_TEMPLATE
 #endif
 #elif defined(__ELF__) || defined(__MINGW32__) || defined(_AIX) || 
\
-defined(__MVS__)
+defined(__MVS__) || defined(__CYGWIN__)
 #define CLANG_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_TEMPLATE_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
 #define CLANG_EXPORT_TEMPLATE

``




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


[clang] [C] Add -Wjump-bypasses-init (PR #138009)

2025-05-01 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

Please add a test for the new indirect goto diagnostic.  Otherwise LGTM

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


[clang] [llvm] [clang][amdgpu] Add builtins for raw/struct buffer lds load (PR #137678)

2025-05-01 Thread Krzysztof Drewniak via cfe-commits

krzysz00 wrote:

> It does, we should have a consistent set of buffer builtins

To specify what I _think_ the proposed rewrite is, it's auto-upgrading or 
otherwise transforming
```llvm
%r = call T llvm.amdgcn.{raw,struct}.buffer.*(<4 x i32> %rsrc, ...)
```
into
```llvm
%rsrc.int = bitcast <4 x i32> %rsrc to i128
%rsrc.ptr = inttoptr i128 %rsrc.int to ptr addrspace(8)
%r = call T @lvm.amdgcn.{raw,struct}.ptr.*(ptr addrspace(8) %rsrc, ...)
```

plus putting some deprecation notices on the 4xi32 versions

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


[clang-tools-extra] [llvm] [clang-doc] Adds a mustache backend (PR #133161)

2025-05-01 Thread Paul Kirth via cfe-commits

ilovepi wrote:

@PeterChou1 I've uploaded a patch set w/ the relevant changes from this patch. 
Some of the details were split into standalone patches, but I'd appreciate if 
you could help both review and test those patches. It would also be nice if you 
could share any testing corpus or lit tests you have.

I think we can leave this PR up until we actually land something in tree.

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


[clang] [Clang][OpenCL][AMDGPU] OpenCL Kernel stubs should be assigned alwaysinline attribute (PR #137769)

2025-05-01 Thread Matt Arsenault via cfe-commits

arsenm wrote:

Apparently the inliner has an arbitrary size threshold even for single uses. I 
don't see the point of that, we should probably remove that 

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


  1   2   3   4   5   6   >