[clang-tools-extra] e10f67a - [clang-doc][NFC] refactor out file helpers (#134298)

2025-04-09 Thread via cfe-commits

Author: PeterChou1
Date: 2025-04-09T17:21:28-04:00
New Revision: e10f67a8270c7745b8a9306a9910b06cfc8d2c55

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

LOG: [clang-doc][NFC] refactor out file helpers (#134298)

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

refactor the code to extract file helpers used in HTML generators for
use in other generators for clang-doc

Added: 
clang-tools-extra/clang-doc/support/CMakeLists.txt
clang-tools-extra/clang-doc/support/File.cpp
clang-tools-extra/clang-doc/support/File.h

Modified: 
clang-tools-extra/clang-doc/CMakeLists.txt
clang-tools-extra/clang-doc/HTMLGenerator.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-doc/CMakeLists.txt 
b/clang-tools-extra/clang-doc/CMakeLists.txt
index 520fe58cbe68e..f4f62c74d6592 100644
--- a/clang-tools-extra/clang-doc/CMakeLists.txt
+++ b/clang-tools-extra/clang-doc/CMakeLists.txt
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS
   BitstreamReader
   FrontendOpenMP
   )
+add_subdirectory(support)
 
 add_clang_library(clangDoc STATIC
   BitcodeReader.cpp
@@ -23,6 +24,7 @@ add_clang_library(clangDoc STATIC
 
 clang_target_link_libraries(clangDoc
   PRIVATE
+  clangDocSupport
   clangAnalysis
   clangAST
   clangASTMatchers

diff  --git a/clang-tools-extra/clang-doc/HTMLGenerator.cpp 
b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
index f559933fc2283..cb10f16804024 100644
--- a/clang-tools-extra/clang-doc/HTMLGenerator.cpp
+++ b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
@@ -8,6 +8,7 @@
 
 #include "Generators.h"
 #include "Representation.h"
+#include "support/File.h"
 #include "clang/Basic/Version.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
@@ -251,47 +252,6 @@ static void appendVector(std::vector &&New,
   std::move(New.begin(), New.end(), std::back_inserter(Original));
 }
 
-// Compute the relative path from an Origin directory to a Destination 
directory
-static SmallString<128> computeRelativePath(StringRef Destination,
-StringRef Origin) {
-  // If Origin is empty, the relative path to the Destination is its complete
-  // path.
-  if (Origin.empty())
-return Destination;
-
-  // The relative path is an empty path if both directories are the same.
-  if (Destination == Origin)
-return {};
-
-  // These iterators iterate through each of their parent directories
-  llvm::sys::path::const_iterator FileI = llvm::sys::path::begin(Destination);
-  llvm::sys::path::const_iterator FileE = llvm::sys::path::end(Destination);
-  llvm::sys::path::const_iterator DirI = llvm::sys::path::begin(Origin);
-  llvm::sys::path::const_iterator DirE = llvm::sys::path::end(Origin);
-  // Advance both iterators until the paths 
diff er. Example:
-  //Destination = A/B/C/D
-  //Origin  = A/B/E/F
-  // FileI will point to C and DirI to E. The directories behind them is the
-  // directory they share (A/B).
-  while (FileI != FileE && DirI != DirE && *FileI == *DirI) {
-++FileI;
-++DirI;
-  }
-  SmallString<128> Result; // This will hold the resulting path.
-  // Result has to go up one directory for each of the remaining directories in
-  // Origin
-  while (DirI != DirE) {
-llvm::sys::path::append(Result, "..");
-++DirI;
-  }
-  // Result has to append each of the remaining directories in Destination
-  while (FileI != FileE) {
-llvm::sys::path::append(Result, *FileI);
-++FileI;
-  }
-  return Result;
-}
-
 // HTML generation
 
 static std::vector>
@@ -1138,23 +1098,6 @@ static llvm::Error genIndex(const ClangDocContext 
&CDCtx) {
   return llvm::Error::success();
 }
 
-static llvm::Error copyFile(StringRef FilePath, StringRef OutDirectory) {
-  llvm::SmallString<128> PathWrite;
-  llvm::sys::path::native(OutDirectory, PathWrite);
-  llvm::sys::path::append(PathWrite, llvm::sys::path::filename(FilePath));
-  llvm::SmallString<128> PathRead;
-  llvm::sys::path::native(FilePath, PathRead);
-  std::error_code OK;
-  std::error_code FileErr = llvm::sys::fs::copy_file(PathRead, PathWrite);
-  if (FileErr != OK) {
-return llvm::createStringError(llvm::inconvertibleErrorCode(),
-   "error creating file " +
-   llvm::sys::path::filename(FilePath) +
-   ": " + FileErr.message() + "\n");
-  }
-  return llvm::Error::success();
-}
-
 llvm::Error HTMLGenerator::createResources(ClangDocContext &CDCtx) {
   auto Err = serializeIndex(CDCtx);
   if (Err)

diff  --git a/clang-tools-extra/clang-doc/support/CMakeLists.txt 
b/clang-tools-extra/clang-doc/support/CMakeLists.txt
new file mode 100644
index 0..a4f7993d5c9d8
--- /dev/null
+++ b/clang-tools-extra/clang-doc/support/CM

[clang] [clang-format] Keep the space between `not` and a unary operator (PR #135035)

2025-04-09 Thread via cfe-commits

llvmbot wrote:

/pull-request llvm/llvm-project#135118

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


[clang] [clang-tools-extra] [clang] Improved canonicalization for template specialization types (PR #135119)

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

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/135119

This changes the TemplateArgument representation to hold a flag indicating 
whether a template argument of expression type is supposed to be canonical or 
not.

This gets one step closer to solving 
https://github.com/llvm/llvm-project/issues/92292

This still doesn't try to unique as-written TSTs. While this would increase the 
amount of memory savings and make code dealing with the AST more well-behaved, 
profiling template argument lists is still too expensive for this to be 
worthwhile, at least for now. Without this uniquing, this patch stands neutral 
in terms of performance impact.

This also fixes the context creation of TSTs, so that they don't in some cases 
get incorrectly flagged as sugar over their own canonical form. This is 
captured in the test expectation change of some AST dumps.

This fixes some places which were unnecessarily canonicalizing these TSTs.

>From 27b84546c3ad8a6de319abf2391308064947768e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 17 Sep 2022 18:07:28 +0200
Subject: [PATCH] [clang] Improved canonicalization for template specialization
 types

This changes the TemplateArgument representation to hold a flag indicating
whether a tempalte argument of expression type is supposed to be canonical
or not.

This gets one step closer to solving 
https://github.com/llvm/llvm-project/issues/92292

This still doesn't try to unique as-written TSTs. While this would
increase the amount of memory savings and make code dealing with
the AST more well-behaved, profiling template argument lists is
still too expensive for this to be worthwhile, at least for now.

This also fixes the context creation of TSTs, so that they don't
in some cases get incorrectly flagged as sugar over their own canonical
form. This is captured in the test expectation change of some AST dumps.

This fixes some places which were unnecessarily canonicalizing these TSTs.
---
 clang-tools-extra/clangd/AST.cpp  |   3 +-
 clang/docs/ReleaseNotes.rst   |   2 +
 clang/include/clang/AST/ASTContext.h  |  46 ++--
 clang/include/clang/AST/PropertiesBase.td |   5 +-
 clang/include/clang/AST/TemplateBase.h|  13 +-
 clang/include/clang/AST/Type.h|   7 +-
 clang/include/clang/AST/TypeProperties.td |  30 +--
 .../clang/Serialization/ASTRecordReader.h |   4 +
 clang/lib/AST/ASTContext.cpp  | 236 ++
 clang/lib/AST/ASTDiagnostic.cpp   |   8 +-
 clang/lib/AST/ASTImporter.cpp |  34 ++-
 clang/lib/AST/DeclTemplate.cpp|   7 +-
 clang/lib/AST/QualTypeNames.cpp   |   3 +-
 clang/lib/AST/TemplateBase.cpp|  19 +-
 clang/lib/AST/Type.cpp|  50 ++--
 clang/lib/Sema/SemaCXXScopeSpec.cpp   |  18 +-
 clang/lib/Sema/SemaExpr.cpp   |  20 +-
 clang/lib/Sema/SemaLookup.cpp |   3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 162 ++--
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  45 ++--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  11 +-
 clang/lib/Sema/SemaTemplateVariadic.cpp   |   3 +-
 clang/lib/Sema/TreeTransform.h|  13 +-
 .../class.derived.general/p2.cpp  |   2 +-
 .../temp/temp.decls/temp.class.spec/p6.cpp|   4 +-
 .../undefined-partial-specialization.cpp  |   2 +-
 clang/test/SemaTemplate/make_integer_seq.cpp  |  61 ++---
 clang/test/SemaTemplate/type_pack_element.cpp |  57 ++---
 clang/unittests/AST/TypePrinterTest.cpp   |   6 +-
 29 files changed, 452 insertions(+), 422 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 66b587f00ff4a..3b991e5e9013f 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -439,7 +439,8 @@ QualType declaredType(const TypeDecl *D) {
   if (const auto *CTSD = llvm::dyn_cast(D))
 if (const auto *Args = CTSD->getTemplateArgsAsWritten())
   return Context.getTemplateSpecializationType(
-  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments());
+  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments(),
+  /*CanonicalArgs=*/std::nullopt);
   return Context.getTypeDeclType(D);
 }
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..204d41476232c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -280,6 +280,8 @@ Improvements to Clang's diagnostics
 - Clang now better preserves the sugared types of pointers to member.
 - Clang now better preserves the presence of the template keyword with 
dependent
   prefixes.
+- Clang now in more cases avoids printing 'type-parameter-X-X' instead of the 
name of
+  the template parameter.
 - Clang now respects the current language mode when printing expressions in
   diagnostics. This fixes 

[clang] [CIR] Upstream binary assignments and comma (PR #135115)

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


@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -fclangir 
-emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s -check-prefix=OGCG
+
+void comma(void) {
+bool b;
+char c;
+float f;
+int i;
+
+b = true, c = 65, f = 3.14f, i = 42;

erichkeane wrote:

If this ends up being the comma operator (i Think it is?) we probably want to 
do some tests like: 
`b = 5.5, false`

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


[clang] [clang-tools-extra] [clang] Improved canonicalization for template specialization types (PR #135119)

2025-04-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clangd

Author: Matheus Izvekov (mizvekov)


Changes

This changes the TemplateArgument representation to hold a flag indicating 
whether a template argument of expression type is supposed to be canonical or 
not.

This gets one step closer to solving 
https://github.com/llvm/llvm-project/issues/92292

This still doesn't try to unique as-written TSTs. While this would increase the 
amount of memory savings and make code dealing with the AST more well-behaved, 
profiling template argument lists is still too expensive for this to be 
worthwhile, at least for now. Without this uniquing, this patch stands neutral 
in terms of performance impact.

This also fixes the context creation of TSTs, so that they don't in some cases 
get incorrectly flagged as sugar over their own canonical form. This is 
captured in the test expectation change of some AST dumps.

This fixes some places which were unnecessarily canonicalizing these TSTs.

---

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


29 Files Affected:

- (modified) clang-tools-extra/clangd/AST.cpp (+2-1) 
- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/AST/ASTContext.h (+31-15) 
- (modified) clang/include/clang/AST/PropertiesBase.td (+4-1) 
- (modified) clang/include/clang/AST/TemplateBase.h (+11-2) 
- (modified) clang/include/clang/AST/Type.h (+3-4) 
- (modified) clang/include/clang/AST/TypeProperties.td (+5-25) 
- (modified) clang/include/clang/Serialization/ASTRecordReader.h (+4) 
- (modified) clang/lib/AST/ASTContext.cpp (+129-107) 
- (modified) clang/lib/AST/ASTDiagnostic.cpp (+4-4) 
- (modified) clang/lib/AST/ASTImporter.cpp (+21-13) 
- (modified) clang/lib/AST/DeclTemplate.cpp (+5-2) 
- (modified) clang/lib/AST/QualTypeNames.cpp (+2-1) 
- (modified) clang/lib/AST/TemplateBase.cpp (+15-4) 
- (modified) clang/lib/AST/Type.cpp (+27-23) 
- (modified) clang/lib/Sema/SemaCXXScopeSpec.cpp (+8-10) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+17-3) 
- (modified) clang/lib/Sema/SemaLookup.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+78-84) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+27-18) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+6-5) 
- (modified) clang/lib/Sema/SemaTemplateVariadic.cpp (+2-1) 
- (modified) clang/lib/Sema/TreeTransform.h (+9-4) 
- (modified) clang/test/CXX/class.derived/class.derived.general/p2.cpp (+1-1) 
- (modified) clang/test/CXX/temp/temp.decls/temp.class.spec/p6.cpp (+2-2) 
- (modified) clang/test/SemaCXX/undefined-partial-specialization.cpp (+1-1) 
- (modified) clang/test/SemaTemplate/make_integer_seq.cpp (+16-45) 
- (modified) clang/test/SemaTemplate/type_pack_element.cpp (+15-42) 
- (modified) clang/unittests/AST/TypePrinterTest.cpp (+3-3) 


``diff
diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 66b587f00ff4a..3b991e5e9013f 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -439,7 +439,8 @@ QualType declaredType(const TypeDecl *D) {
   if (const auto *CTSD = llvm::dyn_cast(D))
 if (const auto *Args = CTSD->getTemplateArgsAsWritten())
   return Context.getTemplateSpecializationType(
-  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments());
+  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments(),
+  /*CanonicalArgs=*/std::nullopt);
   return Context.getTypeDeclType(D);
 }
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..204d41476232c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -280,6 +280,8 @@ Improvements to Clang's diagnostics
 - Clang now better preserves the sugared types of pointers to member.
 - Clang now better preserves the presence of the template keyword with 
dependent
   prefixes.
+- Clang now in more cases avoids printing 'type-parameter-X-X' instead of the 
name of
+  the template parameter.
 - Clang now respects the current language mode when printing expressions in
   diagnostics. This fixes a bunch of `bool` being printed as `_Bool`, and also
   a bunch of HLSL types being printed as their C++ equivalents.
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3ff9f308f3a5e..c339bb698e099 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -364,9 +364,6 @@ class ASTContext : public RefCountedBase {
  const ASTContext&>
 CanonTemplateTemplateParms;
 
-  TemplateTemplateParmDecl *
-getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
-
   /// The typedef for the __int128_t type.
   mutable TypedefDecl *Int128Decl = nullptr;
 
@@ -1808,22 +1805,26 @@ class ASTContext : public RefCountedBase {
   bool ParameterPack,

[clang] [clang-tools-extra] [clang] Improved canonicalization for template specialization types (PR #135119)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Matheus Izvekov (mizvekov)


Changes

This changes the TemplateArgument representation to hold a flag indicating 
whether a template argument of expression type is supposed to be canonical or 
not.

This gets one step closer to solving 
https://github.com/llvm/llvm-project/issues/92292

This still doesn't try to unique as-written TSTs. While this would increase the 
amount of memory savings and make code dealing with the AST more well-behaved, 
profiling template argument lists is still too expensive for this to be 
worthwhile, at least for now. Without this uniquing, this patch stands neutral 
in terms of performance impact.

This also fixes the context creation of TSTs, so that they don't in some cases 
get incorrectly flagged as sugar over their own canonical form. This is 
captured in the test expectation change of some AST dumps.

This fixes some places which were unnecessarily canonicalizing these TSTs.

---

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


29 Files Affected:

- (modified) clang-tools-extra/clangd/AST.cpp (+2-1) 
- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/AST/ASTContext.h (+31-15) 
- (modified) clang/include/clang/AST/PropertiesBase.td (+4-1) 
- (modified) clang/include/clang/AST/TemplateBase.h (+11-2) 
- (modified) clang/include/clang/AST/Type.h (+3-4) 
- (modified) clang/include/clang/AST/TypeProperties.td (+5-25) 
- (modified) clang/include/clang/Serialization/ASTRecordReader.h (+4) 
- (modified) clang/lib/AST/ASTContext.cpp (+129-107) 
- (modified) clang/lib/AST/ASTDiagnostic.cpp (+4-4) 
- (modified) clang/lib/AST/ASTImporter.cpp (+21-13) 
- (modified) clang/lib/AST/DeclTemplate.cpp (+5-2) 
- (modified) clang/lib/AST/QualTypeNames.cpp (+2-1) 
- (modified) clang/lib/AST/TemplateBase.cpp (+15-4) 
- (modified) clang/lib/AST/Type.cpp (+27-23) 
- (modified) clang/lib/Sema/SemaCXXScopeSpec.cpp (+8-10) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+17-3) 
- (modified) clang/lib/Sema/SemaLookup.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+78-84) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+27-18) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+6-5) 
- (modified) clang/lib/Sema/SemaTemplateVariadic.cpp (+2-1) 
- (modified) clang/lib/Sema/TreeTransform.h (+9-4) 
- (modified) clang/test/CXX/class.derived/class.derived.general/p2.cpp (+1-1) 
- (modified) clang/test/CXX/temp/temp.decls/temp.class.spec/p6.cpp (+2-2) 
- (modified) clang/test/SemaCXX/undefined-partial-specialization.cpp (+1-1) 
- (modified) clang/test/SemaTemplate/make_integer_seq.cpp (+16-45) 
- (modified) clang/test/SemaTemplate/type_pack_element.cpp (+15-42) 
- (modified) clang/unittests/AST/TypePrinterTest.cpp (+3-3) 


``diff
diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 66b587f00ff4a..3b991e5e9013f 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -439,7 +439,8 @@ QualType declaredType(const TypeDecl *D) {
   if (const auto *CTSD = llvm::dyn_cast(D))
 if (const auto *Args = CTSD->getTemplateArgsAsWritten())
   return Context.getTemplateSpecializationType(
-  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments());
+  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments(),
+  /*CanonicalArgs=*/std::nullopt);
   return Context.getTypeDeclType(D);
 }
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..204d41476232c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -280,6 +280,8 @@ Improvements to Clang's diagnostics
 - Clang now better preserves the sugared types of pointers to member.
 - Clang now better preserves the presence of the template keyword with 
dependent
   prefixes.
+- Clang now in more cases avoids printing 'type-parameter-X-X' instead of the 
name of
+  the template parameter.
 - Clang now respects the current language mode when printing expressions in
   diagnostics. This fixes a bunch of `bool` being printed as `_Bool`, and also
   a bunch of HLSL types being printed as their C++ equivalents.
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3ff9f308f3a5e..c339bb698e099 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -364,9 +364,6 @@ class ASTContext : public RefCountedBase {
  const ASTContext&>
 CanonTemplateTemplateParms;
 
-  TemplateTemplateParmDecl *
-getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
-
   /// The typedef for the __int128_t type.
   mutable TypedefDecl *Int128Decl = nullptr;
 
@@ -1808,22 +1805,26 @@ class ASTContext : public RefCountedBase {
   bool ParameterPack,
   T

[clang] [CIR] Upstream binary assignments and comma (PR #135115)

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

https://github.com/erichkeane commented:

A little more testing on comma would be nice, else seems reasonable.

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


[clang] 98feb05 - [clang] fix unresolved dependent template specialization mangling (#135111)

2025-04-09 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2025-04-09T23:23:52-03:00
New Revision: 98feb05825a179c56f965d936b948a95d2a6b888

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

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

This fixes a regression introduced in
https://github.com/llvm/llvm-project/pull/133610 which was reported here
https://github.com/llvm/llvm-project/pull/133610#issuecomment-2787332042

When mangling a dependent template specialization appearing within an
unresolved prefix, translate the dtst back to a dependent template name
including the prefix, and mangle following the nested unresolved-type
production.

There are no release notes, since this regression was never released.

Added: 


Modified: 
clang/lib/AST/ItaniumMangle.cpp
clang/test/CodeGenCXX/mangle-template.cpp

Removed: 




diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index eb25b19bbdc74..8790a5282a96b 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -1404,9 +1404,19 @@ void 
CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
 //   - a template type parameter
 //   - a template template parameter with arguments
 // In all of these cases, we should have no prefix.
-if (qualifier->getPrefix()) {
-  mangleUnresolvedPrefix(qualifier->getPrefix(),
- /*recursive*/ true);
+if (NestedNameSpecifier *Prefix = qualifier->getPrefix()) {
+  if (const auto *DTST =
+  dyn_cast(type)) {
+Out << "srN";
+TemplateName Template = getASTContext().getDependentTemplateName(
+{Prefix, DTST->getDependentTemplateName().getName(),
+ /*HasTemplateKeyword=*/true});
+mangleTemplatePrefix(Template);
+mangleTemplateArgs(Template, DTST->template_arguments());
+break;
+  }
+  mangleUnresolvedPrefix(Prefix,
+ /*recursive=*/true);
 } else {
   // Otherwise, all the cases want this.
   Out << "sr";

diff  --git a/clang/test/CodeGenCXX/mangle-template.cpp 
b/clang/test/CodeGenCXX/mangle-template.cpp
index a4cb22739ac2a..365aba5989baa 100644
--- a/clang/test/CodeGenCXX/mangle-template.cpp
+++ b/clang/test/CodeGenCXX/mangle-template.cpp
@@ -70,7 +70,7 @@ namespace test7 {
 static const unsigned value = sizeof(T);
   };
 
-  template struct int_c { 
+  template struct int_c {
 typedef float type;
   };
 
@@ -92,7 +92,7 @@ namespace test8 {
 };
   };
 
-  template struct int_c { 
+  template struct int_c {
 typedef float type;
   };
 
@@ -399,3 +399,20 @@ namespace type_qualifier {
   // CHECK: @_ZN14type_qualifier1gIPiEEvDTcmcvv_ELi1EE
   template void g(int);
 }
+
+namespace unresolved_template_specialization_type {
+  template  struct enable_if {};
+  struct Foo {
+static const int value = true;
+  };
+  struct HashStateBase {
+template  using is_hashable = Foo;
+  };
+  template  struct raw_hash_set {
+template 
+static enable_if::value>
+AbslHashValue() {}
+  };
+  template enable_if raw_hash_set::AbslHashValue();
+  // CHECH: 
@_ZN39unresolved_template_specialization_type12raw_hash_setIiE13AbslHashValueINS_13HashStateBaseEEENS_9enable_ifIXsrNT_11is_hashableIiEE5valueEEEv
+} // namespace unresolved_template_specialization_type



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


[clang] [clang-tools-extra] [clang] Improved canonicalization for template specialization types (PR #135119)

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

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/135119

>From 03801aef9b4f950940d33276095c14047da0a3e6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 17 Sep 2022 18:07:28 +0200
Subject: [PATCH] [clang] Improved canonicalization for template specialization
 types

This changes the TemplateArgument representation to hold a flag indicating
whether a tempalte argument of expression type is supposed to be canonical
or not.

This gets one step closer to solving 
https://github.com/llvm/llvm-project/issues/92292

This still doesn't try to unique as-written TSTs. While this would
increase the amount of memory savings and make code dealing with
the AST more well-behaved, profiling template argument lists is
still too expensive for this to be worthwhile, at least for now.

This also fixes the context creation of TSTs, so that they don't
in some cases get incorrectly flagged as sugar over their own canonical
form. This is captured in the test expectation change of some AST dumps.

This fixes some places which were unnecessarily canonicalizing these TSTs.
---
 clang-tools-extra/clangd/AST.cpp  |   3 +-
 clang/docs/ReleaseNotes.rst   |   2 +
 clang/include/clang/AST/ASTContext.h  |  46 ++--
 clang/include/clang/AST/PropertiesBase.td |   5 +-
 clang/include/clang/AST/TemplateBase.h|  13 +-
 clang/include/clang/AST/Type.h|   7 +-
 clang/include/clang/AST/TypeProperties.td |  30 +--
 clang/lib/AST/ASTContext.cpp  | 236 ++
 clang/lib/AST/ASTDiagnostic.cpp   |   8 +-
 clang/lib/AST/ASTImporter.cpp |  34 ++-
 clang/lib/AST/DeclTemplate.cpp|   7 +-
 clang/lib/AST/QualTypeNames.cpp   |   3 +-
 clang/lib/AST/TemplateBase.cpp|  19 +-
 clang/lib/AST/Type.cpp|  50 ++--
 clang/lib/Sema/SemaCXXScopeSpec.cpp   |  18 +-
 clang/lib/Sema/SemaExpr.cpp   |  20 +-
 clang/lib/Sema/SemaLookup.cpp |   3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 162 ++--
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  45 ++--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  11 +-
 clang/lib/Sema/SemaTemplateVariadic.cpp   |   3 +-
 clang/lib/Sema/TreeTransform.h|  13 +-
 .../class.derived.general/p2.cpp  |   2 +-
 .../temp/temp.decls/temp.class.spec/p6.cpp|   4 +-
 .../undefined-partial-specialization.cpp  |   2 +-
 clang/test/SemaTemplate/make_integer_seq.cpp  |  61 ++---
 clang/test/SemaTemplate/type_pack_element.cpp |  57 ++---
 clang/unittests/AST/TypePrinterTest.cpp   |   6 +-
 28 files changed, 448 insertions(+), 422 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 66b587f00ff4a..3b991e5e9013f 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -439,7 +439,8 @@ QualType declaredType(const TypeDecl *D) {
   if (const auto *CTSD = llvm::dyn_cast(D))
 if (const auto *Args = CTSD->getTemplateArgsAsWritten())
   return Context.getTemplateSpecializationType(
-  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments());
+  TemplateName(CTSD->getSpecializedTemplate()), Args->arguments(),
+  /*CanonicalArgs=*/std::nullopt);
   return Context.getTypeDeclType(D);
 }
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..204d41476232c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -280,6 +280,8 @@ Improvements to Clang's diagnostics
 - Clang now better preserves the sugared types of pointers to member.
 - Clang now better preserves the presence of the template keyword with 
dependent
   prefixes.
+- Clang now in more cases avoids printing 'type-parameter-X-X' instead of the 
name of
+  the template parameter.
 - Clang now respects the current language mode when printing expressions in
   diagnostics. This fixes a bunch of `bool` being printed as `_Bool`, and also
   a bunch of HLSL types being printed as their C++ equivalents.
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3ff9f308f3a5e..c339bb698e099 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -364,9 +364,6 @@ class ASTContext : public RefCountedBase {
  const ASTContext&>
 CanonTemplateTemplateParms;
 
-  TemplateTemplateParmDecl *
-getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
-
   /// The typedef for the __int128_t type.
   mutable TypedefDecl *Int128Decl = nullptr;
 
@@ -1808,22 +1805,26 @@ class ASTContext : public RefCountedBase {
   bool ParameterPack,
   TemplateTypeParmDecl *ParmDecl = nullptr) const;
 
-  QualType getTemplateSpecializationType(TemplateName

[clang] [clang] consistently quote expressions in diagnostics (PR #134769)

2025-04-09 Thread Younan Zhang via cfe-commits

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

Thanks

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


[clang] [llvm] [IR] Mark convergence intrins as has-side-effect (PR #134844)

2025-04-09 Thread Sameer Sahasrabuddhe via cfe-commits

ssahasra wrote:

To take this to its logical conclusion, when convergence tokens are in use, the 
`convergent` attribute is redundant. All we need is a `noconvergent` attribute 
for function declarations. A function definition is convergent iff the body 
contains a call to the `entry` intrinsic, and a function declaration is assumed 
to be convergent unless it has a `noconvergent` attribute on it. So the 
immediate impact on the specification is that everywhere including the 
verifier, it is always okay to ignore the `convergent` attribute on a function 
definition if convergence tokens are in use.

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


[clang] [HLSL] Add support for modulo of floating point scalar and vectors (PR #135125)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Farzon Lotfi (farzonl)


Changes

fixes #135122

SemaExpr.cpp - Make all doubles fail. Add sema support for float scalars and 
vectors when language mode is HLSL.
CGExprScalar.cpp - Allow emit frem when language mode is HLSL.

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+2) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+25-3) 
- (added) clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl (+110) 
- (added) clang/test/SemaHLSL/Operators/frem_modulo-errors.hlsl (+41) 


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 28ae56058a7b4..3b25c79701b60 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -3964,6 +3964,8 @@ Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
 
   if (Ops.Ty->hasUnsignedIntegerRepresentation())
 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
+  else if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
+return Builder.CreateFRem(Ops.LHS, Ops.RHS, "rem");
   else
 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
 }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e7f418ae6802e..25b7bd0e16942 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10695,10 +10695,30 @@ QualType Sema::CheckRemainderOperands(
   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
 
+  // Note: This check is here to simplify the double exclusions of
+  // scalar and vector HLSL checks. No getLangOpts().HLSL
+  // is needed since all languages exlcude doubles.
+  if (LHS.get()->getType()->isDoubleType() ||
+  RHS.get()->getType()->isDoubleType() ||
+  (LHS.get()->getType()->isVectorType() && LHS.get()
+   ->getType()
+   ->getAs()
+   ->getElementType()
+   ->isDoubleType()) ||
+  (RHS.get()->getType()->isVectorType() && RHS.get()
+   ->getType()
+   ->getAs()
+   ->getElementType()
+   ->isDoubleType()))
+return InvalidOperands(Loc, LHS, RHS);
+
   if (LHS.get()->getType()->isVectorType() ||
   RHS.get()->getType()->isVectorType()) {
-if (LHS.get()->getType()->hasIntegerRepresentation() &&
-RHS.get()->getType()->hasIntegerRepresentation())
+if ((LHS.get()->getType()->hasIntegerRepresentation() &&
+ RHS.get()->getType()->hasIntegerRepresentation()) ||
+(getLangOpts().HLSL &&
+ (LHS.get()->getType()->hasFloatingRepresentation() ||
+  RHS.get()->getType()->hasFloatingRepresentation(
   return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  /*AllowBothBool*/ getLangOpts().AltiVec,
  /*AllowBoolConversions*/ false,
@@ -10722,7 +10742,9 @@ QualType Sema::CheckRemainderOperands(
   if (LHS.isInvalid() || RHS.isInvalid())
 return QualType();
 
-  if (compType.isNull() || !compType->isIntegerType())
+  if (compType.isNull() ||
+  (!compType->isIntegerType() &&
+   !(getLangOpts().HLSL && compType->isFloatingType(
 return InvalidOperands(Loc, LHS, RHS);
   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
   return compType;
diff --git a/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl 
b/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl
new file mode 100644
index 0..edc28c5c80b51
--- /dev/null
+++ b/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl
@@ -0,0 +1,110 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library %s \
+// RUN:  -fnative-half-type -emit-llvm -disable-llvm-passes -o - | \
+// RUN:  FileCheck %s
+// RUN: %clang_cc1 -finclude-default-header -triple 
spirv-unknown-vulkan-compute %s \
+// RUN:  -fnative-half-type -emit-llvm -disable-llvm-passes -o - | \
+// RUN:  FileCheck %s
+
+ half2 half_vec_mod_by_int(half2 p1) {
+// CHECK-LABEL: half_vec_mod_by_int
+// CHECK: %rem = frem reassoc nnan ninf nsz arcp afn <2 x half> %{{.*}}, splat 
(half 0xH4000)
+return  p1 % 2;
+}
+
+ half2 half_vec_mod_by_float(half2 p1) {
+// CHECK-LABEL: half_vec_mod_by_float
+// CHECK: %rem = frem reassoc nnan ninf nsz arcp afn <2 x half> %{{.*}}, splat 
(half 0xH4000)
+return  p1 % (half)2.0;
+}
+
+ half2 half_vec_mod_by_half(half2 p1, half p2 ) {
+// CHECK-LABEL: half_vec_mod_by_half
+// CHECK:  %splat.splatinsert = insertelement <2 x half> poison, half %{{.*}}, 
i64 0

[clang] [HLSL] Add support for modulo of floating point scalar and vectors (PR #135125)

2025-04-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-hlsl

@llvm/pr-subscribers-clang

Author: Farzon Lotfi (farzonl)


Changes

fixes #135122

SemaExpr.cpp - Make all doubles fail. Add sema support for float scalars and 
vectors when language mode is HLSL.
CGExprScalar.cpp - Allow emit frem when language mode is HLSL.

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+2) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+25-3) 
- (added) clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl (+110) 
- (added) clang/test/SemaHLSL/Operators/frem_modulo-errors.hlsl (+41) 


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 28ae56058a7b4..3b25c79701b60 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -3964,6 +3964,8 @@ Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
 
   if (Ops.Ty->hasUnsignedIntegerRepresentation())
 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
+  else if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
+return Builder.CreateFRem(Ops.LHS, Ops.RHS, "rem");
   else
 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
 }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index e7f418ae6802e..25b7bd0e16942 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10695,10 +10695,30 @@ QualType Sema::CheckRemainderOperands(
   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
 
+  // Note: This check is here to simplify the double exclusions of
+  // scalar and vector HLSL checks. No getLangOpts().HLSL
+  // is needed since all languages exlcude doubles.
+  if (LHS.get()->getType()->isDoubleType() ||
+  RHS.get()->getType()->isDoubleType() ||
+  (LHS.get()->getType()->isVectorType() && LHS.get()
+   ->getType()
+   ->getAs()
+   ->getElementType()
+   ->isDoubleType()) ||
+  (RHS.get()->getType()->isVectorType() && RHS.get()
+   ->getType()
+   ->getAs()
+   ->getElementType()
+   ->isDoubleType()))
+return InvalidOperands(Loc, LHS, RHS);
+
   if (LHS.get()->getType()->isVectorType() ||
   RHS.get()->getType()->isVectorType()) {
-if (LHS.get()->getType()->hasIntegerRepresentation() &&
-RHS.get()->getType()->hasIntegerRepresentation())
+if ((LHS.get()->getType()->hasIntegerRepresentation() &&
+ RHS.get()->getType()->hasIntegerRepresentation()) ||
+(getLangOpts().HLSL &&
+ (LHS.get()->getType()->hasFloatingRepresentation() ||
+  RHS.get()->getType()->hasFloatingRepresentation(
   return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  /*AllowBothBool*/ getLangOpts().AltiVec,
  /*AllowBoolConversions*/ false,
@@ -10722,7 +10742,9 @@ QualType Sema::CheckRemainderOperands(
   if (LHS.isInvalid() || RHS.isInvalid())
 return QualType();
 
-  if (compType.isNull() || !compType->isIntegerType())
+  if (compType.isNull() ||
+  (!compType->isIntegerType() &&
+   !(getLangOpts().HLSL && compType->isFloatingType(
 return InvalidOperands(Loc, LHS, RHS);
   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
   return compType;
diff --git a/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl 
b/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl
new file mode 100644
index 0..edc28c5c80b51
--- /dev/null
+++ b/clang/test/CodeGenHLSL/BasicFeatures/frem_modulo.hlsl
@@ -0,0 +1,110 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library %s \
+// RUN:  -fnative-half-type -emit-llvm -disable-llvm-passes -o - | \
+// RUN:  FileCheck %s
+// RUN: %clang_cc1 -finclude-default-header -triple 
spirv-unknown-vulkan-compute %s \
+// RUN:  -fnative-half-type -emit-llvm -disable-llvm-passes -o - | \
+// RUN:  FileCheck %s
+
+ half2 half_vec_mod_by_int(half2 p1) {
+// CHECK-LABEL: half_vec_mod_by_int
+// CHECK: %rem = frem reassoc nnan ninf nsz arcp afn <2 x half> %{{.*}}, splat 
(half 0xH4000)
+return  p1 % 2;
+}
+
+ half2 half_vec_mod_by_float(half2 p1) {
+// CHECK-LABEL: half_vec_mod_by_float
+// CHECK: %rem = frem reassoc nnan ninf nsz arcp afn <2 x half> %{{.*}}, splat 
(half 0xH4000)
+return  p1 % (half)2.0;
+}
+
+ half2 half_vec_mod_by_half(half2 p1, half p2 ) {
+// CHECK-LABEL: half_vec_mod_by_half
+// CHECK:  %splat.splatinsert = insertelement <2 x half> poison, hal

[clang] 98ea512 - [clang][bytecode] Clear inactive union fields when copying (#134982)

2025-04-09 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-04-10T06:12:00+02:00
New Revision: 98ea512f720ec954a6f096dbb39534f06affa196

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

LOG: [clang][bytecode] Clear inactive union fields when copying (#134982)

When copying unions, we need to only copy the active field of the source
union, which we were already doing. However, we also need to zero out
the (now) inactive fields, so we don't end up with dangling pointers in
those inactive fields.

Added: 
clang/test/AST/ByteCode/libcxx/minmax.cpp

Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 3029314ddbad8..bde416d98edd3 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2723,6 +2723,45 @@ bool SetThreeWayComparisonField(InterpState &S, CodePtr 
OpPC,
   return true;
 }
 
+static void zeroAll(Pointer &Dest) {
+  const Descriptor *Desc = Dest.getFieldDesc();
+
+  if (Desc->isPrimitive()) {
+TYPE_SWITCH(Desc->getPrimType(), {
+  Dest.deref().~T();
+  new (&Dest.deref()) T();
+});
+return;
+  }
+
+  if (Desc->isRecord()) {
+const Record *R = Desc->ElemRecord;
+for (const Record::Field &F : R->fields()) {
+  Pointer FieldPtr = Dest.atField(F.Offset);
+  zeroAll(FieldPtr);
+}
+return;
+  }
+
+  if (Desc->isPrimitiveArray()) {
+for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
+  TYPE_SWITCH(Desc->getPrimType(), {
+Dest.deref().~T();
+new (&Dest.deref()) T();
+  });
+}
+return;
+  }
+
+  if (Desc->isCompositeArray()) {
+for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
+  Pointer ElemPtr = Dest.atIndex(I).narrow();
+  zeroAll(ElemPtr);
+}
+return;
+  }
+}
+
 static bool copyComposite(InterpState &S, CodePtr OpPC, const Pointer &Src,
   Pointer &Dest, bool Activate);
 static bool copyRecord(InterpState &S, CodePtr OpPC, const Pointer &Src,
@@ -2751,11 +2790,14 @@ static bool copyRecord(InterpState &S, CodePtr OpPC, 
const Pointer &Src,
   const Record *R = DestDesc->ElemRecord;
   for (const Record::Field &F : R->fields()) {
 if (R->isUnion()) {
-  // For unions, only copy the active field.
+  // For unions, only copy the active field. Zero all others.
   const Pointer &SrcField = Src.atField(F.Offset);
   if (SrcField.isActive()) {
 if (!copyField(F, /*Activate=*/true))
   return false;
+  } else {
+Pointer DestField = Dest.atField(F.Offset);
+zeroAll(DestField);
   }
 } else {
   if (!copyField(F, Activate))

diff  --git a/clang/test/AST/ByteCode/libcxx/minmax.cpp 
b/clang/test/AST/ByteCode/libcxx/minmax.cpp
new file mode 100644
index 0..0bb2a68b8cfd1
--- /dev/null
+++ b/clang/test/AST/ByteCode/libcxx/minmax.cpp
@@ -0,0 +1,527 @@
+// RUN: %clang_cc1 -std=c++2c -fexperimental-new-constant-interpreter 
-verify=expected,both %s
+// RUN: %clang_cc1 -std=c++2c  -verify=ref,both %s
+
+/// This used to cause an assertion failure because we were deallocating a
+/// dynamic block that was already dead.
+
+namespace std {
+inline namespace __1 {
+template  struct integral_constant {
+  static inline constexpr const _Tp value = __v;
+};
+typedef integral_constant true_type;
+typedef integral_constant false_type;
+template  using _BoolConstant = integral_constant;
+template  using __remove_cv_t = __remove_cv(_Tp);
+template  using remove_cv_t = __remove_cv_t<_Tp>;
+template 
+inline constexpr bool is_lvalue_reference_v = __is_lvalue_reference(_Tp);
+template 
+using __libcpp_remove_reference_t = __remove_reference_t(_Tp);
+template 
+constexpr _Tp &&forward(__libcpp_remove_reference_t<_Tp> &__t) noexcept;
+template  struct conditional {
+  using type = _If;
+};
+template 
+using conditional_t = typename conditional<_Bp, _IfRes, _ElseRes>::type;
+template 
+using _IsSame = _BoolConstant<__is_same(_Tp, _Up)>;
+using size_t = decltype(sizeof(int));
+template  using __decay_t = __decay(_Tp);
+template  using decay_t = __decay_t<_Tp>;
+template  struct enable_if;
+template  struct enable_if {
+  typedef _Tp type;
+};
+template 
+using __enable_if_t = typename enable_if<_Bp, _Tp>::type;
+template 
+inline constexpr bool is_base_of_v = __is_base_of(_Bp, _Dp);
+template  _Tp &&__declval(int);
+template  decltype(std::__declval<_Tp>(0)) declval() noexcept;
+template  struct __invokable_r {};
+template 
+using __is_invocable = __invokable_r;
+template 
+inline const bool __is_invocable_v = __is_invocable<_Func, _Args...>::value;
+template 
+struct __invoke_result
+: enable_if<__is_invocable_v<_Func, _Args...>,
+typena

[clang] [clang][bytecode] Clear inactive union fields when copying (PR #134982)

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

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


[clang] [Clang][CodeGen] Do not set inbounds flag in `EmitMemberDataPointerAddress` when the base pointer is null (PR #130952)

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

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

>From 0f6ff605da3cbadc5311d4bf6c08fe98970a69c3 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Thu, 10 Apr 2025 09:54:33 +0800
Subject: [PATCH 1/5] [Clang][CodeGen] Do not set inbounds flag for struct GEP
 with null base pointers

---
 clang/docs/ReleaseNotes.rst   |  7 ++
 clang/lib/CodeGen/CGExpr.cpp  | 33 ++---
 clang/lib/CodeGen/CodeGenFunction.h   |  3 +-
 ...ptr-and-nonzero-offset-in-offsetof-idiom.c |  2 +-
 ...r-and-nonzero-offset-in-offsetof-idiom.cpp | 72 ++-
 5 files changed, 105 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..c2f7a519d270a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -42,6 +42,13 @@ Potentially Breaking Changes
 C/C++ Language Potentially Breaking Changes
 ---
 
+- New LLVM optimizations have been implemented that optimize pointer 
arithmetic on
+  null pointers more aggressively.  As part of this, clang has implemented a 
special
+  case for old-style offsetof idioms like ``((int)(&(((struct S 
*)0)->field)))``, to
+  ensure they are not caught by these optimizations.  It is also possible to 
use
+  ``-fwrapv-pointer`` or   ``-fno-delete-null-pointer-checks`` to make pointer 
arithmetic
+  on null pointers well-defined. (#GH130734, #GH130742)
+
 C++ Specific Potentially Breaking Changes
 -
 
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 451034395976f..c8ff2c880a655 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4785,6 +4785,16 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
   }
 
   Expr *BaseExpr = E->getBase();
+  bool IsInBounds = !getLangOpts().PointerOverflowDefined;
+  if (IsInBounds) {
+// Check whether the underlying base pointer is a constant null.
+// If so, we do not set inbounds flag for GEP to avoid breaking some
+// old-style offsetof idioms.
+Expr *UnderlyingBaseExpr = BaseExpr->IgnoreParens();
+while (auto *BaseMemberExpr = dyn_cast(UnderlyingBaseExpr))
+  UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
+IsInBounds = !getContext().isSentinelNullExpr(UnderlyingBaseExpr);
+  }
   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
   LValue BaseLV;
   if (E->isArrow()) {
@@ -4806,7 +4816,7 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
 
   NamedDecl *ND = E->getMemberDecl();
   if (auto *Field = dyn_cast(ND)) {
-LValue LV = EmitLValueForField(BaseLV, Field);
+LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
 setObjCGCLValueClass(getContext(), E, LV);
 if (getLangOpts().OpenMP) {
   // If the member was explicitly marked as nontemporal, mark it as
@@ -4892,12 +4902,15 @@ unsigned CodeGenFunction::getDebugInfoFIndex(const 
RecordDecl *Rec,
 /// Get the address of a zero-sized field within a record. The resulting
 /// address doesn't necessarily have the right type.
 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
-   const FieldDecl *Field) {
+   const FieldDecl *Field,
+   bool IsInBounds) {
   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
   CGF.getContext().getFieldOffset(Field));
   if (Offset.isZero())
 return Base;
   Base = Base.withElementType(CGF.Int8Ty);
+  if (!IsInBounds)
+return CGF.Builder.CreateConstByteGEP(Base, Offset);
   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
 }
 
@@ -4906,16 +4919,16 @@ static Address emitAddrOfZeroSizeField(CodeGenFunction 
&CGF, Address Base,
 ///
 /// The resulting address doesn't necessarily have the right type.
 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
-  const FieldDecl *field) {
+  const FieldDecl *field, bool IsInBounds) 
{
   if (isEmptyFieldForLayout(CGF.getContext(), field))
-return emitAddrOfZeroSizeField(CGF, base, field);
+return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
 
   const RecordDecl *rec = field->getParent();
 
   unsigned idx =
 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
 
-  if (CGF.getLangOpts().PointerOverflowDefined)
+  if (!IsInBounds)
 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
 
   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
@@ -4953,8 +4966,8 @@ static bool hasAnyVptr(const QualType Type, const 
ASTContext &Context) {
   return false;
 }
 
-LValue CodeGenFunction::EmitLValueForField(LValue base,
-   const FieldDecl *field) {
+LValue CodeGenFuncti

[clang] cuda clang: Add support for CUDA surfaces (PR #132883)

2025-04-09 Thread Artem Belevich via cfe-commits

Artem-B wrote:

@AustinSchuh One thing I've missed during review is that the test 
clang/test/CodeGen/nvptx-surface.cu should probably go into 
clang/test/CodeGenCUDA

This would also obviate the need for  #134459.

Can you send the patch to move the test to the right location?

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


[clang] [CIR] Upstream binary assignments and comma (PR #135115)

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

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

This patch adds `VisitBinAssign` and `VisitBinComma` to the ClangIR 
`ScalarExprEmitter` to enable assignments and the comma operator.

>From bcaeadf7fff01d2d92b0d234b40f8d5884974e4c Mon Sep 17 00:00:00 2001
From: Morris Hafner 
Date: Thu, 10 Apr 2025 03:53:43 +0200
Subject: [PATCH] [CIR] Upstream binary assignments and comma

This patch adds `VisitBinAssign` and `VisitBinComma` to the ClangIR 
`ScalarExprEmitter` to enable assignments and the comma operator.
---
 clang/include/clang/CIR/MissingFeatures.h  |  1 +
 clang/lib/CIR/CodeGen/CIRGenDecl.cpp   |  8 +++
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp   |  7 +++
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 60 ++
 clang/lib/CIR/CodeGen/CIRGenFunction.h |  8 +++
 clang/test/CIR/CodeGen/binassign.c | 56 
 clang/test/CIR/CodeGen/comma.c | 53 +++
 clang/test/CIR/IR/binassign.cir| 45 
 8 files changed, 238 insertions(+)
 create mode 100644 clang/test/CIR/CodeGen/binassign.c
 create mode 100644 clang/test/CIR/CodeGen/comma.c
 create mode 100644 clang/test/CIR/IR/binassign.cir

diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 3188429ea3b1b..19cd9c03635b3 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -113,6 +113,7 @@ struct MissingFeatures {
   static bool incrementProfileCounter() { return false; }
   static bool insertBuiltinUnpredictable() { return false; }
   static bool objCGC() { return false; }
+  static bool bitfields() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp 
b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
index b8e72f299acb6..58797c5dd253a 100644
--- a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
@@ -277,3 +277,11 @@ void CIRGenFunction::emitDecl(const Decl &d) {
 cgm.errorNYI(d.getSourceRange(), "emitDecl: unhandled decl type");
   }
 }
+
+void CIRGenFunction::emitNullabilityCheck(LValue lhs, mlir::Value rhs,
+  SourceLocation loc) {
+  if (!sanOpts.has(SanitizerKind::NullabilityAssign))
+return;
+
+  assert(!cir::MissingFeatures::sanitizers());
+}
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 4b6652ad0b9e6..66caea26c3636 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -219,6 +219,13 @@ void CIRGenFunction::emitStoreOfScalar(mlir::Value value, 
Address addr,
   assert(!cir::MissingFeatures::opTBAA());
 }
 
+void CIRGenFunction::emitStoreThroughBitfieldLValue(RValue src, LValue dst,
+mlir::Value &result) {
+  assert(!cir::MissingFeatures::bitfields());
+  cgm.errorNYI("bitfields");
+  result = {};
+}
+
 mlir::Value CIRGenFunction::emitToMemory(mlir::Value value, QualType ty) {
   // Bool has a different representation in memory than in registers,
   // but in ClangIR, it is simply represented as a cir.bool value.
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 4042f5dc23e4b..955082047bd38 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -21,6 +21,7 @@
 #include "mlir/IR/Value.h"
 
 #include 
+#include 
 
 using namespace clang;
 using namespace clang::CIRGen;
@@ -807,6 +808,65 @@ class ScalarExprEmitter : public 
StmtVisitor {
   VISITCOMP(EQ)
   VISITCOMP(NE)
 #undef VISITCOMP
+
+  mlir::Value VisitBinAssign(const BinaryOperator *e) {
+const bool ignore = std::exchange(ignoreResultAssign, false);
+
+mlir::Value rhs;
+LValue lhs;
+
+switch (e->getLHS()->getType().getObjCLifetime()) {
+case Qualifiers::OCL_Strong:
+case Qualifiers::OCL_Autoreleasing:
+case Qualifiers::OCL_ExplicitNone:
+case Qualifiers::OCL_Weak:
+  assert(!cir::MissingFeatures::objCLifetime());
+  break;
+case Qualifiers::OCL_None:
+  // __block variables need to have the rhs evaluated first, plus this
+  // should improve codegen just a little.
+  rhs = Visit(e->getRHS());
+  assert(!cir::MissingFeatures::sanitizers());
+  // TODO(cir): This needs to be emitCheckedLValue() once we support
+  // sanitizers
+  lhs = cgf.emitLValue(e->getLHS());
+
+  // Store the value into the LHS. Bit-fields are handled specially because
+  // the result is altered by the store, i.e., [C99 6.5.16p1]
+  // 'An assignment expression has the value of the left operand after the
+  // assignment...'.
+  if (lhs.isBitField()) {
+cgf.emitStoreThroughBitfieldLValue(RValue::get(rhs), lhs, rhs);
+  } else {
+cgf.emitNullabilityCheck(lhs, rhs, e->getExprLoc());
+ 

[clang] [Clang][CodeGen] Do not set inbounds flag for struct GEP with null base pointers (PR #130734)

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

dtcxzyw wrote:

Rebased on the top of https://github.com/llvm/llvm-project/pull/134269 and 
https://github.com/llvm/llvm-project/pull/134221

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


[clang] [Clang][CodeGen] Do not set inbounds flag for struct GEP with null base pointers (PR #130734)

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

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

>From 0f6ff605da3cbadc5311d4bf6c08fe98970a69c3 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Thu, 10 Apr 2025 09:54:33 +0800
Subject: [PATCH] [Clang][CodeGen] Do not set inbounds flag for struct GEP with
 null base pointers

---
 clang/docs/ReleaseNotes.rst   |  7 ++
 clang/lib/CodeGen/CGExpr.cpp  | 33 ++---
 clang/lib/CodeGen/CodeGenFunction.h   |  3 +-
 ...ptr-and-nonzero-offset-in-offsetof-idiom.c |  2 +-
 ...r-and-nonzero-offset-in-offsetof-idiom.cpp | 72 ++-
 5 files changed, 105 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..c2f7a519d270a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -42,6 +42,13 @@ Potentially Breaking Changes
 C/C++ Language Potentially Breaking Changes
 ---
 
+- New LLVM optimizations have been implemented that optimize pointer 
arithmetic on
+  null pointers more aggressively.  As part of this, clang has implemented a 
special
+  case for old-style offsetof idioms like ``((int)(&(((struct S 
*)0)->field)))``, to
+  ensure they are not caught by these optimizations.  It is also possible to 
use
+  ``-fwrapv-pointer`` or   ``-fno-delete-null-pointer-checks`` to make pointer 
arithmetic
+  on null pointers well-defined. (#GH130734, #GH130742)
+
 C++ Specific Potentially Breaking Changes
 -
 
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 451034395976f..c8ff2c880a655 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4785,6 +4785,16 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
   }
 
   Expr *BaseExpr = E->getBase();
+  bool IsInBounds = !getLangOpts().PointerOverflowDefined;
+  if (IsInBounds) {
+// Check whether the underlying base pointer is a constant null.
+// If so, we do not set inbounds flag for GEP to avoid breaking some
+// old-style offsetof idioms.
+Expr *UnderlyingBaseExpr = BaseExpr->IgnoreParens();
+while (auto *BaseMemberExpr = dyn_cast(UnderlyingBaseExpr))
+  UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
+IsInBounds = !getContext().isSentinelNullExpr(UnderlyingBaseExpr);
+  }
   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
   LValue BaseLV;
   if (E->isArrow()) {
@@ -4806,7 +4816,7 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
 
   NamedDecl *ND = E->getMemberDecl();
   if (auto *Field = dyn_cast(ND)) {
-LValue LV = EmitLValueForField(BaseLV, Field);
+LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
 setObjCGCLValueClass(getContext(), E, LV);
 if (getLangOpts().OpenMP) {
   // If the member was explicitly marked as nontemporal, mark it as
@@ -4892,12 +4902,15 @@ unsigned CodeGenFunction::getDebugInfoFIndex(const 
RecordDecl *Rec,
 /// Get the address of a zero-sized field within a record. The resulting
 /// address doesn't necessarily have the right type.
 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
-   const FieldDecl *Field) {
+   const FieldDecl *Field,
+   bool IsInBounds) {
   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
   CGF.getContext().getFieldOffset(Field));
   if (Offset.isZero())
 return Base;
   Base = Base.withElementType(CGF.Int8Ty);
+  if (!IsInBounds)
+return CGF.Builder.CreateConstByteGEP(Base, Offset);
   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
 }
 
@@ -4906,16 +4919,16 @@ static Address emitAddrOfZeroSizeField(CodeGenFunction 
&CGF, Address Base,
 ///
 /// The resulting address doesn't necessarily have the right type.
 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
-  const FieldDecl *field) {
+  const FieldDecl *field, bool IsInBounds) 
{
   if (isEmptyFieldForLayout(CGF.getContext(), field))
-return emitAddrOfZeroSizeField(CGF, base, field);
+return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
 
   const RecordDecl *rec = field->getParent();
 
   unsigned idx =
 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
 
-  if (CGF.getLangOpts().PointerOverflowDefined)
+  if (!IsInBounds)
 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
 
   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
@@ -4953,8 +4966,8 @@ static bool hasAnyVptr(const QualType Type, const 
ASTContext &Context) {
   return false;
 }
 
-LValue CodeGenFunction::EmitLValueForField(LValue base,
-   const FieldDecl *field) {
+LValue CodeGenFunction::

[clang] [BoundsSafety][Sema] Allow counted_by and counted_by_or_null on pointers where the pointee type is incomplete but potentially completable (PR #106321)

2025-04-09 Thread Dan Liew via cfe-commits


@@ -0,0 +1,584 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify 
%s
+
+#define __counted_by(f)  __attribute__((counted_by(f)))
+
+// 
=
+// # Struct incomplete type with attribute in the decl position
+// 
=
+
+// Note: This could be considered misleading. The typedef isn't actually on 
this
+// line. Also note the discrepancy in diagnostic count (27 vs 51) is due to
+// the pointer arithmetic on incomplete pointee type diagnostic always using
+// diagnostic text that refers to the underlying forward decl, even when the
+// typedef is used.
+// expected-note@+1 27{{forward declaration of 'Incomplete_t' (aka 'struct 
IncompleteTy')}}
+struct IncompleteTy; // expected-note 51{{forward declaration of 'struct 
IncompleteTy'}}
+
+typedef struct IncompleteTy Incomplete_t; 
+
+struct CBBufDeclPos {
+  int count;
+  struct IncompleteTy* buf __counted_by(count); // OK expected-note 
27{{__counted_by attribute is here}}
+  Incomplete_t* buf_typedef __counted_by(count); // OK expected-note 
27{{__counted_by attribute is here}}
+};
+
+void consume_struct_IncompleteTy(struct IncompleteTy* buf);
+
+int idx(void);
+
+
+
+void test_CBBufDeclPos(struct CBBufDeclPos* ptr) {
+  // 
===
+  // ## Local variable initialization
+  // 
===
+  struct CBBufDeclPos explicit_desig_init = {
+.count = 0,
+// expected-error@+1{{cannot initialize 'CBBufDeclPos::buf' that has type 
'struct IncompleteTy * __counted_by(count)' (aka 'struct IncompleteTy *') 
because the pointee type 'struct IncompleteTy' is incomplete and the 
'__counted_by' attribute requires the pointee type be complete when 
initializing; consider providing a complete definition for 'struct 
IncompleteTy' or using the '__sized_by' attribute}}
+.buf = 0x0,
+// expected-error@+1{{cannot initialize 'CBBufDeclPos::buf_typedef' that 
has type 'Incomplete_t * __counted_by(count)' (aka 'struct IncompleteTy *') 
because the pointee type 'Incomplete_t' (aka 'struct IncompleteTy') is 
incomplete and the '__counted_by' attribute requires the pointee type be 
complete when initializing; consider providing a complete definition for 
'Incomplete_t' or using the '__sized_by' attribute}}
+.buf_typedef = 0x0
+  };
+  // Variable is not currently marked as invalid so uses of the variable allows
+  // diagnostics to fire.
+  // expected-error@+1{{cannot assign to 'CBBufDeclPos::buf' that has type 
'struct IncompleteTy * __counted_by(count)' (aka 'struct IncompleteTy *') 
because the pointee type 'struct IncompleteTy' is incomplete and the 
'__counted_by' attribute requires the pointee type be complete when assigning; 
consider providing a complete definition for 'struct IncompleteTy' or using the 
'__sized_by' attribute}}
+  explicit_desig_init.buf = 0x0;
+  // expected-error@+1{{cannot assign to 'CBBufDeclPos::buf_typedef' that has 
type 'Incomplete_t * __counted_by(count)' (aka 'struct IncompleteTy *') because 
the pointee type 'Incomplete_t' (aka 'struct IncompleteTy') is incomplete and 
the '__counted_by' attribute requires the pointee type be complete when 
assigning; consider providing a complete definition for 'Incomplete_t' or using 
the '__sized_by' attribute}}
+  explicit_desig_init.buf_typedef = 0x0;
+  // expected-error@+1{{cannot use 'explicit_desig_init.buf' with type 'struct 
IncompleteTy * __counted_by(count)' (aka 'struct IncompleteTy *') because the 
pointee type 'struct IncompleteTy' is incomplete and the '__counted_by' 
attribute requires the pointee type be complete in this context; consider 
providing a complete definition for 'struct IncompleteTy' or using the 
'__sized_by' attribute}}
+  void *tmp = explicit_desig_init.buf;
+  // expected-error@+1{{cannot use 'explicit_desig_init.buf_typedef' with type 
'Incomplete_t * __counted_by(count)' (aka 'struct IncompleteTy *') because the 
pointee type 'Incomplete_t' (aka 'struct IncompleteTy') is incomplete and the 
'__counted_by' attribute requires the pointee type be complete in this context; 
consider providing a complete definition for 'Incomplete_t' or using the 
'__sized_by' attribute}}

delcypher wrote:

@Sirraide Thank you for these suggestions. I applied these in 

https://github.com/llvm/llvm-project/pull/106321/commits/0c9c62b60d7d602b87aa3bb612d1240cc70f470b

I realized while doing this that

* The existing note in my PR about where the `__counted_by` attribute could be 
declared could be replaced by the new diagnostic that suggests using 
`__sized_by` instead.
* The existing note in my PR about where the incomplete type is declared could 
be replaced with the new diagnostic that suggests com

[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-09 Thread via cfe-commits


@@ -5687,11 +5687,11 @@ bool TokenAnnotator::mustBreakBefore(const 
AnnotatedLine &Line,
 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
 !Left.Children.empty()) {
   // Support AllowShortFunctionsOnASingleLine for JavaScript.
-  return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
- Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty 
||
+  return (!Style.AllowShortFunctionsOnASingleLine.Inline &&
+  !Style.AllowShortFunctionsOnASingleLine.Other) ||
  (Left.NestingLevel == 0 && Line.Level == 0 &&
-  Style.AllowShortFunctionsOnASingleLine &
-  FormatStyle::SFS_InlineOnly);
+  Style.AllowShortFunctionsOnASingleLine.Inline &&
+  !Style.AllowShortFunctionsOnASingleLine.Other);

irymarchyk wrote:

Thanks, fixed. 

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


[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-09 Thread via cfe-commits


@@ -611,20 +611,40 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
   AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
 
-  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+  // Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;

irymarchyk wrote:

Thanks, fixed. Forgot to remove it.

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


[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-09 Thread via cfe-commits

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


[clang] [HLSL] Resource initialization by constructors (PR #135120)

2025-04-09 Thread Helena Kotas via cfe-commits

https://github.com/hekota created 
https://github.com/llvm/llvm-project/pull/135120

- Adds resource constructor that takes explicit binding for all resource 
classes.
- Updates implementation of default resource constructor to initialize resource 
handle to `poison`.
- Removes initialization of resource classes from Codegen.
- Initialization of `cbuffer` still needs to happen in `CGHLSLRuntime` because 
it does not have a corresponding resource class type.

Design proposal: llvm/wg-hlsl#197

Closes #134154 

>From 85001dcbc184491dfb24e9d2a39df46fd4c9a363 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Wed, 9 Apr 2025 18:17:26 -0700
Subject: [PATCH] Initialize resources by constructors

- add resource record constructor with explicit binding
- completes implementation of default resource constructor
- removes resource initialization for Codegen for resource records
- cbuffer still needs to be initialized in Codegen because it does not have a 
resource class type
---
 clang/include/clang/Basic/Builtins.td |  12 ++
 clang/include/clang/Sema/SemaHLSL.h   |   1 +
 clang/lib/CodeGen/CGHLSLBuiltins.cpp  |  18 ++
 clang/lib/CodeGen/CGHLSLRuntime.cpp   |  78 -
 clang/lib/Sema/HLSLBuiltinTypeDeclBuilder.cpp |  36 +++-
 clang/lib/Sema/HLSLBuiltinTypeDeclBuilder.h   |   1 +
 clang/lib/Sema/HLSLExternalSemaSource.cpp |   3 +-
 clang/lib/Sema/SemaDecl.cpp   |   6 +-
 clang/lib/Sema/SemaHLSL.cpp   |  89 ++
 .../test/AST/HLSL/StructuredBuffers-AST.hlsl  |  60 ++-
 clang/test/AST/HLSL/TypedBuffers-AST.hlsl |   5 +-
 .../ByteAddressBuffers-constructors.hlsl  | 129 +++---
 .../builtins/RWBuffer-constructor-opt.hlsl|   2 +-
 .../builtins/RWBuffer-constructor.hlsl| 117 -
 .../StructuredBuffers-constructors.hlsl   | 159 --
 clang/test/CodeGenHLSL/cbuffer.hlsl   |   8 +-
 .../CodeGenHLSL/cbuffer_with_packoffset.hlsl  |   4 +-
 clang/test/CodeGenHLSL/resource-bindings.hlsl |  52 +++---
 .../hlsl_resource_handle_attrs.hlsl   |   4 +-
 19 files changed, 610 insertions(+), 174 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 868e5b92acdc9..5e92715f59e57 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4789,6 +4789,18 @@ def HLSLResourceGetPointer : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void(...)";
 }
 
+def HLSLResourceCreatePoisonHandle : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_resource_createpoisonhandle"];
+  let Attributes = [NoThrow];
+  let Prototype = "void(...)";
+}
+
+def HLSLResourceCreateHandleFromBinding : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_resource_createhandlefrombinding"];
+  let Attributes = [NoThrow];
+  let Prototype = "void(...)";
+}
+
 def HLSLAll : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_all"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/include/clang/Sema/SemaHLSL.h 
b/clang/include/clang/Sema/SemaHLSL.h
index f333fe30e8da0..a913d6cce62bd 100644
--- a/clang/include/clang/Sema/SemaHLSL.h
+++ b/clang/include/clang/Sema/SemaHLSL.h
@@ -105,6 +105,7 @@ class SemaHLSL : public SemaBase {
  HLSLParamModifierAttr::Spelling Spelling);
   void ActOnTopLevelFunction(FunctionDecl *FD);
   void ActOnVariableDeclarator(VarDecl *VD);
+  bool ActOnUninitializedVarDecl(VarDecl *D);
   void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU);
   void CheckEntryPoint(FunctionDecl *FD);
   void CheckSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param,
diff --git a/clang/lib/CodeGen/CGHLSLBuiltins.cpp 
b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
index 99c62808c323d..c652f435781f0 100644
--- a/clang/lib/CodeGen/CGHLSLBuiltins.cpp
+++ b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
@@ -287,6 +287,24 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 RetTy, CGM.getHLSLRuntime().getCreateResourceGetPointerIntrinsic(),
 ArrayRef{HandleOp, IndexOp});
   }
+  case Builtin::BI__builtin_hlsl_resource_createpoisonhandle: {
+llvm::Type *HandleTy = CGM.getTypes().ConvertType(E->getType());
+return llvm::PoisonValue::get(HandleTy);
+  }
+  case Builtin::BI__builtin_hlsl_resource_createhandlefrombinding: {
+llvm::Type *HandleTy = CGM.getTypes().ConvertType(E->getType());
+Value *SpaceNoOp = EmitScalarExpr(E->getArg(1));
+Value *RegisterNoOp = EmitScalarExpr(E->getArg(2));
+Value *RangeOp = EmitScalarExpr(E->getArg(3));
+Value *IndexOp = EmitScalarExpr(E->getArg(4));
+// FIXME: NonUniformResourceIndex bit is not yet implemented
+Value *NonUniform =
+llvm::ConstantInt::get(llvm::Type::getInt1Ty(getLLVMContext()), false);
+return Builder.CreateIntrinsic(
+HandleTy, CGM.getHLSLRuntime().getCreateHandleFromBindingIntrinsic(),
+ArrayRef{SpaceNoOp, RegisterNoOp, Ran

[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-09 Thread via cfe-commits

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


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

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

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


[clang] [cfi][NFCI] Precommit tests to show nomerge functionality (PR #135104)

2025-04-09 Thread Thurston Dang via cfe-commits

https://github.com/thurstond created 
https://github.com/llvm/llvm-project/pull/135104

https://github.com/llvm/llvm-project/pull/120464 (and earlier CLs) added 
-fsanitize-merge functionality, which is intended to work for all "sanitizers". 
It is nearly correct for CFI.

This patch precommits some tests for CFI, to track the progress of future 
-fsanitize-merge fixes for CFI.

>From a48051b4c1e2230f46617265268d49c64846f21b Mon Sep 17 00:00:00 2001
From: Thurston Dang 
Date: Thu, 10 Apr 2025 00:03:08 +
Subject: [PATCH] [cfi][NFCI] Precommit tests to show nomerge functionality

https://github.com/llvm/llvm-project/pull/120464 (and earlier CLs) added 
-fsanitize-merge functionality, which is intended to work for all "sanitizers". 
It is nearly correct for CFI.

This patch precommits some tests for CFI, to track the progress of
future -fsanitize-merge fixes.
---
 clang/test/CodeGen/cfi-check-fail-nomerge.c  | 232 +++
 clang/test/CodeGen/cfi-check-fail2-nomerge.c | 206 
 clang/test/CodeGenCXX/cfi-mfcall-nomerge.cpp | 131 +++
 3 files changed, 569 insertions(+)
 create mode 100644 clang/test/CodeGen/cfi-check-fail-nomerge.c
 create mode 100644 clang/test/CodeGen/cfi-check-fail2-nomerge.c
 create mode 100644 clang/test/CodeGenCXX/cfi-mfcall-nomerge.cpp

diff --git a/clang/test/CodeGen/cfi-check-fail-nomerge.c 
b/clang/test/CodeGen/cfi-check-fail-nomerge.c
new file mode 100644
index 0..05ea8d8327904
--- /dev/null
+++ b/clang/test/CodeGen/cfi-check-fail-nomerge.c
@@ -0,0 +1,232 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --include-generated-funcs --version 5
+//
+// N.B. although the clang driver defaults to merge, clang_cc1 defaults to 
non-merge.
+// (This is similar to -fsanitize-recover, for which the default is also 
applied
+// at the driver level only.)
+// If optimization is disabled, merging is disabled (overrides 
-fsanitize-merge).
+
+// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux -fsanitize-cfi-cross-dso \
+// RUN: 
-fsanitize=cfi-icall,cfi-nvcall,cfi-vcall,cfi-unrelated-cast,cfi-derived-cast \
+// RUN: -fsanitize-trap=cfi-icall,cfi-nvcall \
+// RUN: -fsanitize-merge=cfi-icall,cfi-nvcall \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=MERGE
+
+// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux -fsanitize-cfi-cross-dso \
+// RUN: 
-fsanitize=cfi-icall,cfi-nvcall,cfi-vcall,cfi-unrelated-cast,cfi-derived-cast \
+// RUN: -fsanitize-trap=cfi-icall,cfi-nvcall \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=NO-MERGE
+
+// NOMERGE-LABEL: define dso_local void @caller(
+// NOMERGE-SAME: ptr noundef [[F:%.*]]) #[[ATTR0:[0-9]+]] !type 
[[META4:![0-9]+]] !type [[META5:![0-9]+]] !type [[META6:![0-9]+]] {
+// NOMERGE-NEXT:  [[ENTRY:.*:]]
+// NOMERGE-NEXT:[[F_ADDR:%.*]] = alloca ptr, align 8
+// NOMERGE-NEXT:store ptr [[F]], ptr [[F_ADDR]], align 8
+// NOMERGE-NEXT:[[TMP0:%.*]] = load ptr, ptr [[F_ADDR]], align 8
+// NOMERGE-NEXT:[[TMP1:%.*]] = call i1 @llvm.type.test(ptr [[TMP0]], 
metadata !"_ZTSFvvE"), !nosanitize [[META7:![0-9]+]]
+// NOMERGE-NEXT:br i1 [[TMP1]], label %[[CFI_CONT:.*]], label 
%[[CFI_SLOWPATH:.*]], !prof [[PROF8:![0-9]+]], !nosanitize [[META7]]
+// NOMERGE:   [[CFI_SLOWPATH]]:
+// NOMERGE-NEXT:call void @__cfi_slowpath(i64 9080559750644022485, ptr 
[[TMP0]]) #[[ATTR7:[0-9]+]], !nosanitize [[META7]]
+// NOMERGE-NEXT:br label %[[CFI_CONT]], !nosanitize [[META7]]
+// NOMERGE:   [[CFI_CONT]]:
+// NOMERGE-NEXT:call void [[TMP0]]()
+// NOMERGE-NEXT:ret void
+void caller(void (*f)(void)) {
+  f();
+}
+
+
+
+// MERGE-LABEL: define dso_local void @caller(
+// MERGE-SAME: ptr noundef [[F:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] 
!type [[META4:![0-9]+]] !type [[META5:![0-9]+]] !type [[META6:![0-9]+]] {
+// MERGE-NEXT:  [[ENTRY:.*:]]
+// MERGE-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.type.test(ptr [[F]], 
metadata !"_ZTSFvvE"), !nosanitize [[META7:![0-9]+]]
+// MERGE-NEXT:br i1 [[TMP0]], label %[[CFI_CONT:.*]], label 
%[[CFI_SLOWPATH:.*]], !prof [[PROF8:![0-9]+]], !nosanitize [[META7]]
+// MERGE:   [[CFI_SLOWPATH]]:
+// MERGE-NEXT:tail call void @__cfi_slowpath(i64 9080559750644022485, ptr 
[[F]]) #[[ATTR5:[0-9]+]], !nosanitize [[META7]]
+// MERGE-NEXT:br label %[[CFI_CONT]], !nosanitize [[META7]]
+// MERGE:   [[CFI_CONT]]:
+// MERGE-NEXT:tail call void [[F]]() #[[ATTR5]]
+// MERGE-NEXT:ret void
+//
+//
+// MERGE-LABEL: define weak_odr hidden void @__cfi_check_fail(
+// MERGE-SAME: ptr noundef [[TMP0:%.*]], ptr noundef [[TMP1:%.*]]) #[[ATTR0]] {
+// MERGE-NEXT:  [[ENTRY:.*:]]
+// MERGE-NEXT:[[DOTNOT:%.*]] = icmp eq ptr [[TMP0]], null, !nosanitize 
[[META7]]
+// MERGE-NEXT:br i1 [[DOTNOT]], label %[[TRAP:.*]], label %[[CONT:.*]], 
!prof [[PROF9:![0-9]+]], !nosanitize [[META7]]
+// MERGE:   [[TRAP]]:
+// MERGE-NEXT:tail call void @llvm.ubsantrap(i8 2) #[[AT

[clang] [clang] consistently quote expressions in diagnostics (PR #134769)

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


@@ -143,8 +143,8 @@ def note_constexpr_null_subobject : Note<
   "access array element of|perform pointer arithmetic on|"
   "access real component of|"
   "access imaginary component of}0 null pointer">;
-def note_constexpr_null_callee : Note<
-  "'%0' evaluates to a null function pointer">;
+def note_constexpr_null_callee
+: Note<"%0 evaluates to a null function pointer">;

mizvekov wrote:

Yeah, clang-format gained support for these files a while back.

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


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

2025-04-09 Thread Younan Zhang via cfe-commits

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


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


[clang] [CIR] Upstream binary assignments and comma (PR #135115)

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


@@ -807,6 +808,65 @@ class ScalarExprEmitter : public 
StmtVisitor {
   VISITCOMP(EQ)
   VISITCOMP(NE)
 #undef VISITCOMP
+
+  mlir::Value VisitBinAssign(const BinaryOperator *e) {
+const bool ignore = std::exchange(ignoreResultAssign, false);
+
+mlir::Value rhs;
+LValue lhs;
+
+switch (e->getLHS()->getType().getObjCLifetime()) {
+case Qualifiers::OCL_Strong:
+case Qualifiers::OCL_Autoreleasing:
+case Qualifiers::OCL_ExplicitNone:
+case Qualifiers::OCL_Weak:
+  assert(!cir::MissingFeatures::objCLifetime());
+  break;
+case Qualifiers::OCL_None:
+  // __block variables need to have the rhs evaluated first, plus this
+  // should improve codegen just a little.
+  rhs = Visit(e->getRHS());
+  assert(!cir::MissingFeatures::sanitizers());
+  // TODO(cir): This needs to be emitCheckedLValue() once we support
+  // sanitizers
+  lhs = cgf.emitLValue(e->getLHS());
+
+  // Store the value into the LHS. Bit-fields are handled specially because
+  // the result is altered by the store, i.e., [C99 6.5.16p1]
+  // 'An assignment expression has the value of the left operand after the
+  // assignment...'.
+  if (lhs.isBitField()) {
+cgf.emitStoreThroughBitfieldLValue(RValue::get(rhs), lhs, rhs);
+  } else {
+cgf.emitNullabilityCheck(lhs, rhs, e->getExprLoc());
+CIRGenFunction::SourceLocRAIIObject loc{
+cgf, cgf.getLoc(e->getSourceRange())};
+cgf.emitStoreThroughLValue(RValue::get(rhs), lhs);
+  }
+}
+
+// If the result is clearly ignored, return now.
+if (ignore)
+  return nullptr;
+
+// The result of an assignment in C is the assigned r-value.
+if (!cgf.getLangOpts().CPlusPlus)
+  return rhs;
+
+// If the lvalue is non-volatile, return the computed value of the
+// assignment.
+if (!lhs.isVolatile())
+  return rhs;
+
+// Otherwise, reload the value.
+return emitLoadOfLValue(lhs, e->getExprLoc());
+  }
+
+  mlir::Value VisitBinComma(const BinaryOperator *e) {
+cgf.emitIgnoredExpr(e->getLHS());
+// NOTE: We don't need to EnsureInsertPoint() like LLVM codegen.

erichkeane wrote:

Why not?

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


[clang] [clang-format] Keep the space between `not` and a unary operator (PR #135035)

2025-04-09 Thread Owen Pan via cfe-commits

owenca wrote:

/cherry-pick f34483838937b1a01ee11ee22bdd6e13c81e9fff

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


[clang] [clang-tools-extra] [libcxx] [clang] improved preservation of template keyword (PR #133610)

2025-04-09 Thread Jorge Gorbe Moya via cfe-commits

slackito wrote:

> @slackito this will be fixed here: #135111

Thanks for the quick fix!



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


[clang] 0283bb3 - [Clang][CodeGen][UBSan] Add more precise attributes to recoverable ubsan handlers (#130990)

2025-04-09 Thread via cfe-commits

Author: Yingwei Zheng
Date: 2025-04-10T11:09:45+08:00
New Revision: 0283bb3afcc5dc521f6b2e7d541a830a9546ed80

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

LOG: [Clang][CodeGen][UBSan] Add more precise attributes to recoverable ubsan 
handlers (#130990)

This patch adds `memory(argmem: read, inaccessiblemem: readwrite)
mustprogress` to **recoverable** ubsan handlers in order to unblock some
memory/loop optimizations. It provides an average of 3% performance
improvement on llvm-test-suite (except for 49 test failures due to ubsan
diagnostics).

Closes https://github.com/llvm/llvm-project/issues/130093.

Added: 
clang/test/CodeGen/ubsan-attr.cpp

Modified: 
clang/lib/CodeGen/CGExpr.cpp
clang/test/CodeGen/allow-ubsan-check.c
clang/test/CodeGen/attr-counted-by.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 451034395976f..28068d3408c62 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -3621,6 +3621,18 @@ static void emitCheckHandlerCall(CodeGenFunction &CGF,
 .addAttribute(llvm::Attribute::NoUnwind);
   }
   B.addUWTableAttr(llvm::UWTableKind::Default);
+  // Add more precise attributes to recoverable ubsan handlers for better
+  // optimizations.
+  if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 && MayReturn) {
+// __ubsan_handle_dynamic_type_cache_miss reads the vtable, which is also
+// accessible by the current module.
+if (CheckHandler != SanitizerHandler::DynamicTypeCacheMiss)
+  B.addMemoryAttr(llvm::MemoryEffects::argMemOnly(llvm::ModRefInfo::Ref) |
+  llvm::MemoryEffects::inaccessibleMemOnly());
+// If the handler does not return, it must interact with the environment in
+// an observable way.
+B.addAttribute(llvm::Attribute::MustProgress);
+  }
 
   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
   FnType, FnName,

diff  --git a/clang/test/CodeGen/allow-ubsan-check.c 
b/clang/test/CodeGen/allow-ubsan-check.c
index e225fb63f08eb..6358425aa40be 100644
--- a/clang/test/CodeGen/allow-ubsan-check.c
+++ b/clang/test/CodeGen/allow-ubsan-check.c
@@ -29,7 +29,7 @@
 // CHECK:   [[HANDLER_DIVREM_OVERFLOW]]:
 // CHECK-NEXT:[[TMP10:%.*]] = zext i32 [[X]] to i64, !nosanitize [[META2]]
 // CHECK-NEXT:[[TMP11:%.*]] = zext i32 [[Y]] to i64, !nosanitize [[META2]]
-// CHECK-NEXT:tail call void @__ubsan_handle_divrem_overflow_abort(ptr 
nonnull @[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR6:[0-9]+]], 
!nosanitize [[META2]]
+// CHECK-NEXT:tail call void @__ubsan_handle_divrem_overflow_abort(ptr 
nonnull @[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR8:[0-9]+]], 
!nosanitize [[META2]]
 // CHECK-NEXT:unreachable, !nosanitize [[META2]]
 // CHECK:   [[CONT]]:
 // CHECK-NEXT:[[DIV:%.*]] = sdiv i32 [[X]], [[Y]]
@@ -75,7 +75,7 @@
 // REC:   [[HANDLER_DIVREM_OVERFLOW]]:
 // REC-NEXT:[[TMP10:%.*]] = zext i32 [[X]] to i64, !nosanitize [[META2]]
 // REC-NEXT:[[TMP11:%.*]] = zext i32 [[Y]] to i64, !nosanitize [[META2]]
-// REC-NEXT:tail call void @__ubsan_handle_divrem_overflow(ptr nonnull 
@[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR6:[0-9]+]], !nosanitize 
[[META2]]
+// REC-NEXT:tail call void @__ubsan_handle_divrem_overflow(ptr nonnull 
@[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR8:[0-9]+]], !nosanitize 
[[META2]]
 // REC-NEXT:br label %[[CONT]], !nosanitize [[META2]]
 // REC:   [[CONT]]:
 // REC-NEXT:[[DIV:%.*]] = sdiv i32 [[X]], [[Y]]
@@ -86,7 +86,7 @@ int div(int x, int y) {
 }
 
 // CHECK-LABEL: define dso_local i32 @null(
-// CHECK-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR0]] {
+// CHECK-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR3:[0-9]+]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:[[TMP0:%.*]] = icmp eq ptr [[X]], null, !nosanitize [[META2]]
 //
@@ -95,7 +95,7 @@ int div(int x, int y) {
 // CHECK-NEXT:[[DOTNOT1:%.*]] = and i1 [[TMP0]], [[TMP1]]
 // CHECK-NEXT:br i1 [[DOTNOT1]], label %[[HANDLER_TYPE_MISMATCH:.*]], 
label %[[CONT:.*]], !prof [[PROF4:![0-9]+]], !nosanitize [[META2]]
 // CHECK:   [[HANDLER_TYPE_MISMATCH]]:
-// CHECK-NEXT:tail call void @__ubsan_handle_type_mismatch_v1_abort(ptr 
nonnull @[[GLOB2:[0-9]+]], i64 0) #[[ATTR6]], !nosanitize [[META2]]
+// CHECK-NEXT:tail call void @__ubsan_handle_type_mismatch_v1_abort(ptr 
nonnull @[[GLOB2:[0-9]+]], i64 0) #[[ATTR8]], !nosanitize [[META2]]
 // CHECK-NEXT:unreachable, !nosanitize [[META2]]
 // CHECK:   [[CONT]]:
 // CHECK-NEXT:[[TMP2:%.*]] = load i32, ptr [[X]], align 4, !tbaa 
[[TBAA5:![0-9]+]]
@@ -116,14 +116,14 @@ int div(int x, i

[clang] [Clang][CodeGen][UBSan] Add more precise attributes to recoverable ubsan handlers (PR #130990)

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

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


[clang] [Clang][CodeGen] Do not set inbounds flag for struct GEP with null base pointers (PR #130734)

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

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

>From 0f6ff605da3cbadc5311d4bf6c08fe98970a69c3 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Thu, 10 Apr 2025 09:54:33 +0800
Subject: [PATCH 1/3] [Clang][CodeGen] Do not set inbounds flag for struct GEP
 with null base pointers

---
 clang/docs/ReleaseNotes.rst   |  7 ++
 clang/lib/CodeGen/CGExpr.cpp  | 33 ++---
 clang/lib/CodeGen/CodeGenFunction.h   |  3 +-
 ...ptr-and-nonzero-offset-in-offsetof-idiom.c |  2 +-
 ...r-and-nonzero-offset-in-offsetof-idiom.cpp | 72 ++-
 5 files changed, 105 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd16641c25ed8..c2f7a519d270a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -42,6 +42,13 @@ Potentially Breaking Changes
 C/C++ Language Potentially Breaking Changes
 ---
 
+- New LLVM optimizations have been implemented that optimize pointer 
arithmetic on
+  null pointers more aggressively.  As part of this, clang has implemented a 
special
+  case for old-style offsetof idioms like ``((int)(&(((struct S 
*)0)->field)))``, to
+  ensure they are not caught by these optimizations.  It is also possible to 
use
+  ``-fwrapv-pointer`` or   ``-fno-delete-null-pointer-checks`` to make pointer 
arithmetic
+  on null pointers well-defined. (#GH130734, #GH130742)
+
 C++ Specific Potentially Breaking Changes
 -
 
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 451034395976f..c8ff2c880a655 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4785,6 +4785,16 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
   }
 
   Expr *BaseExpr = E->getBase();
+  bool IsInBounds = !getLangOpts().PointerOverflowDefined;
+  if (IsInBounds) {
+// Check whether the underlying base pointer is a constant null.
+// If so, we do not set inbounds flag for GEP to avoid breaking some
+// old-style offsetof idioms.
+Expr *UnderlyingBaseExpr = BaseExpr->IgnoreParens();
+while (auto *BaseMemberExpr = dyn_cast(UnderlyingBaseExpr))
+  UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
+IsInBounds = !getContext().isSentinelNullExpr(UnderlyingBaseExpr);
+  }
   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
   LValue BaseLV;
   if (E->isArrow()) {
@@ -4806,7 +4816,7 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr 
*E) {
 
   NamedDecl *ND = E->getMemberDecl();
   if (auto *Field = dyn_cast(ND)) {
-LValue LV = EmitLValueForField(BaseLV, Field);
+LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
 setObjCGCLValueClass(getContext(), E, LV);
 if (getLangOpts().OpenMP) {
   // If the member was explicitly marked as nontemporal, mark it as
@@ -4892,12 +4902,15 @@ unsigned CodeGenFunction::getDebugInfoFIndex(const 
RecordDecl *Rec,
 /// Get the address of a zero-sized field within a record. The resulting
 /// address doesn't necessarily have the right type.
 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
-   const FieldDecl *Field) {
+   const FieldDecl *Field,
+   bool IsInBounds) {
   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
   CGF.getContext().getFieldOffset(Field));
   if (Offset.isZero())
 return Base;
   Base = Base.withElementType(CGF.Int8Ty);
+  if (!IsInBounds)
+return CGF.Builder.CreateConstByteGEP(Base, Offset);
   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
 }
 
@@ -4906,16 +4919,16 @@ static Address emitAddrOfZeroSizeField(CodeGenFunction 
&CGF, Address Base,
 ///
 /// The resulting address doesn't necessarily have the right type.
 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
-  const FieldDecl *field) {
+  const FieldDecl *field, bool IsInBounds) 
{
   if (isEmptyFieldForLayout(CGF.getContext(), field))
-return emitAddrOfZeroSizeField(CGF, base, field);
+return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
 
   const RecordDecl *rec = field->getParent();
 
   unsigned idx =
 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
 
-  if (CGF.getLangOpts().PointerOverflowDefined)
+  if (!IsInBounds)
 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
 
   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
@@ -4953,8 +4966,8 @@ static bool hasAnyVptr(const QualType Type, const 
ASTContext &Context) {
   return false;
 }
 
-LValue CodeGenFunction::EmitLValueForField(LValue base,
-   const FieldDecl *field) {
+LValue CodeGenFuncti

[clang] [Clang][P1061] Fix invalid pack binding crash (PR #135129)

2025-04-09 Thread Jason Rice via cfe-commits

https://github.com/ricejasonf created 
https://github.com/llvm/llvm-project/pull/135129

Fixes #134882 

Consider
```
struct foo { char a; int b; };
constexpr foo t{'a', 1};
constexpr auto [...m] = t;
```
Without the `constexpr` qualifier, the decomposition declaration just happens 
to not crash in the call to `DeclMustBeEmitted` because it returns early 
because of its "discardable gval linkage". So, the fix is in `flat_bindings` 
where we cannot assume the pack binding is valid. There is also a fix along the 
same vein from a suggestion made by @shafik. The tests are still building on my 
machine, but I thought I would submit this to get eyes on it earlier since it 
is trivial.

>From 27290e3c7dc2a36a33e4582758d875704c7cbe33 Mon Sep 17 00:00:00 2001
From: Jason Rice 
Date: Wed, 9 Apr 2025 21:31:00 -0700
Subject: [PATCH] [Clang][P1061] Fix invalid pack binding crash

---
 clang/include/clang/AST/DeclCXX.h | 2 +-
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp| 5 ++---
 clang/test/SemaCXX/cxx2c-binding-pack-nontemplate.cpp | 6 ++
 3 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 56cec07ec0293..ba6d87f8158ab 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -4281,7 +4281,7 @@ class DecompositionDecl final
 [](BindingDecl *BD) { return BD->isParameterPack(); });
 
 Bindings = Bindings.drop_front(BeforePackBindings.size());
-if (!Bindings.empty()) {
+if (!Bindings.empty() && Bindings.front()->getBinding()) {
   PackBindings = Bindings.front()->getBindingPackDecls();
   Bindings = Bindings.drop_front();
 }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index e0f7ccc4674d8..4f7410c9bf0d8 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1597,11 +1597,10 @@ Decl 
*TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
   auto *NewDD = cast_if_present(
   VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
 
-  if (!NewDD || NewDD->isInvalidDecl())
+  if (!NewDD || NewDD->isInvalidDecl()) {
 for (auto *NewBD : NewBindings)
   NewBD->setInvalidDecl();
-
-  if (OldBindingPack) {
+  } else if (OldBindingPack) {
 // Mark the bindings in the pack as instantiated.
 auto Bindings = NewDD->bindings();
 BindingDecl *NewBindingPack = *llvm::find_if(
diff --git a/clang/test/SemaCXX/cxx2c-binding-pack-nontemplate.cpp 
b/clang/test/SemaCXX/cxx2c-binding-pack-nontemplate.cpp
index ea94757dc66b6..1818dc699c71c 100644
--- a/clang/test/SemaCXX/cxx2c-binding-pack-nontemplate.cpp
+++ b/clang/test/SemaCXX/cxx2c-binding-pack-nontemplate.cpp
@@ -8,4 +8,10 @@ void decompose_array() {
   // cxx23-warning@+2 {{structured binding packs are a C++2c extension}}
   // nontemplate-error@+1 {{pack declaration outside of template}}
   auto [x, ...rest, y] = arr;
+
+  // cxx26-warning@+4 {{structured binding packs are incompatible with C++ 
standards before C++2c}}
+  // cxx23-warning@+3 {{structured binding packs are a C++2c extension}}
+  // nontemplate-error@+2 {{decomposition declaration cannot be declared 
'constexpr'}}
+  // nontemplate-error@+1 {{pack declaration outside of template}}
+  constexpr auto [x, ...rest, y] = arr;
 }

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


[clang] [llvm] MCAsmStreamer: Replace the MCInstPrinter * parameter with unique_ptr (PR #135128)

2025-04-09 Thread Fangrui Song via cfe-commits

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


[clang] Revert "[Clang][CodeGen][UBSan] Add more precise attributes to recoverable ubsan handlers" (PR #135130)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yingwei Zheng (dtcxzyw)


Changes

Reverts llvm/llvm-project#130990

Breaks buildbot https://lab.llvm.org/buildbot/#/builders/186/builds/8072

---

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CGExpr.cpp (-12) 
- (modified) clang/test/CodeGen/allow-ubsan-check.c (+14-14) 
- (modified) clang/test/CodeGen/attr-counted-by.c (+116-116) 
- (removed) clang/test/CodeGen/ubsan-attr.cpp (-100) 


``diff
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 28068d3408c62..451034395976f 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -3621,18 +3621,6 @@ static void emitCheckHandlerCall(CodeGenFunction &CGF,
 .addAttribute(llvm::Attribute::NoUnwind);
   }
   B.addUWTableAttr(llvm::UWTableKind::Default);
-  // Add more precise attributes to recoverable ubsan handlers for better
-  // optimizations.
-  if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 && MayReturn) {
-// __ubsan_handle_dynamic_type_cache_miss reads the vtable, which is also
-// accessible by the current module.
-if (CheckHandler != SanitizerHandler::DynamicTypeCacheMiss)
-  B.addMemoryAttr(llvm::MemoryEffects::argMemOnly(llvm::ModRefInfo::Ref) |
-  llvm::MemoryEffects::inaccessibleMemOnly());
-// If the handler does not return, it must interact with the environment in
-// an observable way.
-B.addAttribute(llvm::Attribute::MustProgress);
-  }
 
   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
   FnType, FnName,
diff --git a/clang/test/CodeGen/allow-ubsan-check.c 
b/clang/test/CodeGen/allow-ubsan-check.c
index 6358425aa40be..e225fb63f08eb 100644
--- a/clang/test/CodeGen/allow-ubsan-check.c
+++ b/clang/test/CodeGen/allow-ubsan-check.c
@@ -29,7 +29,7 @@
 // CHECK:   [[HANDLER_DIVREM_OVERFLOW]]:
 // CHECK-NEXT:[[TMP10:%.*]] = zext i32 [[X]] to i64, !nosanitize [[META2]]
 // CHECK-NEXT:[[TMP11:%.*]] = zext i32 [[Y]] to i64, !nosanitize [[META2]]
-// CHECK-NEXT:tail call void @__ubsan_handle_divrem_overflow_abort(ptr 
nonnull @[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR8:[0-9]+]], 
!nosanitize [[META2]]
+// CHECK-NEXT:tail call void @__ubsan_handle_divrem_overflow_abort(ptr 
nonnull @[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR6:[0-9]+]], 
!nosanitize [[META2]]
 // CHECK-NEXT:unreachable, !nosanitize [[META2]]
 // CHECK:   [[CONT]]:
 // CHECK-NEXT:[[DIV:%.*]] = sdiv i32 [[X]], [[Y]]
@@ -75,7 +75,7 @@
 // REC:   [[HANDLER_DIVREM_OVERFLOW]]:
 // REC-NEXT:[[TMP10:%.*]] = zext i32 [[X]] to i64, !nosanitize [[META2]]
 // REC-NEXT:[[TMP11:%.*]] = zext i32 [[Y]] to i64, !nosanitize [[META2]]
-// REC-NEXT:tail call void @__ubsan_handle_divrem_overflow(ptr nonnull 
@[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR8:[0-9]+]], !nosanitize 
[[META2]]
+// REC-NEXT:tail call void @__ubsan_handle_divrem_overflow(ptr nonnull 
@[[GLOB1:[0-9]+]], i64 [[TMP10]], i64 [[TMP11]]) #[[ATTR6:[0-9]+]], !nosanitize 
[[META2]]
 // REC-NEXT:br label %[[CONT]], !nosanitize [[META2]]
 // REC:   [[CONT]]:
 // REC-NEXT:[[DIV:%.*]] = sdiv i32 [[X]], [[Y]]
@@ -86,7 +86,7 @@ int div(int x, int y) {
 }
 
 // CHECK-LABEL: define dso_local i32 @null(
-// CHECK-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR3:[0-9]+]] {
+// CHECK-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:[[TMP0:%.*]] = icmp eq ptr [[X]], null, !nosanitize [[META2]]
 //
@@ -95,7 +95,7 @@ int div(int x, int y) {
 // CHECK-NEXT:[[DOTNOT1:%.*]] = and i1 [[TMP0]], [[TMP1]]
 // CHECK-NEXT:br i1 [[DOTNOT1]], label %[[HANDLER_TYPE_MISMATCH:.*]], 
label %[[CONT:.*]], !prof [[PROF4:![0-9]+]], !nosanitize [[META2]]
 // CHECK:   [[HANDLER_TYPE_MISMATCH]]:
-// CHECK-NEXT:tail call void @__ubsan_handle_type_mismatch_v1_abort(ptr 
nonnull @[[GLOB2:[0-9]+]], i64 0) #[[ATTR8]], !nosanitize [[META2]]
+// CHECK-NEXT:tail call void @__ubsan_handle_type_mismatch_v1_abort(ptr 
nonnull @[[GLOB2:[0-9]+]], i64 0) #[[ATTR6]], !nosanitize [[META2]]
 // CHECK-NEXT:unreachable, !nosanitize [[META2]]
 // CHECK:   [[CONT]]:
 // CHECK-NEXT:[[TMP2:%.*]] = load i32, ptr [[X]], align 4, !tbaa 
[[TBAA5:![0-9]+]]
@@ -116,14 +116,14 @@ int div(int x, int y) {
 // TR-NEXT:ret i32 [[TMP2]]
 //
 // REC-LABEL: define dso_local i32 @null(
-// REC-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR3:[0-9]+]] {
+// REC-SAME: ptr noundef readonly captures(address_is_null) [[X:%.*]]) 
local_unnamed_addr #[[ATTR0]] {
 // REC-NEXT:  [[ENTRY:.*:]]
 // REC-NEXT:[[TMP0:%.*]] = icmp eq ptr [[X]], null, !nosanitize [[META2]]
 // REC-NEXT:[[TMP1:%.*]] 

[clang] [clang-format] Keep the space between `not` and a unary operator (PR #135035)

2025-04-09 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang] fix NestedNameSpecifier dependency calculation (PR #135067)

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

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


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


[clang] [Clang][Sema]:Fix musttail attribute on a function with not_tail_called attribute has no warning/error (PR #134465)

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

mizvekov wrote:

I agree that if we can't guarantee it will be tail-called, this must be an 
error.

must_tail is not an optimization.

In fact, LLVM by itself will already perform tail call optimizations, and 
remove them when it would not be profitable in terms of execution cost.

The point of must_tail is to support cases where the tail call is required for 
correctness, otherwise by ignoring it will lead to UB.

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


[clang] [llvm] [Clang][OpenMP] Support for dispatch construct (Sema & Codegen) support (PR #131838)

2025-04-09 Thread via cfe-commits

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


[clang] [Clang][Sema]:Fix musttail attribute on a function with not_tail_called attribute has no warning/error (PR #134465)

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

AaronBallman wrote:

> > > @AaronBallman @erichkeane Thank you for your comments. There's a question 
> > > here about whether to report an error or a warning here, and you're in a 
> > > divided opinion. My opinion is that it is better to use the error report 
> > > here. Because these are two mutually exclusive conditions, it is 
> > > semantically unreasonable to set tail calls or non-tail calls even if the 
> > > program is still run after a warning is reported. I still want to hear 
> > > your opinions. Regarding the PR title, PR information, test cases, I will 
> > > fill in the next submission. Thank you both again.
> > 
> > 
> > I favor an error in this case because the whole point to `musttail` is to 
> > _ensure_ that a tail call happens or the code is rejected: 
> > https://clang.llvm.org/docs/AttributeReference.html#musttail
> 
> I lean towards warning, only because the behavior is 'ignored attribute', and 
> those are a specific warning group.

CC @haberman as the original author of `musttail` in Clang, but 
8344675908424ee532d4ae30e5043c5a5834e02c was the original commit for this 
feature and *every* misuse of `musttail` is an error there. What I recall of 
the design discussion is that guarantees are the entire point to using the 
attribute. In fact, the original commit message said "The  attribute is applied 
to a return statement (not a function declaration), and an error is emitted if 
a tail call cannot be guaranteed, for example if the function signatures of 
caller and callee are not compatible. Guaranteed tail calls enable a class of 
algorithms that would otherwise use an arbitrary amount of stack space."

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


[clang] [llvm] [HLSL][SPIR-V] Add hlsl_private address space for SPIR-V (PR #133464)

2025-04-09 Thread Nathan Gauër via cfe-commits

https://github.com/Keenuts updated 
https://github.com/llvm/llvm-project/pull/133464

From 12524667594d413c93a2c88a206a930cff638da3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nathan=20Gau=C3=ABr?= 
Date: Thu, 28 Nov 2024 15:00:56 +0100
Subject: [PATCH 1/6] [SPIR-V] Add hlsl_private address space for SPIR-V

In SPIR-V, private global variables have the Private storage class.
This PR adds a new address space which allows frontend to emit
variable with this storage class when targeting this backend.

This is covered in this proposal: llvm/wg-hlsl@4c9e11a

This PR will cause addrspacecast to show up in several cases, like class
member functions or assignment. Those will have to be handled in the
backend later on, particularly to fixup pointer storage classes in some
functions.

Before this change, global variable were emitted with the 'Function'
storage class, which was wrong.
---
 clang/include/clang/Basic/AddressSpaces.h |  1 +
 clang/include/clang/Sema/Sema.h   |  1 +
 clang/lib/AST/Type.cpp|  5 ++
 clang/lib/AST/TypePrinter.cpp |  2 +
 clang/lib/Basic/TargetInfo.cpp|  2 +
 clang/lib/Basic/Targets/AArch64.h |  1 +
 clang/lib/Basic/Targets/AMDGPU.cpp|  4 ++
 clang/lib/Basic/Targets/DirectX.h |  1 +
 clang/lib/Basic/Targets/NVPTX.h   |  1 +
 clang/lib/Basic/Targets/SPIR.h| 48 ++-
 clang/lib/Basic/Targets/SystemZ.h |  1 +
 clang/lib/Basic/Targets/TCE.h |  1 +
 clang/lib/Basic/Targets/WebAssembly.h |  1 +
 clang/lib/Basic/Targets/X86.h |  1 +
 clang/lib/CodeGen/CGDeclCXX.cpp   | 16 ++-
 clang/lib/CodeGen/CodeGenFunction.cpp | 12 ++---
 clang/lib/Sema/SemaDecl.cpp   | 35 ++
 clang/test/AST/HLSL/cbuffer.hlsl  |  2 +-
 .../test/CodeGenHLSL/GlobalConstructors.hlsl  | 15 --
 ...uffer_with_static_global_and_function.hlsl |  1 +
 .../test/CodeGenHLSL/out-of-line-static.hlsl  | 30 
 clang/test/CodeGenHLSL/static-variable.hlsl   | 18 +++
 .../SemaTemplate/address_space-dependent.cpp  |  4 +-
 llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp  |  3 ++
 24 files changed, 169 insertions(+), 37 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/out-of-line-static.hlsl
 create mode 100644 clang/test/CodeGenHLSL/static-variable.hlsl

diff --git a/clang/include/clang/Basic/AddressSpaces.h 
b/clang/include/clang/Basic/AddressSpaces.h
index d18bfe54931f9..5787e6dac0e36 100644
--- a/clang/include/clang/Basic/AddressSpaces.h
+++ b/clang/include/clang/Basic/AddressSpaces.h
@@ -59,6 +59,7 @@ enum class LangAS : unsigned {
   // HLSL specific address spaces.
   hlsl_groupshared,
   hlsl_constant,
+  hlsl_private,
 
   // Wasm specific address spaces.
   wasm_funcref,
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 7bd77d33a1f3d..94b3792d25350 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4328,6 +4328,7 @@ class Sema final : public SemaBase {
   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
 
   void deduceOpenCLAddressSpace(ValueDecl *decl);
+  void deduceHLSLAddressSpace(VarDecl *decl);
 
   /// Adjust the \c DeclContext for a function or variable that might be a
   /// function-local external declaration.
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 4336fe44b82ad..dcdb0104f0224 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -94,6 +94,8 @@ bool Qualifiers::isTargetAddressSpaceSupersetOf(LangAS A, 
LangAS B,
  (A == LangAS::Default &&
   (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
B == LangAS::cuda_shared)) ||
+ // Default is a superset of HLSL private.
+ (A == LangAS::Default && B == LangAS::hlsl_private) ||
  // Conversions from target specific address spaces may be legal
  // depending on the target information.
  Ctx.getTargetInfo().isAddressSpaceSupersetOf(A, B);
@@ -5168,6 +5170,9 @@ bool Type::isHLSLIntangibleType() const {
   CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
   assert(RD != nullptr &&
  "all HLSL structs and classes should be CXXRecordDecl");
+
+  if (!RD->isCompleteDefinition())
+return false;
   assert(RD->isCompleteDefinition() && "expecting complete type");
   return RD->isHLSLIntangible();
 }
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 4ec252e3f89b5..4f2b00d19a446 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2581,6 +2581,8 @@ std::string Qualifiers::getAddrSpaceAsString(LangAS AS) {
 return "groupshared";
   case LangAS::hlsl_constant:
 return "hlsl_constant";
+  case LangAS::hlsl_private:
+return "hlsl_private";
   case LangAS::wasm_funcref:
 return "__funcref";
   default:
diff --git a/clang/lib/Basic/Targe

[clang] [llvm] [DirectX] Implement Shader Flags Analysis for ResMayNotAlias (PR #131070)

2025-04-09 Thread Deric C. via cfe-commits

https://github.com/Icohedron updated 
https://github.com/llvm/llvm-project/pull/131070

>From 81196e016dbf1209637dd13315efff7eac461d42 Mon Sep 17 00:00:00 2001
From: Icohedron 
Date: Fri, 14 Mar 2025 00:24:26 +
Subject: [PATCH 1/8] Implement ResMayNotAlias DXIL shader flag analysis

---
 clang/include/clang/Basic/CodeGenOptions.def  |  3 ++
 clang/include/clang/Driver/Options.td |  5 +++
 clang/lib/CodeGen/CGHLSLRuntime.cpp   |  3 ++
 clang/lib/Driver/ToolChains/Clang.cpp |  1 +
 clang/test/CodeGenHLSL/res-may-alias.hlsl |  7 +++
 llvm/lib/Target/DirectX/DXILShaderFlags.cpp   | 43 ---
 llvm/lib/Target/DirectX/DXILShaderFlags.h |  9 +++-
 .../DirectX/ShaderFlags/res-may-alias-0.ll| 39 +
 .../DirectX/ShaderFlags/res-may-alias-1.ll| 37 
 .../res-may-not-alias-shadermodel6.7.ll   | 33 ++
 .../res-may-not-alias-shadermodel6.8.ll   | 33 ++
 .../typed-uav-load-additional-formats.ll  |  9 ++--
 12 files changed, 210 insertions(+), 12 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/res-may-alias.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-0.ll
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-1.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.7.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.8.ll

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index a7f5f1abbb825..a436c0ec98d5b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -476,6 +476,9 @@ CODEGENOPT(ImportCallOptimization, 1, 0)
 /// (BlocksRuntime) on Windows.
 CODEGENOPT(StaticClosure, 1, 0)
 
+/// Assume that UAVs/SRVs may alias
+CODEGENOPT(ResMayAlias, 1, 0)
+
 /// FIXME: Make DebugOptions its own top-level .def file.
 #include "DebugOptions.def"
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 66ae8f1c7f064..9c5fd2354f95e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -9043,6 +9043,11 @@ def dxil_validator_version : Option<["/", "-"], 
"validator-version", KIND_SEPARA
   HelpText<"Override validator version for module. Format: ;"
"Default: DXIL.dll version or current internal version">,
   MarshallingInfoString, "\"1.8\"">;
+def res_may_alias : Option<["/", "-"], "res-may-alias", KIND_FLAG>,
+  Group, Flags<[HelpHidden]>,
+  Visibility<[DXCOption, ClangOption, CC1Option]>,
+  HelpText<"Assume that UAVs/SRVs may alias">,
+  MarshallingInfoFlag>;
 def target_profile : DXCJoinedOrSeparate<"T">, MetaVarName<"">,
   HelpText<"Set target profile">,
   Values<"ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7,"
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 5916fa6183a27..6fd8bc295e8ca 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -283,10 +283,13 @@ void CGHLSLRuntime::addHLSLBufferLayoutType(const 
RecordType *StructType,
 
 void CGHLSLRuntime::finishCodeGen() {
   auto &TargetOpts = CGM.getTarget().getTargetOpts();
+  auto &CodeGenOpts = CGM.getCodeGenOpts();
   llvm::Module &M = CGM.getModule();
   Triple T(M.getTargetTriple());
   if (T.getArch() == Triple::ArchType::dxil)
 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
+  if (CodeGenOpts.ResMayAlias)
+M.setModuleFlag(llvm::Module::ModFlagBehavior::Error, "dx.resmayalias", 1);
 
   generateGlobalCtorDtorCalls();
 }
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index fe172d923ac07..9be3939641cfc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3959,6 +3959,7 @@ static void RenderOpenCLOptions(const ArgList &Args, 
ArgStringList &CmdArgs,
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_res_may_alias,
  options::OPT_D,
  options::OPT_I,
  options::OPT_O,
diff --git a/clang/test/CodeGenHLSL/res-may-alias.hlsl 
b/clang/test/CodeGenHLSL/res-may-alias.hlsl
new file mode 100644
index 0..53ee8ee4935d8
--- /dev/null
+++ b/clang/test/CodeGenHLSL/res-may-alias.hlsl
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -res-may-alias -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disable-llvm-passes -o - %s | 
FileCheck %s --check-prefix=FLAG
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disable-

[clang] [llvm] [DirectX] Implement Shader Flags Analysis for ResMayNotAlias (PR #131070)

2025-04-09 Thread Deric C. via cfe-commits

https://github.com/Icohedron updated 
https://github.com/llvm/llvm-project/pull/131070

>From 81196e016dbf1209637dd13315efff7eac461d42 Mon Sep 17 00:00:00 2001
From: Icohedron 
Date: Fri, 14 Mar 2025 00:24:26 +
Subject: [PATCH 1/9] Implement ResMayNotAlias DXIL shader flag analysis

---
 clang/include/clang/Basic/CodeGenOptions.def  |  3 ++
 clang/include/clang/Driver/Options.td |  5 +++
 clang/lib/CodeGen/CGHLSLRuntime.cpp   |  3 ++
 clang/lib/Driver/ToolChains/Clang.cpp |  1 +
 clang/test/CodeGenHLSL/res-may-alias.hlsl |  7 +++
 llvm/lib/Target/DirectX/DXILShaderFlags.cpp   | 43 ---
 llvm/lib/Target/DirectX/DXILShaderFlags.h |  9 +++-
 .../DirectX/ShaderFlags/res-may-alias-0.ll| 39 +
 .../DirectX/ShaderFlags/res-may-alias-1.ll| 37 
 .../res-may-not-alias-shadermodel6.7.ll   | 33 ++
 .../res-may-not-alias-shadermodel6.8.ll   | 33 ++
 .../typed-uav-load-additional-formats.ll  |  9 ++--
 12 files changed, 210 insertions(+), 12 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/res-may-alias.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-0.ll
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-1.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.7.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.8.ll

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index a7f5f1abbb825..a436c0ec98d5b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -476,6 +476,9 @@ CODEGENOPT(ImportCallOptimization, 1, 0)
 /// (BlocksRuntime) on Windows.
 CODEGENOPT(StaticClosure, 1, 0)
 
+/// Assume that UAVs/SRVs may alias
+CODEGENOPT(ResMayAlias, 1, 0)
+
 /// FIXME: Make DebugOptions its own top-level .def file.
 #include "DebugOptions.def"
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 66ae8f1c7f064..9c5fd2354f95e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -9043,6 +9043,11 @@ def dxil_validator_version : Option<["/", "-"], 
"validator-version", KIND_SEPARA
   HelpText<"Override validator version for module. Format: ;"
"Default: DXIL.dll version or current internal version">,
   MarshallingInfoString, "\"1.8\"">;
+def res_may_alias : Option<["/", "-"], "res-may-alias", KIND_FLAG>,
+  Group, Flags<[HelpHidden]>,
+  Visibility<[DXCOption, ClangOption, CC1Option]>,
+  HelpText<"Assume that UAVs/SRVs may alias">,
+  MarshallingInfoFlag>;
 def target_profile : DXCJoinedOrSeparate<"T">, MetaVarName<"">,
   HelpText<"Set target profile">,
   Values<"ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7,"
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 5916fa6183a27..6fd8bc295e8ca 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -283,10 +283,13 @@ void CGHLSLRuntime::addHLSLBufferLayoutType(const 
RecordType *StructType,
 
 void CGHLSLRuntime::finishCodeGen() {
   auto &TargetOpts = CGM.getTarget().getTargetOpts();
+  auto &CodeGenOpts = CGM.getCodeGenOpts();
   llvm::Module &M = CGM.getModule();
   Triple T(M.getTargetTriple());
   if (T.getArch() == Triple::ArchType::dxil)
 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
+  if (CodeGenOpts.ResMayAlias)
+M.setModuleFlag(llvm::Module::ModFlagBehavior::Error, "dx.resmayalias", 1);
 
   generateGlobalCtorDtorCalls();
 }
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index fe172d923ac07..9be3939641cfc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3959,6 +3959,7 @@ static void RenderOpenCLOptions(const ArgList &Args, 
ArgStringList &CmdArgs,
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_res_may_alias,
  options::OPT_D,
  options::OPT_I,
  options::OPT_O,
diff --git a/clang/test/CodeGenHLSL/res-may-alias.hlsl 
b/clang/test/CodeGenHLSL/res-may-alias.hlsl
new file mode 100644
index 0..53ee8ee4935d8
--- /dev/null
+++ b/clang/test/CodeGenHLSL/res-may-alias.hlsl
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -res-may-alias -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disable-llvm-passes -o - %s | 
FileCheck %s --check-prefix=FLAG
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disable-

[clang] [CIR] Upstream ArraySubscriptExpr for fixed size array (PR #134536)

2025-04-09 Thread Amr Hesham via cfe-commits

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


[clang] [CIR] Upstream ArraySubscriptExpr for fixed size array (PR #134536)

2025-04-09 Thread Amr Hesham via cfe-commits


@@ -390,6 +391,148 @@ LValue CIRGenFunction::emitUnaryOpLValue(const 
UnaryOperator *e) {
   llvm_unreachable("Unknown unary operator kind!");
 }
 
+/// If the specified expr is a simple decay from an array to pointer,
+/// return the array subexpression.
+/// FIXME: this could be abstracted into a common AST helper.
+static const Expr *getSimpleArrayDecayOperand(const Expr *e) {
+  // If this isn't just an array->pointer decay, bail out.
+  const auto *castExpr = dyn_cast(e);
+  if (!castExpr || castExpr->getCastKind() != CK_ArrayToPointerDecay)
+return nullptr;
+
+  // If this is a decay from variable width array, bail out.
+  const Expr *subExpr = castExpr->getSubExpr();
+  if (subExpr->getType()->isVariableArrayType())
+return nullptr;
+
+  return subExpr;
+}
+
+static mlir::IntegerAttr getConstantIndexOrNull(mlir::Value idx) {
+  // TODO(cir): should we consider using MLIRs IndexType instead of 
IntegerAttr?
+  if (auto constantOp = dyn_cast(idx.getDefiningOp()))
+return mlir::dyn_cast(constantOp.getValue());

AmrDeveloper wrote:

I am thinking to upstream at least `isPreserveAIArrayBase` because now even 
this NYI message is wrong, it should be related to `PreserveAIArray` so I think 
it better to upstream isPreserveAIArrayBase so I can make the else branch 
related to it`cgf.cgm.errorNYI("emitArraySubscriptExpr: Non Constant Index");`

What do you think? @andykaylor 

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


[clang] [flang] [driver] Generalize the code that adds the path of libflang_rt.runtime.a. (PR #134362)

2025-04-09 Thread Daniel Chen via cfe-commits

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


[clang] Implement `-dump-minimization-hints` flag. (PR #133910)

2025-04-09 Thread Viktoriia Bakalova via cfe-commits


@@ -121,6 +305,25 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
   if (!Consumer)
 return nullptr;
 
+  std::vector> Consumers;
+  llvm::StringRef DumpDeserializedDeclarationRangesPath =
+  CI.getFrontendOpts().DumpMinimizationHintsPath;
+  if (!DumpDeserializedDeclarationRangesPath.empty()) {
+std::error_code ErrorCode;
+auto FileStream = std::make_unique(
+DumpDeserializedDeclarationRangesPath, ErrorCode,
+llvm::sys::fs::OF_None);
+if (!ErrorCode) {
+  Consumers.push_back(std::make_unique(
+  CI.getSourceManager(), std::move(FileStream)));
+} else {
+  llvm::errs() << "Failed to create output file for "
+  "-dump-deserialized-declaration-ranges flag, file path: "

VitaNuo wrote:

Thanks!

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


[clang] [CIR] Upstream initial function call support (PR #134673)

2025-04-09 Thread Bruno Cardoso Lopes via cfe-commits

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

LGTM after few extra nits

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


[clang] [PAC] Add support for __ptrauth type qualifier (PR #100830)

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


@@ -0,0 +1,142 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios -std=c++11  -fptrauth-calls 
-fptrauth-intrinsics -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -std=c++11  -fptrauth-calls 
-fptrauth-intrinsics -verify -fsyntax-only %s
+
+#define AQ __ptrauth(1,1,50)
+#define AQ2 __ptrauth(1,1,51)
+#define IQ __ptrauth(1,0,50)
+
+struct __attribute__((trivial_abi)) AddrDisc { // expected-warning 
{{'trivial_abi' cannot be applied to 'AddrDisc'}} expected-note {{'trivial_abi' 
is disallowed on 'AddrDisc' because it has an address-discriminated '__ptrauth' 
field}}
+  int * AQ m0;
+};
+
+struct __attribute__((trivial_abi)) NoAddrDisc {
+  int * IQ m0;
+};
+
+namespace test_union {
+
+  union U0 {
+int * AQ f0; // expected-note 4 {{'U0' is implicitly deleted because 
variant field 'f0' has an address-discriminated '__ptrauth' qualifier}}
+
+// ptrauth fields that don't have an address-discriminated qualifier don't
+// delete the special functions.
+int * IQ f1;
+  };
+
+  union U1 {
+int * AQ f0; // expected-note 8 {{'U1' is implicitly deleted because 
variant field 'f0' has an address-discriminated '__ptrauth' qualifier}}
+U1() = default;
+~U1() = default;
+U1(const U1 &) = default; // expected-warning {{explicitly defaulted copy 
constructor is implicitly deleted}} expected-note 2 {{explicitly defaulted 
function was implicitly deleted here}} expected-note{{replace 'default'}}
+U1(U1 &&) = default; // expected-warning {{explicitly defaulted move 
constructor is implicitly deleted}} expected-note{{replace 'default'}}
+U1 & operator=(const U1 &) = default; // expected-warning {{explicitly 
defaulted copy assignment operator is implicitly deleted}} expected-note 2 
{{explicitly defaulted function was implicitly deleted here}} 
expected-note{{replace 'default'}}
+U1 & operator=(U1 &&) = default; // expected-warning {{explicitly 
defaulted move assignment operator is implicitly deleted}} 
expected-note{{replace 'default'}}
+  };
+
+  // It's fine if the user has explicitly defined the special functions.
+  union U2 {
+int * AQ f0;
+U2() = default;
+~U2() = default;
+U2(const U2 &);
+U2(U2 &&);
+U2 & operator=(const U2 &);
+U2 & operator=(U2 &&);
+  };
+
+  // Address-discriminated ptrauth fields in anonymous union fields delete the
+  // defaulted copy/move constructors/assignment operators of the containing
+  // class.
+  struct S0 {
+union {
+  int * AQ f0; // expected-note 4 {{' is implicitly deleted because 
variant field 'f0' has an address-discriminated '__ptrauth' qualifier}}
+  char f1;
+};
+  };
+
+  struct S1 {
+union {
+  union {
+int * AQ f0; // expected-note 4 {{implicitly deleted because variant 
field 'f0' has an address-discriminated '__ptrauth' qualifier}}
+char f1;
+  } u; // expected-note 4 {{'S1' is implicitly deleted because field 'u' 
has a deleted}}
+  int f2;
+};
+  };
+
+  U0 *x0;
+  U1 *x1;
+  U2 *x2;
+  S0 *x3;
+  S1 *x4;
+
+  // No diagnostics since constructors/destructors of the unions aren't 
deleted by default.
+  void testDefaultConstructor() {
+U0 u0;
+U1 u1;
+U2 u2;
+S0 s0;
+S1 s1;
+  }
+
+  // No diagnostics since destructors of the unions aren't deleted by default.
+  void testDestructor(U0 *u0, U1 *u1, U2 *u2, S0 *s0, S1 *s1) {
+delete u0;
+delete u1;
+delete u2;
+delete s0;
+delete s1;
+  }
+
+  void testCopyConstructor(U0 *u0, U1 *u1, U2 *u2, S0 *s0, S1 *s1) {
+U0 t0(*u0); // expected-error {{call to implicitly-deleted copy 
constructor}}
+U1 t1(*u1); // expected-error {{call to implicitly-deleted copy 
constructor}}
+U2 t2(*u2);
+S0 t3(*s0); // expected-error {{call to implicitly-deleted copy 
constructor}}
+S1 t4(*s1); // expected-error {{call to implicitly-deleted copy 
constructor}}
+  }
+
+  void testCopyAssignment(U0 *u0, U1 *u1, U2 *u2, S0 *s0, S1 *s1) {
+*x0 = *u0; // expected-error {{cannot be assigned because its copy 
assignment operator is implicitly deleted}}
+*x1 = *u1; // expected-error {{cannot be assigned because its copy 
assignment operator is implicitly deleted}}
+*x2 = *u2;
+*x3 = *s0; // expected-error {{cannot be assigned because its copy 
assignment operator is implicitly deleted}}
+*x4 = *s1; // expected-error {{cannot be assigned because its copy 
assignment operator is implicitly deleted}}
+  }
+
+  void testMoveConstructor(U0 *u0, U1 *u1, U2 *u2, S0 *s0, S1 *s1) {
+U0 t0(static_cast(*u0)); // expected-error {{call to 
implicitly-deleted copy constructor}}
+U1 t1(static_cast(*u1)); // expected-error {{call to 
implicitly-deleted copy constructor}}
+U2 t2(static_cast(*u2));
+S0 t3(static_cast(*s0)); // expected-error {{call to 
implicitly-deleted copy constructor}}
+S1 t4(static_cast(*s1)); // expected-error {{call to 
implicitly-deleted copy constructor}}
+  }
+
+  void testMoveAssignme

[clang] [llvm] [Clang] [OpenMP] Support NOWAIT with optional argument (PR #135030)

2025-04-09 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-09 Thread via cfe-commits


@@ -5687,11 +5687,11 @@ bool TokenAnnotator::mustBreakBefore(const 
AnnotatedLine &Line,
 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
 !Left.Children.empty()) {
   // Support AllowShortFunctionsOnASingleLine for JavaScript.
-  return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
- Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty 
||
+  return (!Style.AllowShortFunctionsOnASingleLine.Inline &&
+  !Style.AllowShortFunctionsOnASingleLine.Other) ||
  (Left.NestingLevel == 0 && Line.Level == 0 &&
-  Style.AllowShortFunctionsOnASingleLine &
-  FormatStyle::SFS_InlineOnly);
+  Style.AllowShortFunctionsOnASingleLine.Inline &&
+  !Style.AllowShortFunctionsOnASingleLine.Other);

sstwcw wrote:

It looks like you should not add inline here.  The old check uses `&`.  That is 
same as comparing against `SFS_All`.  The idea is that the brace should be on a 
new line if either the `AllosShortFunctionsOnASingleLine` is completely 
disabled, or the function is at the top level and the other option is disabled.

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


[clang] [llvm] [HLSL][SPIR-V] Add hlsl_private address space for SPIR-V (PR #133464)

2025-04-09 Thread Helena Kotas via cfe-commits
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= 
Message-ID:
In-Reply-To: 


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

LGTM! Thanks!

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


[clang] [llvm] [IR] Mark convergence intrins as has-side-effect (PR #134844)

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

arsenm wrote:

Thinking we should remove the IR verification requirement. It's more of a lint 
type check and violations would be UB 

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


[clang] [CXX Safe Buffer] Update the safe buffer attribute documentation (PR #135087)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Malavika Samak (malavikasamak)


Changes

Update the documentation for the unsafe_buffer_usage attribute to capture the 
new behavior introduced by https://github.com/llvm/llvm-project/pull/125671

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


1 Files Affected:

- (modified) clang/include/clang/Basic/AttrDocs.td (+5-3) 


``diff
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c8b371280e35d..1546d849f6856 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7517,9 +7517,11 @@ the field it is attached to, and it may also lead to 
emission of automatic fix-i
 hints which would help the user replace the use of unsafe functions(/fields) 
with safe
 alternatives, though the attribute can be used even when the fix can't be 
automated.
 
-* Attribute attached to functions: The attribute does not suppress
-  ``-Wunsafe-buffer-usage`` inside the function to which it is attached.
-  These warnings still need to be addressed.
+* Attribute attached to functions: The attribute suppresses all the
+  ``-Wunsafe-buffer-usage`` warnings inside the function to which it is 
attached, since
+  it is now classified as an unsafe function. The attribute must be placed 
judiciously
+  as there won't be any warning for unsafe operations within the function and 
this can
+  also cause it to mask new usafe operations introduced in the future.
 
   The attribute is warranted even if the only way a function can overflow
   the buffer is by violating the function's preconditions. For example, it

``




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


[clang] [CXX Safe Buffer] Update the safe buffer attribute documentation (PR #135087)

2025-04-09 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak created 
https://github.com/llvm/llvm-project/pull/135087

Update the documentation for the unsafe_buffer_usage attribute to capture the 
new behavior introduced by https://github.com/llvm/llvm-project/pull/125671

>From c3fbfd791d0c2f6d9ed0825fd2a043d3319da058 Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Wed, 9 Apr 2025 14:31:06 -0700
Subject: [PATCH] Update the documentation for the unsafe_buffer_usage
 attribute to capture the new beahvior introduced by
 https://github.com/llvm/llvm-project/pull/125671

---
 clang/include/clang/Basic/AttrDocs.td | 8 +---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c8b371280e35d..1546d849f6856 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7517,9 +7517,11 @@ the field it is attached to, and it may also lead to 
emission of automatic fix-i
 hints which would help the user replace the use of unsafe functions(/fields) 
with safe
 alternatives, though the attribute can be used even when the fix can't be 
automated.
 
-* Attribute attached to functions: The attribute does not suppress
-  ``-Wunsafe-buffer-usage`` inside the function to which it is attached.
-  These warnings still need to be addressed.
+* Attribute attached to functions: The attribute suppresses all the
+  ``-Wunsafe-buffer-usage`` warnings inside the function to which it is 
attached, since
+  it is now classified as an unsafe function. The attribute must be placed 
judiciously
+  as there won't be any warning for unsafe operations within the function and 
this can
+  also cause it to mask new usafe operations introduced in the future.
 
   The attribute is warranted even if the only way a function can overflow
   the buffer is by violating the function's preconditions. For example, it

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


[clang] [llvm] [AArch64][SelectionDAG] Add CodeGen support for scalar FEAT_CPA (PR #105669)

2025-04-09 Thread Alexander Richardson via cfe-commits

arichardson wrote:

ping @rgwott. Any chance you will have time to update this PR and address the 
outstanding comments?

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


[clang] d47401e - [OpenACC] Start enforcing 'device_type' clause values

2025-04-09 Thread via cfe-commits

Author: erichkeane
Date: 2025-04-09T14:55:50-07:00
New Revision: d47401e376d458fb9bb4f4f9be0e07c0fdd7a52c

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

LOG: [OpenACC] Start enforcing 'device_type' clause values

Researching in prep of doing the implementation for lowering, I found
that the source of the valid identifiers list from flang is in the
frontend.  This patch adds the same list to the frontend, but does it as
a sema diagnostic, so we still parse it as an identifier/identifier-like
thing, but then diagnose it as invalid later.

Added: 
clang/test/SemaOpenACC/device_type_valid_values.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaOpenACCClause.cpp
clang/test/AST/ast-print-openacc-combined-construct.cpp
clang/test/AST/ast-print-openacc-compute-construct.cpp
clang/test/AST/ast-print-openacc-data-construct.cpp
clang/test/AST/ast-print-openacc-init-construct.cpp
clang/test/AST/ast-print-openacc-loop-construct.cpp
clang/test/AST/ast-print-openacc-routine-construct.cpp
clang/test/AST/ast-print-openacc-set-construct.cpp
clang/test/AST/ast-print-openacc-shutdown-construct.cpp
clang/test/AST/ast-print-openacc-update-construct.cpp
clang/test/ParserOpenACC/parse-clauses.c
clang/test/SemaOpenACC/combined-construct-device_type-ast.cpp
clang/test/SemaOpenACC/combined-construct-device_type-clause.c
clang/test/SemaOpenACC/combined-construct-device_type-clause.cpp
clang/test/SemaOpenACC/compute-construct-device_type-ast.cpp
clang/test/SemaOpenACC/compute-construct-device_type-clause.c
clang/test/SemaOpenACC/compute-construct-device_type-clause.cpp
clang/test/SemaOpenACC/data-construct-device_type-ast.cpp
clang/test/SemaOpenACC/data-construct-device_type-clause.c
clang/test/SemaOpenACC/init-construct-ast.cpp
clang/test/SemaOpenACC/init-construct.cpp
clang/test/SemaOpenACC/loop-construct-device_type-ast.cpp
clang/test/SemaOpenACC/loop-construct-device_type-clause.c
clang/test/SemaOpenACC/loop-construct-device_type-clause.cpp
clang/test/SemaOpenACC/routine-construct-ast.cpp
clang/test/SemaOpenACC/routine-construct-clauses.cpp
clang/test/SemaOpenACC/set-construct-ast.cpp
clang/test/SemaOpenACC/set-construct.cpp
clang/test/SemaOpenACC/shutdown-construct-ast.cpp
clang/test/SemaOpenACC/shutdown-construct.cpp
clang/test/SemaOpenACC/update-construct-ast.cpp
clang/test/SemaOpenACC/update-construct.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d17519d4c4155..fdf3f8816e746 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13061,6 +13061,8 @@ def err_acc_decl_for_routine
 : Error<"expected function or lambda declaration for 'routine' construct">;
 def err_acc_invalid_modifier
 : Error<"OpenACC '%0' modifier not valid on '%1' clause">;
+def err_acc_invalid_default_type
+: Error<"invalid value %0 in '%1' clause; valid values are %2">;
 
 // AMDGCN builtins diagnostics
 def err_amdgcn_load_lds_size_invalid_value : Error<"invalid size value">;

diff  --git a/clang/lib/Sema/SemaOpenACCClause.cpp 
b/clang/lib/Sema/SemaOpenACCClause.cpp
index 7d10c50d404d2..8aa0c52f0ce19 100644
--- a/clang/lib/Sema/SemaOpenACCClause.cpp
+++ b/clang/lib/Sema/SemaOpenACCClause.cpp
@@ -1338,13 +1338,50 @@ OpenACCClause 
*SemaOpenACCClauseVisitor::VisitDeviceTypeClause(
   checkAlreadyHasClauseOfKind(SemaRef, ExistingClauses, Clause))
 return nullptr;
 
-  // TODO OpenACC: Once we get enough of the CodeGen implemented that we have
-  // a source for the list of valid architectures, we need to warn on unknown
-  // identifiers here.
+  // The list of valid device_type values. Flang also has these hardcoded in
+  // openacc_parsers.cpp, as there does not seem to be a reliable backend
+  // source. The list below is sourced from Flang, though NVC++ supports only
+  // 'nvidia', 'host', 'multicore', and 'default'.
+  const std::array ValidValues{
+  "default", "nvidia", "acc_device_nvidia", "radeon", "host", "multicore"};
+  // As an optimization, we have a manually maintained list of valid values
+  // below, rather than trying to calculate from above. These should be kept in
+  // sync if/when the above list ever changes.
+  std::string ValidValuesString =
+  "'default', 'nvidia', 'acc_device_nvidia', 'radeon', 'host', 
'multicore'";
+
+  llvm::SmallVector Architectures{
+  Clause.getDeviceTypeArchitectures()};
+
+  // The parser has ensured that we either have a single entry of just '*'
+  // (represented by a nullptr IdentifierInfo), or a list.
+
+  bool Diagnosed = fals

[clang] [clang][index] Handle undefined function-like macros in single file parse mode (PR #135054)

2025-04-09 Thread Jan Svoboda via cfe-commits

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


[clang] [C11] Implement WG14 N1285 (temporary lifetimes) (PR #133472)

2025-04-09 Thread Eli Friedman via cfe-commits

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

LGTM

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


[clang] [C11] Implement WG14 N1285 (temporary lifetimes) (PR #133472)

2025-04-09 Thread Eli Friedman via cfe-commits


@@ -7653,8 +7653,11 @@ ExprResult Sema::TemporaryMaterializationConversion(Expr 
*E) {
   // In C++98, we don't want to implicitly create an xvalue.
   // FIXME: This means that AST consumers need to deal with "prvalues" that
   // denote materialized temporaries. Maybe we should add another ValueKind
-  // for "xvalue pretending to be a prvalue" for C++98 support.
-  if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
+  // for "xvalue pretending to be a prvalue" for C++98 support. C11 added the

efriedma-quic wrote:

Maybe reorganize this comment so the description of C11 rules isn't part of the 
"FIXME"?

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


[clang] [C11] Implement WG14 N1285 (temporary lifetimes) (PR #133472)

2025-04-09 Thread Eli Friedman via cfe-commits

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


[clang] 58b91d1 - [CIR][NFC] Upstream LValueBaseInfo handling (#134928)

2025-04-09 Thread via cfe-commits

Author: Andy Kaylor
Date: 2025-04-09T15:27:50-07:00
New Revision: 58b91d10a4c9dcd71ea0bcf6ff702a46dad147cb

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

LOG: [CIR][NFC] Upstream LValueBaseInfo handling (#134928)

Previous implementations that used the cir::LValue class omitted hanling
of the LValueBaseInfo class, which tracks information about the basis
for the LValue's alignment. As more code was upstreamed from the
incubator, we were accumulating technical debt by adding more places
where this wasn't handled correctly. This change puts the interfaces in
place to track this information.

The information being tracked isn't used yet, so no functional change is
intended. The tracking is being added now because it will become more
difficult to add it as more features are implemented.

Added: 


Modified: 
clang/include/clang/CIR/MissingFeatures.h
clang/lib/CIR/CodeGen/CIRGenDecl.cpp
clang/lib/CIR/CodeGen/CIRGenExpr.cpp
clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
clang/lib/CIR/CodeGen/CIRGenFunction.h
clang/lib/CIR/CodeGen/CIRGenModule.cpp
clang/lib/CIR/CodeGen/CIRGenModule.h
clang/lib/CIR/CodeGen/CIRGenValue.h

Removed: 




diff  --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index a180c19a64288..3188429ea3b1b 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -108,11 +108,11 @@ struct MissingFeatures {
   static bool cgFPOptionsRAII() { return false; }
   static bool metaDataNode() { return false; }
   static bool fastMathFlags() { return false; }
-  static bool lvalueBaseInfo() { return false; }
   static bool alignCXXRecordDecl() { return false; }
   static bool setNonGC() { return false; }
   static bool incrementProfileCounter() { return false; }
   static bool insertBuiltinUnpredictable() { return false; }
+  static bool objCGC() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }

diff  --git a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp 
b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
index d0eb648683e8c..b8e72f299acb6 100644
--- a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
@@ -146,7 +146,7 @@ void CIRGenFunction::emitAutoVarInit(
   // its removal/optimization to the CIR lowering.
   if (!constant || isa(init)) {
 initializeWhatIsTechnicallyUninitialized(addr);
-LValue lv = LValue::makeAddr(addr, type);
+LValue lv = makeAddrLValue(addr, type, AlignmentSource::Decl);
 emitExprAsInit(init, &d, lv);
 // In case lv has uses it means we indeed initialized something
 // out of it while trying to build the expression, mark it as such.
@@ -165,7 +165,7 @@ void CIRGenFunction::emitAutoVarInit(
   assert(typedConstant && "expected typed attribute");
   if (!emission.IsConstantAggregate) {
 // For simple scalar/complex initialization, store the value directly.
-LValue lv = LValue::makeAddr(addr, type);
+LValue lv = makeAddrLValue(addr, type);
 assert(init && "expected initializer");
 mlir::Location initLoc = getLoc(init->getSourceRange());
 // lv.setNonGC(true);

diff  --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 441d841bf41f1..4b6652ad0b9e6 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -28,7 +28,8 @@ using namespace cir;
 
 /// Given an expression of pointer type, try to
 /// derive a more accurate bound on the alignment of the pointer.
-Address CIRGenFunction::emitPointerWithAlignment(const Expr *expr) {
+Address CIRGenFunction::emitPointerWithAlignment(const Expr *expr,
+ LValueBaseInfo *baseInfo) {
   // We allow this with ObjC object pointers because of fragile ABIs.
   assert(expr->getType()->isPointerType() ||
  expr->getType()->isObjCObjectPointerType());
@@ -164,7 +165,8 @@ Address CIRGenFunction::emitPointerWithAlignment(const Expr 
*expr) {
 
   // Otherwise, use the alignment of the type.
   return makeNaturalAddressForPointer(
-  emitScalarExpr(expr), expr->getType()->getPointeeType(), CharUnits());
+  emitScalarExpr(expr), expr->getType()->getPointeeType(), CharUnits(),
+  /*forPointeeType=*/true, baseInfo);
 }
 
 void CIRGenFunction::emitStoreThroughLValue(RValue src, LValue dst,
@@ -300,7 +302,7 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr 
*e) {
   cgm.errorNYI(vd->getSourceRange(), "emitDeclRefLValue: static local");
 }
 
-return LValue::makeAddr(addr, ty);
+return makeAddrLValue(addr, ty, AlignmentSource::Type);
   }
 
   cgm.errorNYI(e->getSourceRange(), "emitDeclRefLValue: unhandled decl type");
@@ -338,9 +340,9 @@ LValue CIRGe

[clang] [clang] Implement CWG2803 and CWG2958 (PR #132779)

2025-04-09 Thread Vlad Serebrennikov via cfe-commits


@@ -6,6 +6,89 @@
 // RUN: %clang_cc1 -std=c++23 -pedantic-errors 
-verify=expected,since-cxx11,cxx11-23,since-cxx20,since-cxx23 %s
 // RUN: %clang_cc1 -std=c++2c -pedantic-errors 
-verify=expected,since-cxx11,since-cxx20,since-cxx23,since-cxx26 %s
 
+namespace cwg2803 { // cwg2803: 21
+
+int a[1], *p, *ap[1];
+
+void f1(void*);
+int f1(const volatile int* const&);
+int i1 = f1((int*)0);
+
+void f2(const volatile void* const&);
+int f2(void*);
+int i2 = f2((int*)0);
+
+void f3(const volatile int*);
+int f3(const int*);
+int i3 = f3((int*)0);
+
+void f4(const volatile int* const&);
+int f4(const int* const volatile&);
+int i4 = f4(p);
+
+void f5(const int* const volatile&);
+int f5(const int* const&);
+int i5 = f5(p);
+
+void f6(const volatile int* const (&)[1]);
+int f6(const int* const volatile (&)[1]);
+int i6 = f6(ap);
+
+void f7(const int* const volatile (&)[1]);
+int f7(const int* const (&)[1]);
+int i7 = f7(ap);
+
+int f8(const int* const (&)[]);
+int f8(const volatile int* const (&)[1]);
+int i8 = f8(ap);
+// since-cxx20-error@-1 {{call to 'f8' is ambiguous}}
+//   since-cxx20-note@-4 {{candidate function}}
+//   since-cxx20-note@-4 {{candidate function}}
+
+void f9(const volatile int* const (&)[]);
+int f9(const int* const volatile (&)[1]);
+int i9 = f9(ap);
+
+void f10(int (&)[]);
+int f10(int (&)[1]);
+int i10 = f10(a);
+
+int f11(int (&)[]);
+int f11(const int (&)[1]);
+int i11 = f11(a);
+// since-cxx20-error@-1 {{call to 'f11' is ambiguous}}
+//   since-cxx20-note@-4 {{candidate function}}
+//   since-cxx20-note@-4 {{candidate function}}
+
+int f12(const int (&)[]);
+int f12(volatile int (&)[1]);
+int i12 = f12(a);
+// since-cxx20-error@-1 {{call to 'f12' is ambiguous}}
+//   since-cxx20-note@-4 {{candidate function}}
+//   since-cxx20-note@-4 {{candidate function}}
+
+#if __cplusplus >= 201103L
+void f13(const int* const&&);
+int f13(int* const&);
+int i13 = f13((int*)0);
+
+void f14(const int* const&);
+int f14(const volatile int* const volatile&&);
+int i14 = f14((int*)0);

Endilll wrote:

Oh, I missed that you're using rvalue references there. Sorry for that. Can you 
revert the changes you made?
As a side note, extension warnings are always a red flag in conformance tests.

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


[clang] [CIR] Upstream support for cir.get_global (PR #135095)

2025-04-09 Thread Andy Kaylor via cfe-commits

andykaylor wrote:

@mmha 

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


[clang] [llvm] [AArch64][SVE] Instcombine ptrue(all) to splat(i1) (PR #135016)

2025-04-09 Thread Paul Walker via cfe-commits

https://github.com/paulwalker-arm commented:

I'll take a closer look later but here are some stylistic things to streamline 
the patch a little.

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


[clang] [CIR][NFC] Upstream LValueBaseInfo handling (PR #134928)

2025-04-09 Thread Andy Kaylor via cfe-commits

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


[clang] [OpenACC][CIR] Implement 'data' construct lowering (PR #135038)

2025-04-09 Thread Valentin Clement バレンタイン クレメン via cfe-commits

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

LGTM from the OpenACC dialect point of view. 

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


[clang] [llvm] [DirectX] Implement UseNativeLowPrecision shader flag analysis (PR #134288)

2025-04-09 Thread Finn Plummer via cfe-commits


@@ -0,0 +1,45 @@
+; RUN: opt -S --passes="print-dx-shader-flags" 2>&1 %s | FileCheck %s
+; RUN: llc %s --filetype=obj -o - | obj2yaml | FileCheck %s --check-prefix=DXC
+
+target triple = "dxil-pc-shadermodel6.7-library"
+
+;CHECK: ; Combined Shader Flags for Module
+;CHECK-NEXT: ; Shader Flags Value: 0x00800020
+;CHECK-NEXT: ;
+;CHECK-NEXT: ; Note: shader requires additional functionality:
+;CHECK-NEXT: ; Note: extra DXIL module flags:
+;CHECK-NEXT: ;   D3D11_1_SB_GLOBAL_FLAG_ENABLE_MINIMUM_PRECISION
+;CHECK-NEXT: ;   Native 16bit types enabled
+;CHECK-NEXT: ;
+;CHECK-NEXT: ; Shader Flags for Module Functions
+
+;CHECK-LABEL: ; Function add_i16 : 0x00800020
+define i16 @add_i16(i16 %a, i16 %b) #0 {
+  %sum = add i16 %a, %b
+  ret i16 %sum
+}
+
+; NOTE: The flag for native low precision is set for every function in the
+; module regardless of whether or not the function uses low precision data
+; types. This matches the behavior in DXC
+;CHECK-LABEL: ; Function add_i32 : 0x0080
+define i32 @add_i32(i32 %a, i32 %b) #0 {
+  %sum = add i32 %a, %b
+  ret i32 %sum
+}
+
+;CHECK-LABEL: ; Function add_half : 0x00800020
+define half @add_half(half %a, half %b) #0 {
+  %sum = fadd half %a, %b
+  ret half %sum
+}
+
+attributes #0 = { convergent norecurse nounwind "hlsl.export" }
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 1, !"dx.nativelowprec", i32 1}
+
+; DXC: - Name:SFI0
+; DXC-NEXT: Size:8
+; DXC-NOT: Flags:
+; DXC: ...

inbelic wrote:

What is this testing?

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


[clang] [clang] fix NestedNameSpecifier dependency calculation (PR #135067)

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

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


[clang] 154507c - [clang] fix NestedNameSpecifier dependency calculation (#135067)

2025-04-09 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2025-04-09T19:44:40-03:00
New Revision: 154507cf403e1859b9a81fa76af406e8489daa4b

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

LOG: [clang] fix NestedNameSpecifier dependency calculation (#135067)

A NestedNameSpecifier of TypeSpec kind can be non-dependent even if its
prefix is dependent, when for example the prefix is an injected class
type but the type itself is a simple alias to a non-dependent type.

This issue was a bit hard to observe because if it is an alias to a
class type, then we (for some unknown reason) ignored that the NNS was
dependent in the first place, which wouldn't happen with an enum type.

This could have been a workaround for previous dependency bugs, and is
not relevant anymore for any of the test cases in the tree, so this
patch also removes that.

The other kinds of dependencies are still relevant. If the prefix
contains an unexpanded pack, then this NNS is still unexpanded, and
likewise for errors.

This fixes a regression reported here:
https://github.com/llvm/llvm-project/pull/133610#issuecomment-2787909829
which was introduced by https://github.com/llvm/llvm-project/pull/133610

There are no release notes since the regression was never released.

Added: 


Modified: 
clang/lib/AST/NestedNameSpecifier.cpp
clang/lib/Sema/SemaCXXScopeSpec.cpp
clang/test/SemaTemplate/dependent-names.cpp

Removed: 




diff  --git a/clang/lib/AST/NestedNameSpecifier.cpp 
b/clang/lib/AST/NestedNameSpecifier.cpp
index 51aa2d69d0f0d..bd0fe36d781da 100644
--- a/clang/lib/AST/NestedNameSpecifier.cpp
+++ b/clang/lib/AST/NestedNameSpecifier.cpp
@@ -221,7 +221,8 @@ NestedNameSpecifierDependence 
NestedNameSpecifier::getDependence() const {
 NestedNameSpecifierDependence Dep =
 toNestedNameSpecifierDependendence(getAsType()->getDependence());
 if (NestedNameSpecifier *Prefix = getPrefix())
-  Dep |= Prefix->getDependence();
+  Dep |=
+  Prefix->getDependence() & ~NestedNameSpecifierDependence::Dependent;
 return Dep;
   }
   }

diff  --git a/clang/lib/Sema/SemaCXXScopeSpec.cpp 
b/clang/lib/Sema/SemaCXXScopeSpec.cpp
index ea7936b0e5b8f..68ee006c6cf00 100644
--- a/clang/lib/Sema/SemaCXXScopeSpec.cpp
+++ b/clang/lib/Sema/SemaCXXScopeSpec.cpp
@@ -31,8 +31,7 @@ static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
   const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
   if (const RecordType *RecordTy = dyn_cast(Ty)) {
 CXXRecordDecl *Record = cast(RecordTy->getDecl());
-if (!Record->isDependentContext() ||
-Record->isCurrentInstantiation(CurContext))
+if (Record->isCurrentInstantiation(CurContext))
   return Record;
 
 return nullptr;

diff  --git a/clang/test/SemaTemplate/dependent-names.cpp 
b/clang/test/SemaTemplate/dependent-names.cpp
index 538abde3eddd5..54ce3760d2d01 100644
--- a/clang/test/SemaTemplate/dependent-names.cpp
+++ b/clang/test/SemaTemplate/dependent-names.cpp
@@ -467,3 +467,17 @@ namespace TransformDependentTemplates {
 void f(Arg);
   };
 } // namespace TransformDependentTemplates
+
+namespace TransformNestedName {
+  enum class S { kA };
+
+  template  struct N {
+using State = S;
+template  = 0>
+void F();
+  };
+
+  template 
+  template ::State::kA>>
+  inline void N::F() {}
+} // namespace TransformNestedName



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


[clang] [CXX Safe Buffer] Update the documentation for unsafe_buffer_usage attribute (PR #135087)

2025-04-09 Thread Malavika Samak via cfe-commits

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


[clang] [llvm] [DirectX] Implement Shader Flags Analysis for ResMayNotAlias (PR #131070)

2025-04-09 Thread Deric C. via cfe-commits

https://github.com/Icohedron updated 
https://github.com/llvm/llvm-project/pull/131070

>From 81196e016dbf1209637dd13315efff7eac461d42 Mon Sep 17 00:00:00 2001
From: Icohedron 
Date: Fri, 14 Mar 2025 00:24:26 +
Subject: [PATCH 01/10] Implement ResMayNotAlias DXIL shader flag analysis

---
 clang/include/clang/Basic/CodeGenOptions.def  |  3 ++
 clang/include/clang/Driver/Options.td |  5 +++
 clang/lib/CodeGen/CGHLSLRuntime.cpp   |  3 ++
 clang/lib/Driver/ToolChains/Clang.cpp |  1 +
 clang/test/CodeGenHLSL/res-may-alias.hlsl |  7 +++
 llvm/lib/Target/DirectX/DXILShaderFlags.cpp   | 43 ---
 llvm/lib/Target/DirectX/DXILShaderFlags.h |  9 +++-
 .../DirectX/ShaderFlags/res-may-alias-0.ll| 39 +
 .../DirectX/ShaderFlags/res-may-alias-1.ll| 37 
 .../res-may-not-alias-shadermodel6.7.ll   | 33 ++
 .../res-may-not-alias-shadermodel6.8.ll   | 33 ++
 .../typed-uav-load-additional-formats.ll  |  9 ++--
 12 files changed, 210 insertions(+), 12 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/res-may-alias.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-0.ll
 create mode 100644 llvm/test/CodeGen/DirectX/ShaderFlags/res-may-alias-1.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.7.ll
 create mode 100644 
llvm/test/CodeGen/DirectX/ShaderFlags/res-may-not-alias-shadermodel6.8.ll

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index a7f5f1abbb825..a436c0ec98d5b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -476,6 +476,9 @@ CODEGENOPT(ImportCallOptimization, 1, 0)
 /// (BlocksRuntime) on Windows.
 CODEGENOPT(StaticClosure, 1, 0)
 
+/// Assume that UAVs/SRVs may alias
+CODEGENOPT(ResMayAlias, 1, 0)
+
 /// FIXME: Make DebugOptions its own top-level .def file.
 #include "DebugOptions.def"
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 66ae8f1c7f064..9c5fd2354f95e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -9043,6 +9043,11 @@ def dxil_validator_version : Option<["/", "-"], 
"validator-version", KIND_SEPARA
   HelpText<"Override validator version for module. Format: ;"
"Default: DXIL.dll version or current internal version">,
   MarshallingInfoString, "\"1.8\"">;
+def res_may_alias : Option<["/", "-"], "res-may-alias", KIND_FLAG>,
+  Group, Flags<[HelpHidden]>,
+  Visibility<[DXCOption, ClangOption, CC1Option]>,
+  HelpText<"Assume that UAVs/SRVs may alias">,
+  MarshallingInfoFlag>;
 def target_profile : DXCJoinedOrSeparate<"T">, MetaVarName<"">,
   HelpText<"Set target profile">,
   Values<"ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7,"
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 5916fa6183a27..6fd8bc295e8ca 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -283,10 +283,13 @@ void CGHLSLRuntime::addHLSLBufferLayoutType(const 
RecordType *StructType,
 
 void CGHLSLRuntime::finishCodeGen() {
   auto &TargetOpts = CGM.getTarget().getTargetOpts();
+  auto &CodeGenOpts = CGM.getCodeGenOpts();
   llvm::Module &M = CGM.getModule();
   Triple T(M.getTargetTriple());
   if (T.getArch() == Triple::ArchType::dxil)
 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
+  if (CodeGenOpts.ResMayAlias)
+M.setModuleFlag(llvm::Module::ModFlagBehavior::Error, "dx.resmayalias", 1);
 
   generateGlobalCtorDtorCalls();
 }
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index fe172d923ac07..9be3939641cfc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3959,6 +3959,7 @@ static void RenderOpenCLOptions(const ArgList &Args, 
ArgStringList &CmdArgs,
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
   const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_res_may_alias,
  options::OPT_D,
  options::OPT_I,
  options::OPT_O,
diff --git a/clang/test/CodeGenHLSL/res-may-alias.hlsl 
b/clang/test/CodeGenHLSL/res-may-alias.hlsl
new file mode 100644
index 0..53ee8ee4935d8
--- /dev/null
+++ b/clang/test/CodeGenHLSL/res-may-alias.hlsl
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -res-may-alias -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disable-llvm-passes -o - %s | 
FileCheck %s --check-prefix=FLAG
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.3-library -emit-llvm -disabl

[clang-tools-extra] [clang-doc][NFC] refactor out file helpers (PR #134298)

2025-04-09 Thread Daniel Thornburgh via cfe-commits

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


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


[clang] [CIR] Upstream ArraySubscriptExpr for fixed size array (PR #134536)

2025-04-09 Thread Andy Kaylor via cfe-commits


@@ -390,6 +391,148 @@ LValue CIRGenFunction::emitUnaryOpLValue(const 
UnaryOperator *e) {
   llvm_unreachable("Unknown unary operator kind!");
 }
 
+/// If the specified expr is a simple decay from an array to pointer,
+/// return the array subexpression.
+/// FIXME: this could be abstracted into a common AST helper.
+static const Expr *getSimpleArrayDecayOperand(const Expr *e) {
+  // If this isn't just an array->pointer decay, bail out.
+  const auto *castExpr = dyn_cast(e);
+  if (!castExpr || castExpr->getCastKind() != CK_ArrayToPointerDecay)
+return nullptr;
+
+  // If this is a decay from variable width array, bail out.
+  const Expr *subExpr = castExpr->getSubExpr();
+  if (subExpr->getType()->isVariableArrayType())
+return nullptr;
+
+  return subExpr;
+}
+
+static mlir::IntegerAttr getConstantIndexOrNull(mlir::Value idx) {
+  // TODO(cir): should we consider using MLIRs IndexType instead of 
IntegerAttr?
+  if (auto constantOp = dyn_cast(idx.getDefiningOp()))
+return mlir::dyn_cast(constantOp.getValue());

andykaylor wrote:

If I understand correctly, cgf.isInPreservedAIRegion will never be true until 
we support the associated builtin function (`__builtin_preserve_access_index`), 
which isn't supported yet in the incubator and isn't a high priority and might 
not be relevant to CIR at all. I don't see any reason to upstream any of that 
yet.

But you're right that the check in emitArraySubscriptPtr is wrong as it 
currently appears in this PR. It appears that there is no reason to be checking 
for a constant index as we are there and we should be unconditionally calling 
the code in the true case. If you can support a variable index with no other 
changes, go ahead. Otherwise, leave it for a subsequent patch.

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


[clang] [HLSL] Implement the `lit` intrinsic (PR #134171)

2025-04-09 Thread Farzon Lotfi via cfe-commits

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


[clang] [CIR] Upstream support for cir.get_global (PR #135095)

2025-04-09 Thread Andy Kaylor via cfe-commits

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

This adds basic support for referencing global variables from within functions 
via the cir.get_global operation.

>From 43f2d5e73037559055dcbe65d8871c05c532d9f0 Mon Sep 17 00:00:00 2001
From: Andy Kaylor 
Date: Wed, 9 Apr 2025 14:25:35 -0700
Subject: [PATCH] [CIR] Upstream support for cir.get_global

This adds basic support for referencing global variables from within
functions via the cir.get_global operation.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  31 ++
 clang/include/clang/CIR/MissingFeatures.h |   5 +
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp  |  41 ++-
 clang/lib/CIR/CodeGen/CIRGenModule.cpp| 100 ++
 clang/lib/CIR/CodeGen/CIRGenModule.h  |  25 +
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp   |  35 ++
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp |  21 
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  10 ++
 clang/test/CIR/CodeGen/basic.c|  25 +
 9 files changed, 291 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index ce6f6c70189d9..000eb10e5c4ca 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -1279,6 +1279,37 @@ def GlobalOp : CIR_Op<"global"> {
   let hasVerifier = 1;
 }
 
+//===--===//
+// GetGlobalOp
+//===--===//
+
+def GetGlobalOp : CIR_Op<"get_global",
+[Pure, DeclareOpInterfaceMethods]> {
+  let summary = "Get the address of a global variable";
+  let description = [{
+The `cir.get_global` operation retrieves the address pointing to a
+named global variable. If the global variable is marked constant, writing
+to the resulting address (such as through a `cir.store` operation) is
+undefined. Resulting type must always be a `!cir.ptr<...>` type with the
+same address space as the global variable.
+
+Example:
+```mlir
+%x = cir.get_global @gv : !cir.ptr
+```
+  }];
+
+  let arguments = (ins FlatSymbolRefAttr:$name);
+  let results = (outs Res:$addr);
+
+  let assemblyFormat = [{
+$name `:` qualified(type($addr)) attr-dict
+  }];
+
+  // `GetGlobalOp` is fully verified by its traits.
+  let hasVerifier = 0;
+}
+
 
//===--===//
 // FuncOp
 
//===--===//
diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 3188429ea3b1b..70ecb50a93e1d 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -35,6 +35,7 @@ struct MissingFeatures {
   static bool opGlobalThreadLocal() { return false; }
   static bool opGlobalConstant() { return false; }
   static bool opGlobalAlignment() { return false; }
+  static bool opGlobalWeakRef() { return false; }
 
   static bool supportIFuncAttr() { return false; }
   static bool supportVisibility() { return false; }
@@ -113,6 +114,10 @@ struct MissingFeatures {
   static bool incrementProfileCounter() { return false; }
   static bool insertBuiltinUnpredictable() { return false; }
   static bool objCGC() { return false; }
+  static bool setObjCGCLValueClass() { return false; }
+  static bool mangledNames() { return false; }
+  static bool setDLLStorageClass() { return false; }
+  static bool openMP() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 4b6652ad0b9e6..de76f5e4dd4d7 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -183,6 +183,43 @@ void CIRGenFunction::emitStoreThroughLValue(RValue src, 
LValue dst,
   emitStoreOfScalar(src.getScalarVal(), dst, isInit);
 }
 
+static LValue emitGlobalVarDeclLValue(CIRGenFunction &cgf, const Expr *e,
+  const VarDecl *vd) {
+  QualType T = e->getType();
+
+  // If it's thread_local, emit a call to its wrapper function instead.
+  assert(!cir::MissingFeatures::opGlobalThreadLocal());
+  if (vd->getTLSKind() == VarDecl::TLS_Dynamic)
+cgf.cgm.errorNYI(e->getSourceRange(),
+ "emitGlobalVarDeclLValue: thread_local variable");
+
+  // Check if the variable is marked as declare target with link clause in
+  // device codegen.
+  if (cgf.getLangOpts().OpenMP)
+cgf.cgm.errorNYI(e->getSourceRange(), "emitGlobalVarDeclLValue: OpenMP");
+
+  // Traditional LLVM codegen handles thread local separately, CIR handles
+  // as part of getAddrOfGlobalVar.
+  mlir::Value v = cgf.cgm.getAddrOfGlobalVar(vd);
+
+  assert(!cir::MissingFeatures::addressSpace());
+  mli

[clang] [cfi][NFCI] Precommit tests to show nomerge functionality (PR #135104)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Thurston Dang (thurstond)


Changes

https://github.com/llvm/llvm-project/pull/120464 (and earlier CLs) added 
-fsanitize-merge functionality, which is intended to work for all "sanitizers". 
It is nearly correct for CFI.

This patch precommits some tests for CFI, to track the progress of future 
-fsanitize-merge fixes for CFI.

---

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


3 Files Affected:

- (added) clang/test/CodeGen/cfi-check-fail-nomerge.c (+232) 
- (added) clang/test/CodeGen/cfi-check-fail2-nomerge.c (+206) 
- (added) clang/test/CodeGenCXX/cfi-mfcall-nomerge.cpp (+131) 


``diff
diff --git a/clang/test/CodeGen/cfi-check-fail-nomerge.c 
b/clang/test/CodeGen/cfi-check-fail-nomerge.c
new file mode 100644
index 0..05ea8d8327904
--- /dev/null
+++ b/clang/test/CodeGen/cfi-check-fail-nomerge.c
@@ -0,0 +1,232 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --include-generated-funcs --version 5
+//
+// N.B. although the clang driver defaults to merge, clang_cc1 defaults to 
non-merge.
+// (This is similar to -fsanitize-recover, for which the default is also 
applied
+// at the driver level only.)
+// If optimization is disabled, merging is disabled (overrides 
-fsanitize-merge).
+
+// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux -fsanitize-cfi-cross-dso \
+// RUN: 
-fsanitize=cfi-icall,cfi-nvcall,cfi-vcall,cfi-unrelated-cast,cfi-derived-cast \
+// RUN: -fsanitize-trap=cfi-icall,cfi-nvcall \
+// RUN: -fsanitize-merge=cfi-icall,cfi-nvcall \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=MERGE
+
+// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux -fsanitize-cfi-cross-dso \
+// RUN: 
-fsanitize=cfi-icall,cfi-nvcall,cfi-vcall,cfi-unrelated-cast,cfi-derived-cast \
+// RUN: -fsanitize-trap=cfi-icall,cfi-nvcall \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=NO-MERGE
+
+// NOMERGE-LABEL: define dso_local void @caller(
+// NOMERGE-SAME: ptr noundef [[F:%.*]]) #[[ATTR0:[0-9]+]] !type 
[[META4:![0-9]+]] !type [[META5:![0-9]+]] !type [[META6:![0-9]+]] {
+// NOMERGE-NEXT:  [[ENTRY:.*:]]
+// NOMERGE-NEXT:[[F_ADDR:%.*]] = alloca ptr, align 8
+// NOMERGE-NEXT:store ptr [[F]], ptr [[F_ADDR]], align 8
+// NOMERGE-NEXT:[[TMP0:%.*]] = load ptr, ptr [[F_ADDR]], align 8
+// NOMERGE-NEXT:[[TMP1:%.*]] = call i1 @llvm.type.test(ptr [[TMP0]], 
metadata !"_ZTSFvvE"), !nosanitize [[META7:![0-9]+]]
+// NOMERGE-NEXT:br i1 [[TMP1]], label %[[CFI_CONT:.*]], label 
%[[CFI_SLOWPATH:.*]], !prof [[PROF8:![0-9]+]], !nosanitize [[META7]]
+// NOMERGE:   [[CFI_SLOWPATH]]:
+// NOMERGE-NEXT:call void @__cfi_slowpath(i64 9080559750644022485, ptr 
[[TMP0]]) #[[ATTR7:[0-9]+]], !nosanitize [[META7]]
+// NOMERGE-NEXT:br label %[[CFI_CONT]], !nosanitize [[META7]]
+// NOMERGE:   [[CFI_CONT]]:
+// NOMERGE-NEXT:call void [[TMP0]]()
+// NOMERGE-NEXT:ret void
+void caller(void (*f)(void)) {
+  f();
+}
+
+
+
+// MERGE-LABEL: define dso_local void @caller(
+// MERGE-SAME: ptr noundef [[F:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] 
!type [[META4:![0-9]+]] !type [[META5:![0-9]+]] !type [[META6:![0-9]+]] {
+// MERGE-NEXT:  [[ENTRY:.*:]]
+// MERGE-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.type.test(ptr [[F]], 
metadata !"_ZTSFvvE"), !nosanitize [[META7:![0-9]+]]
+// MERGE-NEXT:br i1 [[TMP0]], label %[[CFI_CONT:.*]], label 
%[[CFI_SLOWPATH:.*]], !prof [[PROF8:![0-9]+]], !nosanitize [[META7]]
+// MERGE:   [[CFI_SLOWPATH]]:
+// MERGE-NEXT:tail call void @__cfi_slowpath(i64 9080559750644022485, ptr 
[[F]]) #[[ATTR5:[0-9]+]], !nosanitize [[META7]]
+// MERGE-NEXT:br label %[[CFI_CONT]], !nosanitize [[META7]]
+// MERGE:   [[CFI_CONT]]:
+// MERGE-NEXT:tail call void [[F]]() #[[ATTR5]]
+// MERGE-NEXT:ret void
+//
+//
+// MERGE-LABEL: define weak_odr hidden void @__cfi_check_fail(
+// MERGE-SAME: ptr noundef [[TMP0:%.*]], ptr noundef [[TMP1:%.*]]) #[[ATTR0]] {
+// MERGE-NEXT:  [[ENTRY:.*:]]
+// MERGE-NEXT:[[DOTNOT:%.*]] = icmp eq ptr [[TMP0]], null, !nosanitize 
[[META7]]
+// MERGE-NEXT:br i1 [[DOTNOT]], label %[[TRAP:.*]], label %[[CONT:.*]], 
!prof [[PROF9:![0-9]+]], !nosanitize [[META7]]
+// MERGE:   [[TRAP]]:
+// MERGE-NEXT:tail call void @llvm.ubsantrap(i8 2) #[[ATTR6:[0-9]+]], 
!nosanitize [[META7]]
+// MERGE-NEXT:unreachable, !nosanitize [[META7]]
+// MERGE:   [[CONT]]:
+// MERGE-NEXT:[[TMP2:%.*]] = load i8, ptr [[TMP0]], align 4, !nosanitize 
[[META7]]
+// MERGE-NEXT:[[TMP3:%.*]] = tail call i1 @llvm.type.test(ptr [[TMP1]], 
metadata !"all-vtables"), !nosanitize [[META7]]
+// MERGE-NEXT:[[TMP4:%.*]] = zext i1 [[TMP3]] to i64, !nosanitize [[META7]]
+// MERGE-NEXT:switch i8 [[TMP2]], label %[[CONT8:.*]] [
+// MERGE-NEXT:  i8 0, label %[[HANDLER_CFI_CHECK_FAIL:.*]]
+// MERGE-NEXT:  i8 1, label %[[TR

[clang] [Clang] Make enums trivially equality comparable (PR #133587)

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

https://github.com/shafik commented:

The summary should not merely link to an issue but describe the problem as 
well. Two reasons:

1) for folks reading this in git log
2) The issue may not totally explain what is going on.

I actually did not get it at first b/c the issue talks about *char* and 
*std::byte* it took me a bit to realize oh yes *std::byte* is an enum. A good 
summary would have clarified this for reviewers.

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

2025-04-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andy Kaylor (andykaylor)


Changes

This change adds minimal support for structure types. To keep the initial 
change small, only incomplete declarations are being supported in this patch. 
More complete support will follow.

---

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


11 Files Affected:

- (modified) clang/include/clang/CIR/Dialect/IR/CIRTypes.h (+4) 
- (modified) clang/include/clang/CIR/Dialect/IR/CIRTypes.td (+114-1) 
- (added) clang/include/clang/CIR/Dialect/IR/CIRTypesDetails.h (+116) 
- (modified) clang/include/clang/CIR/MissingFeatures.h (+3) 
- (modified) clang/lib/CIR/CodeGen/CIRGenBuilder.h (+39) 
- (modified) clang/lib/CIR/CodeGen/CIRGenModule.cpp (+4) 
- (modified) clang/lib/CIR/CodeGen/CIRGenTypes.cpp (+75-2) 
- (modified) clang/lib/CIR/CodeGen/CIRGenTypes.h (+8) 
- (modified) clang/lib/CIR/Dialect/IR/CIRTypes.cpp (+173-3) 
- (added) clang/test/CIR/CodeGen/struct.c (+13) 
- (added) clang/test/CIR/IR/struct.cir (+9) 


``diff
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.h 
b/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
index 7b0fcbc7cc98f..d2c407b2fd686 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.h
@@ -20,6 +20,10 @@
 
 namespace cir {
 
+namespace detail {
+struct StructTypeStorage;
+} // namespace detail
+
 bool isAnyFloatingPointType(mlir::Type t);
 bool isFPOrFPVectorTy(mlir::Type);
 
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td 
b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
index e285c0f28f113..bcdaf54bbd84f 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
@@ -400,13 +400,126 @@ def VoidPtr : Type<
   "cir::VoidType::get($_builder.getContext()))"> {
 }
 
+//===--===//
+// StructType
+//
+// The base type for all RecordDecls.
+//===--===//
+
+def CIR_StructType : CIR_Type<"Struct", "struct",
+[
+  DeclareTypeInterfaceMethods,
+  MutableType,
+]> {
+  let summary = "CIR struct type";
+  let description = [{
+Each unique clang::RecordDecl is mapped to a `cir.struct` and any object in
+C/C++ that has a struct type will have a `cir.struct` in CIR.
+
+There are three possible formats for this type:
+
+ - Identified and complete structs: unique name and a known body.
+ - Identified and incomplete structs: unique name and unknown body.
+ - Anonymous structs: no name and a known body.
+
+Identified structs are uniqued by their name, and anonymous structs are
+uniqued by their body. This means that two anonymous structs with the same
+body will be the same type, and two identified structs with the same name
+will be the same type. Attempting to build a struct with an existing name,
+but a different body will result in an error.
+
+A few examples:
+
+```mlir
+!complete = !cir.struct}>
+!incomplete = !cir.struct
+!anonymous = !cir.struct}>
+```
+
+Incomplete structs are mutable, meaning they can be later completed with a
+body automatically updating in place every type in the code that uses the
+incomplete struct. Mutability allows for recursive types to be represented,
+meaning the struct can have members that refer to itself. This is useful 
for
+representing recursive records and is implemented through a special syntax.
+In the example below, the `Node` struct has a member that is a pointer to a
+`Node` struct:
+
+```mlir
+!struct = !cir.struct>}>
+```
+  }];
+
+  let parameters = (ins
+OptionalArrayRefParameter<"mlir::Type">:$members,
+OptionalParameter<"mlir::StringAttr">:$name,
+"bool":$incomplete,
+"bool":$packed,
+"bool":$padded,
+"StructType::RecordKind":$kind
+  );
+
+  // StorageClass is defined in C++ for mutability.
+  let storageClass = "StructTypeStorage";
+  let genStorageClass = 0;
+
+  let skipDefaultBuilders = 1;
+  let genVerifyDecl = 1;
+
+  let builders = [
+// Create an identified and incomplete struct type.
+TypeBuilder<(ins
+  "mlir::StringAttr":$name,
+  "RecordKind":$kind
+), [{
+  return $_get($_ctxt, /*members=*/llvm::ArrayRef{}, name,
+ /*incomplete=*/true, /*packed=*/false,
+ /*padded=*/false, kind);
+}]>];
+
+  let extraClassDeclaration = [{
+using Base::verifyInvariants;
+
+enum RecordKind : uint32_t { Class, Union, Struct };
+
+bool isClass() const { return getKind() == RecordKind::Class; };
+bool isStruct() const { return getKind() == RecordKind::Struct; };
+bool isUnion() const { return getKind() == RecordKind::Union; };
+bool isComplete() const { return !isIncomplete()

[clang] [Clang] Handle default template arguments for alias CTAD guides (PR #134807)

2025-04-09 Thread Younan Zhang via cfe-commits


@@ -690,6 +690,23 @@ SmallVector 
TemplateParamsReferencedInTemplateArgumentList(
   SemaRef.MarkUsedTemplateParameters(
   DeducedArgs, TemplateParamsList->getDepth(), ReferencedTemplateParams);
 
+  auto MarkDefaultArgs = [&](auto *Param) {
+if (!Param || !Param->hasDefaultArgument())
+  return;
+SemaRef.MarkUsedTemplateParameters(
+Param->getDefaultArgument().getArgument(),
+TemplateParamsList->getDepth(), ReferencedTemplateParams);
+  };
+
+  for (unsigned Index = 0; Index < TemplateParamsList->size(); ++Index) {
+if (!ReferencedTemplateParams[Index])
+  continue;
+auto *Param = TemplateParamsList->getParam(Index);
+MarkDefaultArgs(dyn_cast(Param));
+MarkDefaultArgs(dyn_cast(Param));
+MarkDefaultArgs(dyn_cast(Param));
+  }
+

zyn0217 wrote:

> For example, it seems this will mark default arguments as used even if the 
> corresponding parameter has a deduced argument.

That might not be a big deal, because as long as the default parameter doesn't 
end up in the argument list of RHS, it shouldn't affect the template argument 
deduction running against on the synthesized deductions guides -- we don't need 
to CodeGen for deduction guides nor it has to be fully instantiated for all of 
its parameters, right?

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


[clang-tools-extra] [clang-doc][NFC] refactor out file helpers (PR #134298)

2025-04-09 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-x86_64-debian-dylib` 
running on `gribozavr4` while building `clang-tools-extra` at step 5 
"build-unified-tree".

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


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

```
Step 5 (build-unified-tree) failure: build (failure)
...
61.955 [8/2/7272] Linking CXX shared library lib/liblldb.so.21.0.0git
61.957 [7/2/7273] Creating library symlink lib/liblldb.so.21.0git lib/liblldb.so
61.961 [4/4/7274] Linking CXX static library lib/liblldbIntelMPX.a
62.083 [3/4/7275] Linking CXX shared library lib/liblldbIntelFeatures.so.21.0git
62.084 [2/4/7276] Linking CXX executable bin/lldb
62.084 [2/3/7277] Creating library symlink lib/liblldbIntelFeatures.so
62.107 [2/2/7278] Linking CXX executable bin/lldb-dap
63.114 [2/1/7279] Building CXX object 
tools/clang/tools/extra/clang-doc/CMakeFiles/obj.clangDoc.dir/HTMLGenerator.cpp.o
63.127 [1/1/7280] Linking CXX static library lib/libclangDoc.a
63.265 [0/1/7281] Linking CXX executable bin/clang-doc
FAILED: bin/clang-doc 
: && /usr/bin/clang++ -fPIC -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 -fdiagnostics-color 
-ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual 
-Wno-nested-anon-types -O3 -DNDEBUG -Wl,--gc-sections 
tools/clang/tools/extra/clang-doc/tool/CMakeFiles/clang-doc.dir/ClangDocMain.cpp.o
 -o bin/clang-doc  
-Wl,-rpath,"\$ORIGIN/../lib:/b/1/llvm-x86_64-debian-dylib/build/lib:"  
-lpthread  lib/libclangDoc.a  lib/libclang-cpp.so.21.0git  
lib/libLLVM.so.21.0git && :
lib/libclangDoc.a(HTMLGenerator.cpp.o):HTMLGenerator.cpp:function 
clang::doc::HTMLGenerator::createResources(clang::doc::ClangDocContext&): 
error: undefined reference to 'clang::doc::copyFile(llvm::StringRef, 
llvm::StringRef)'
lib/libclangDoc.a(HTMLGenerator.cpp.o):HTMLGenerator.cpp:function 
clang::doc::HTMLGenerator::createResources(clang::doc::ClangDocContext&): 
error: undefined reference to 'clang::doc::copyFile(llvm::StringRef, 
llvm::StringRef)'
lib/libclangDoc.a(HTMLGenerator.cpp.o):HTMLGenerator.cpp:function 
clang::doc::genFileHeadNodes(llvm::StringRef, llvm::StringRef, 
clang::doc::ClangDocContext const&): error: undefined reference to 
'clang::doc::computeRelativePath(llvm::StringRef, llvm::StringRef)'
lib/libclangDoc.a(HTMLGenerator.cpp.o):HTMLGenerator.cpp:function 
clang::doc::genFileHeadNodes(llvm::StringRef, llvm::StringRef, 
clang::doc::ClangDocContext const&): error: undefined reference to 
'clang::doc::computeRelativePath(llvm::StringRef, llvm::StringRef)'
lib/libclangDoc.a(HTMLGenerator.cpp.o):HTMLGenerator.cpp:function 
clang::doc::genFileHeadNodes(llvm::StringRef, llvm::StringRef, 
clang::doc::ClangDocContext const&): error: undefined reference to 
'clang::doc::computeRelativePath(llvm::StringRef, llvm::StringRef)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

```



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


[clang] [cfi][NFCI] Precommit tests to show nomerge functionality (PR #135104)

2025-04-09 Thread Vitaly Buka via cfe-commits

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


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


[clang] [OpenACC][CIR] Implement 'device_type' clause lowering for 'init'/'sh… (PR #135102)

2025-04-09 Thread Valentin Clement バレンタイン クレメン via cfe-commits


@@ -4,4 +4,17 @@ void acc_init(void) {
   // CHECK: cir.func @acc_init() {
 #pragma acc init
 // CHECK-NEXT: acc.init loc(#{{[a-zA-Z0-9]+}}){{$}}
+
+#pragma acc init device_type(*)

clementval wrote:

What happens if you have this?

```
#pragma acc init device_type(*) device_type(nvidia)
```

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


[clang] [OpenACC][CIR] Implement 'device_type' clause lowering for 'init'/'sh… (PR #135102)

2025-04-09 Thread Valentin Clement バレンタイン クレメン via cfe-commits

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


[clang] [OpenACC][CIR] Implement 'device_type' clause lowering for 'init'/'sh… (PR #135102)

2025-04-09 Thread Valentin Clement バレンタイン クレメン via cfe-commits

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

LGTM. 



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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -400,13 +400,126 @@ def VoidPtr : Type<
   "cir::VoidType::get($_builder.getContext()))"> {
 }
 
+//===--===//
+// StructType
+//
+// The base type for all RecordDecls.
+//===--===//
+
+def CIR_StructType : CIR_Type<"Struct", "struct",
+[
+  DeclareTypeInterfaceMethods,
+  MutableType,
+]> {
+  let summary = "CIR struct type";
+  let description = [{
+Each unique clang::RecordDecl is mapped to a `cir.struct` and any object in
+C/C++ that has a struct type will have a `cir.struct` in CIR.
+
+There are three possible formats for this type:
+
+ - Identified and complete structs: unique name and a known body.
+ - Identified and incomplete structs: unique name and unknown body.
+ - Anonymous structs: no name and a known body.
+
+Identified structs are uniqued by their name, and anonymous structs are
+uniqued by their body. This means that two anonymous structs with the same
+body will be the same type, and two identified structs with the same name
+will be the same type. Attempting to build a struct with an existing name,
+but a different body will result in an error.
+
+A few examples:
+
+```mlir
+!complete = !cir.struct}>
+!incomplete = !cir.struct
+!anonymous = !cir.struct}>
+```
+
+Incomplete structs are mutable, meaning they can be later completed with a
+body automatically updating in place every type in the code that uses the
+incomplete struct. Mutability allows for recursive types to be represented,
+meaning the struct can have members that refer to itself. This is useful 
for
+representing recursive records and is implemented through a special syntax.
+In the example below, the `Node` struct has a member that is a pointer to a
+`Node` struct:
+
+```mlir
+!struct = !cir.structhttps://github.com/llvm/llvm-project/pull/135105
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -0,0 +1,116 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+//
+// This file contains implementation details, such as storage structures, of
+// CIR dialect types.
+//
+//===--===//
+#ifndef CIR_DIALECT_IR_CIRTYPESDETAILS_H
+#define CIR_DIALECT_IR_CIRTYPESDETAILS_H
+
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/Support/LogicalResult.h"
+#include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "llvm/ADT/Hashing.h"
+
+namespace cir {
+namespace detail {
+
+//===--===//
+// CIR StructTypeStorage
+//===--===//
+
+/// Type storage for CIR record types.
+struct StructTypeStorage : public mlir::TypeStorage {
+  struct KeyTy {
+llvm::ArrayRef members;
+mlir::StringAttr name;
+bool incomplete;
+bool packed;
+bool padded;
+StructType::RecordKind kind;
+
+KeyTy(llvm::ArrayRef members, mlir::StringAttr name,
+  bool incomplete, bool packed, bool padded,
+  StructType::RecordKind kind)
+: members(members), name(name), incomplete(incomplete), packed(packed),
+  padded(padded), kind(kind) {}
+  };
+
+  llvm::ArrayRef members;
+  mlir::StringAttr name;
+  bool incomplete;
+  bool packed;
+  bool padded;
+  StructType::RecordKind kind;
+
+  StructTypeStorage(llvm::ArrayRef members, mlir::StringAttr name,
+bool incomplete, bool packed, bool padded,
+StructType::RecordKind kind)
+  : members(members), name(name), incomplete(incomplete), packed(packed),
+padded(padded), kind(kind) {}

erichkeane wrote:

Can we assert that this is has a name if it is incomplete?

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o 
%t.cir
+// RUN: FileCheck --check-prefix=CIR --input-file=%t.cir %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o 
%t-cir.ll
+// RUN: FileCheck --check-prefix=LLVM --input-file=%t-cir.ll %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o %t.ll
+// RUN: FileCheck --check-prefix=OGCG --input-file=%t.ll %s
+
+// Declaration with an incomplete struct type.
+struct U *p;
+
+// CIR: cir.global external @p = #cir.ptr : !cir.ptr>

erichkeane wrote:

Could we/can we do a test not in the global scope, that is, a pointer to 
incomplete struct at function scope?  Or as function parameters?

Perhaps a 'union' test of both of these as well?

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -86,10 +86,80 @@ mlir::Type 
CIRGenTypes::convertFunctionTypeInternal(QualType qft) {
   return cir::FuncType::get(SmallVector{}, cgm.VoidTy);
 }
 
+// This is CIR's version of CodeGenTypes::addRecordTypeName. It isn't shareable
+// because CIR has different uniquing requirements.
+std::string CIRGenTypes::getRecordTypeName(const clang::RecordDecl *recordDecl,
+   StringRef suffix) {
+  llvm::SmallString<256> typeName;
+  llvm::raw_svector_ostream outStream(typeName);
+
+  PrintingPolicy policy = recordDecl->getASTContext().getPrintingPolicy();
+  policy.SuppressInlineNamespace = false;
+
+  if (recordDecl->getIdentifier()) {
+if (recordDecl->getDeclContext())

erichkeane wrote:

Er... what is going on here?  A record decl is ALWAYS going to have a 
DeclContext.

Is this some sort of attempt to differentiate global-namespace records?

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -400,13 +400,126 @@ def VoidPtr : Type<
   "cir::VoidType::get($_builder.getContext()))"> {
 }
 
+//===--===//
+// StructType
+//
+// The base type for all RecordDecls.
+//===--===//
+
+def CIR_StructType : CIR_Type<"Struct", "struct",
+[
+  DeclareTypeInterfaceMethods,
+  MutableType,
+]> {
+  let summary = "CIR struct type";
+  let description = [{
+Each unique clang::RecordDecl is mapped to a `cir.struct` and any object in

erichkeane wrote:

So this is actually a bit confusing/awkward.  A RecordDecl can represent a 
'union' as well as a 'class' or 'struct' type.  

So I question the name of it here.

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -37,6 +50,32 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 llvm_unreachable("Unsupported format for long double");
   }
 
+  /// Get a CIR record kind from a AST declaration tag.
+  cir::StructType::RecordKind getRecordKind(const clang::TagTypeKind kind) {
+switch (kind) {
+case clang::TagTypeKind::Struct:
+  return cir::StructType::Struct;
+case clang::TagTypeKind::Union:
+  return cir::StructType::Union;
+case clang::TagTypeKind::Class:
+  return cir::StructType::Class;
+case clang::TagTypeKind::Interface:
+  llvm_unreachable("interface records are NYI");
+case clang::TagTypeKind::Enum:
+  llvm_unreachable("enum records are NYI");

erichkeane wrote:

technically, enum is a tag-type/enum-type not a record-type.

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


[clang] 75cbb1f - [clang-format][NFC] Add FormatToken::is(tok::ObjCKeywordKind) (#134973)

2025-04-09 Thread via cfe-commits

Author: Owen Pan
Date: 2025-04-09T17:49:26-07:00
New Revision: 75cbb1f0fa734efb79c1a1233f1aba377dfad9e1

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

LOG: [clang-format][NFC] Add FormatToken::is(tok::ObjCKeywordKind) (#134973)

This allows simplification of code that checks if a token is an
Objective-C keyword.

Also, delete the following in
UnwrappedLineParser::parseStructuralElement():
- an else-after-break in the tok::at case
- the copypasted code in the tok::objc_autoreleasepool case

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 226d39f635676..eec5cc8632168 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3078,7 +3078,7 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
   for (const FormatToken *FormatTok = Line->First; FormatTok;
FormatTok = FormatTok->Next) {
 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
- (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
+ (FormatTok->isNot(tok::objc_not_keyword) ||
   FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
  tok::l_brace))) ||
 (FormatTok->Tok.isAnyIdentifier() &&

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index a5c2388bb143d..87e16397ad069 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -621,6 +621,9 @@ struct FormatToken {
   bool MacroParent = false;
 
   bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
+  bool is(tok::ObjCKeywordKind Kind) const {
+return Tok.getObjCKeywordID() == Kind;
+  }
   bool is(TokenType TT) const { return getType() == TT; }
   bool is(const IdentifierInfo *II) const {
 return II && II == Tok.getIdentifierInfo();
@@ -678,10 +681,6 @@ struct FormatToken {
 return isOneOf(tok::kw___attribute, tok::kw___declspec, TT_AttributeMacro);
   }
 
-  bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
-return Tok.isObjCAtKeyword(Kind);
-  }
-
   bool isAccessSpecifierKeyword() const {
 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
   }
@@ -707,11 +706,8 @@ struct FormatToken {
   [[nodiscard]] bool isTypeOrIdentifier(const LangOptions &LangOpts) const;
 
   bool isObjCAccessSpecifier() const {
-return is(tok::at) && Next &&
-   (Next->isObjCAtKeyword(tok::objc_public) ||
-Next->isObjCAtKeyword(tok::objc_protected) ||
-Next->isObjCAtKeyword(tok::objc_package) ||
-Next->isObjCAtKeyword(tok::objc_private));
+return Next && Next->isOneOf(tok::objc_public, tok::objc_protected,
+ tok::objc_package, tok::objc_private);
   }
 
   /// Returns whether \p Tok is ([{ or an opening < of a template or in

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index bd54470dcba37..a3aa69a1c17b4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -330,8 +330,8 @@ class AnnotatingParser {
 if (!Style.isVerilog()) {
   if (FormatToken *MaybeSel = OpeningParen.Previous) {
 // @selector( starts a selector.
-if (MaybeSel->isObjCAtKeyword(tok::objc_selector) &&
-MaybeSel->Previous && MaybeSel->Previous->is(tok::at)) {
+if (MaybeSel->is(tok::objc_selector) && MaybeSel->Previous &&
+MaybeSel->Previous->is(tok::at)) {
   StartsObjCMethodExpr = true;
 }
   }
@@ -4505,7 +4505,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
 return true;
   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
-  Left.Tok.getObjCKeywordID() == tok::objc_property) {
+  Left.is(tok::objc_property)) {
 return true;
   }
   if (Right.is(tok::hashhash))
@@ -4899,7 +4899,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 }
 return false;
   }
-  if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != 
tok::objc_not_keyword)
+  if (Left.is(tok::at) && Right.isNot(tok::objc_not_keyword))
 return false;
   if (Right.is(TT_UnaryOperator)) {
 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
@@ -6220,9 +6220,7 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine 
&Line,
   if (Right.is(TT_TemplateCloser))
 return Style.BreakBeforeTemplateCloser;
 
-  if (Left.is(tok::at)

[clang] [Clang] Make enums trivially equality comparable (PR #133587)

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


@@ -5240,9 +5249,13 @@ static bool 
HasNonDeletedDefaultedEqualityComparison(Sema &S,
 static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, 
SourceLocation KeyLoc) {
   QualType CanonicalType = Type.getCanonicalType();
   if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
-  CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
+  CanonicalType->isArrayType())
 return false;
 
+  if (CanonicalType->isEnumeralType())
+return EqualityComparisonIsDefaulted(

shafik wrote:

It looks like you are currently only testing if it is defaulted, we should be 
testing all code paths if possible to insure this does what we expect and to 
prevent future regressions.

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


[clang] [clang-format] Keep the space between `not` and a unary operator (PR #135035)

2025-04-09 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Keep the space between `not` and a unary operator (PR #135035)

2025-04-09 Thread Owen Pan via cfe-commits

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


[clang] [CIR] Upstream minimal support for structure types (PR #135105)

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


@@ -37,6 +50,32 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 llvm_unreachable("Unsupported format for long double");
   }
 
+  /// Get a CIR record kind from a AST declaration tag.
+  cir::StructType::RecordKind getRecordKind(const clang::TagTypeKind kind) {
+switch (kind) {
+case clang::TagTypeKind::Struct:
+  return cir::StructType::Struct;
+case clang::TagTypeKind::Union:
+  return cir::StructType::Union;
+case clang::TagTypeKind::Class:
+  return cir::StructType::Class;
+case clang::TagTypeKind::Interface:
+  llvm_unreachable("interface records are NYI");
+case clang::TagTypeKind::Enum:
+  llvm_unreachable("enum records are NYI");
+}
+  }
+
+  /// Get an incomplete CIR struct type.
+  cir::StructType getIncompleteStructTy(llvm::StringRef name,
+const clang::RecordDecl *rd) {
+const mlir::StringAttr nameAttr = getStringAttr(name);
+cir::StructType::RecordKind kind = cir::StructType::RecordKind::Struct;
+if (rd)

erichkeane wrote:

Should we/could we assert that `rd` represents an incomplete type?  Since the 
function name is asking for one?

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


  1   2   3   4   5   >