[clang] Fix extra parenthesis in diagnostic (PR #122055)

2025-01-08 Thread via cfe-commits

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


[clang] Fix extra parenthesis in diagnostic (PR #122055)

2025-01-08 Thread via cfe-commits

https://github.com/hstk30-hw approved this pull request.


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


[clang] de67ca1 - Fix extra parenthesis in diagnostic (#122055)

2025-01-08 Thread via cfe-commits

Author: Hubert Tong
Date: 2025-01-08T16:00:15+08:00
New Revision: de67ca12183787414869f8426a3bb65a6615e945

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

LOG: Fix extra parenthesis in diagnostic (#122055)

Following https://github.com/llvm/llvm-project/pull/120380,
`err_pack_expansion_length_conflict` has one close paren too many.

Remove the extra parenthesis.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 70f87a104a9821..ab2d6237c1cab8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5878,7 +5878,7 @@ def err_pack_expansion_without_parameter_packs : Error<
   "pack expansion does not contain any unexpanded parameter packs">;
 def err_pack_expansion_length_conflict : Error<
   "pack expansion contains parameter packs %0 and %1 that have 
diff erent "
-  "lengths (%2 vs. %select{|at least }3%4))">;
+  "lengths (%2 vs. %select{|at least }3%4)">;
 def err_pack_expansion_length_conflict_multilevel : Error<
   "pack expansion contains parameter pack %0 that has a 
diff erent "
   "length (%1 vs. %select{|at least }2%3) from outer parameter packs">;



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


[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)

2025-01-08 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1228,35 +1228,45 @@ bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
 NonTypeTemplateParmDecl *NewConstrainedParm,
 NonTypeTemplateParmDecl *OrigConstrainedParm,
 SourceLocation EllipsisLoc) {
-  if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() 
||
-  TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
-Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
- diag::err_unsupported_placeholder_constraint)
-<< NewConstrainedParm->getTypeSourceInfo()
-   ->getTypeLoc()
-   .getSourceRange();
-return true;
-  }
-  // FIXME: Concepts: This should be the type of the placeholder, but this is
-  // unclear in the wording right now.
-  DeclRefExpr *Ref =
-  BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
-   VK_PRValue, OrigConstrainedParm->getLocation());
-  if (!Ref)
-return true;
-  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
-  *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
-  TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
-  TL.getRAngleLoc(), BuildDecltypeType(Ref),
-  OrigConstrainedParm->getLocation(),
-  [&](TemplateArgumentListInfo &ConstraintArgs) {
-for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
-  ConstraintArgs.addArgument(TL.getArgLoc(I));
-  },
-  EllipsisLoc);
+  ExprResult ImmediatelyDeclaredConstraint = [&] {
+if (NewConstrainedParm->getType().getNonPackExpansionType() !=
+TL.getType() ||
+TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
+  Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
+   diag::err_unsupported_placeholder_constraint)
+  << NewConstrainedParm->getTypeSourceInfo()
+ ->getTypeLoc()
+ .getSourceRange();
+  return ExprResult();
+}
+
+// FIXME: Concepts: This should be the type of the placeholder, but this is
+// unclear in the wording right now.
+DeclRefExpr *Ref =
+BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
+ VK_PRValue, OrigConstrainedParm->getLocation());
+assert(Ref != nullptr && "Unexpected nullptr!");
+
+return formImmediatelyDeclaredConstraint(
+*this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
+TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(),
+TL.getLAngleLoc(), TL.getRAngleLoc(), BuildDecltypeType(Ref),
+OrigConstrainedParm->getLocation(),
+[&](TemplateArgumentListInfo &ConstraintArgs) {
+  for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
+ConstraintArgs.addArgument(TL.getArgLoc(I));
+},
+EllipsisLoc);
+  }();
+
   if (ImmediatelyDeclaredConstraint.isInvalid() ||
-  !ImmediatelyDeclaredConstraint.isUsable())
+  !ImmediatelyDeclaredConstraint.isUsable()) {
+NewConstrainedParm->setPlaceholderTypeConstraint(
+RecoveryExpr::Create(Context, OrigConstrainedParm->getType(),

alejandro-alvarez-sonarsource wrote:

The reasons for the `RecoveryExpr` is, indeed, like @erichkeane said, to be 
able to identify on the AST places where things were missing during parsing.

For this particular use case, the frontend (an analyzers) can easily tell apart 

1. There is no type constraint (`nullptr`)
2. There should be one but we could not parse it (`RecoveryExpr`)

The second point, IIUC [the 
documentation](https://clang.llvm.org/doxygen/classclang_1_1RecoveryExpr.html#details),
 is one of the reasons to use `RecoveryExpr`. Option 1 fixes the crash but 
loses information that can be used for better diagnosis.

> which was found during reduction of an unrelated bug

Not really, and I apologize if I have given this impression.
We have had few crashes and assertions when parsing `mp-units` with missing 
headers. This was not accidentally found because of #118288 (which is my other 
PR based on errors from this project).

>  I mostly say this because always initializing the placeholder pointer to 
> null would have been a much simpler fix, which would potentially cover other 
> instances of a similar bug.

I agree with you here, and the trailing object should probably be initialized 
to null on the constructor of `NonTypeTemplateParmDecl` to catch any other 
accidental uninitialized value. I am happy to do that too if no one objects.

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


[clang] [X86] Return illegal vectors in memory (PR #121944)

2025-01-08 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

This is a long existing problem and LLVM community doesn't make consensus about 
it, see https://reviews.llvm.org/D53919

My point is the case of returning illegal vectors is not well defined by psABI, 
and we have already warned this case in frontend. Considering the backward 
compatibility risk, I'd like to keep it as it.

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits


@@ -3115,7 +3115,19 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
 
   /// Returns the index of this field within its record,
   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
-  unsigned getFieldIndex() const;
+  unsigned getFieldIndex() const {
+const FieldDecl *C = getCanonicalDecl();
+if (C->CachedFieldIndex == 0)
+  C->setCachedFieldIndex();
+assert(C->CachedFieldIndex);

bricknerb wrote:

This should be insider the if above.

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits


@@ -3115,7 +3115,19 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
 
   /// Returns the index of this field within its record,
   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
-  unsigned getFieldIndex() const;
+  unsigned getFieldIndex() const {
+const FieldDecl *C = getCanonicalDecl();
+if (C->CachedFieldIndex == 0)
+  C->setCachedFieldIndex();
+assert(C->CachedFieldIndex);

bricknerb wrote:

Consider being consistent around comparing the index to zero explicitly or not 
(you do it explicitly on line 3120 and implicitly on line 3122).

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits


@@ -3115,7 +3115,19 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
 
   /// Returns the index of this field within its record,
   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
-  unsigned getFieldIndex() const;
+  unsigned getFieldIndex() const {
+const FieldDecl *C = getCanonicalDecl();
+if (C->CachedFieldIndex == 0)

bricknerb wrote:

The change here compared to the original implementation assumes 
getCanonicalDecl()->getCanonicalDecl() always equals to getCanonicalDecl().
This makes sense but just double checking that this is indeed the case.

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits


@@ -3115,7 +3115,19 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
 
   /// Returns the index of this field within its record,
   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
-  unsigned getFieldIndex() const;
+  unsigned getFieldIndex() const {
+const FieldDecl *C = getCanonicalDecl();

bricknerb wrote:

Consider keeping the original Canonical variable name.
https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly

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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits

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


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


[clang] Use range-based for to iterate over fields in record layout, NFC (PR #122029)

2025-01-08 Thread Boaz Brickner via cfe-commits

bricknerb wrote:

Thanks for doing this!
FWIW, I think splitting this to smaller PRs would be easier. For example:
1. `getFieldIndex()` inlining.
2. Passing fields instead of their indexes and iterate over fields.
3. Use `std::next()` instead of defining a `Next` variable.
4. Rename `isNoUniqueAddress` to `isNonVirtualBaseType`.

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


[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)

2025-01-08 Thread Younan Zhang via cfe-commits
Alejandro =?utf-8?q?Álvarez_Ayllón?=,
Alejandro =?utf-8?q?Álvarez_Ayllón?Message-ID:
In-Reply-To: 



@@ -1228,35 +1228,45 @@ bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
 NonTypeTemplateParmDecl *NewConstrainedParm,
 NonTypeTemplateParmDecl *OrigConstrainedParm,
 SourceLocation EllipsisLoc) {
-  if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() 
||
-  TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
-Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
- diag::err_unsupported_placeholder_constraint)
-<< NewConstrainedParm->getTypeSourceInfo()
-   ->getTypeLoc()
-   .getSourceRange();
-return true;
-  }
-  // FIXME: Concepts: This should be the type of the placeholder, but this is
-  // unclear in the wording right now.
-  DeclRefExpr *Ref =
-  BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
-   VK_PRValue, OrigConstrainedParm->getLocation());
-  if (!Ref)
-return true;
-  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
-  *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
-  TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
-  TL.getRAngleLoc(), BuildDecltypeType(Ref),
-  OrigConstrainedParm->getLocation(),
-  [&](TemplateArgumentListInfo &ConstraintArgs) {
-for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
-  ConstraintArgs.addArgument(TL.getArgLoc(I));
-  },
-  EllipsisLoc);
+  ExprResult ImmediatelyDeclaredConstraint = [&] {
+if (NewConstrainedParm->getType().getNonPackExpansionType() !=
+TL.getType() ||
+TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
+  Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
+   diag::err_unsupported_placeholder_constraint)
+  << NewConstrainedParm->getTypeSourceInfo()
+ ->getTypeLoc()
+ .getSourceRange();
+  return ExprResult();
+}
+
+// FIXME: Concepts: This should be the type of the placeholder, but this is
+// unclear in the wording right now.
+DeclRefExpr *Ref =
+BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
+ VK_PRValue, OrigConstrainedParm->getLocation());
+assert(Ref != nullptr && "Unexpected nullptr!");
+
+return formImmediatelyDeclaredConstraint(
+*this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
+TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(),
+TL.getLAngleLoc(), TL.getRAngleLoc(), BuildDecltypeType(Ref),
+OrigConstrainedParm->getLocation(),
+[&](TemplateArgumentListInfo &ConstraintArgs) {
+  for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
+ConstraintArgs.addArgument(TL.getArgLoc(I));
+},
+EllipsisLoc);
+  }();
+
   if (ImmediatelyDeclaredConstraint.isInvalid() ||
-  !ImmediatelyDeclaredConstraint.isUsable())
+  !ImmediatelyDeclaredConstraint.isUsable()) {
+NewConstrainedParm->setPlaceholderTypeConstraint(
+RecoveryExpr::Create(Context, OrigConstrainedParm->getType(),

zyn0217 wrote:

> and the trailing object should probably be initialized to null on the 
> constructor of NonTypeTemplateParmDecl to catch any other accidental 
> uninitialized value. 

We have a bit flag `TypeConstraintInitialized` in `TemplateTypeParmDecl` to 
represent a state of "having constraint attached but uninitialized (because of 
invalid constraint expression)". I think it'd be better to do the same thing in 
NonTypeTemplateParmDecl, or the reverse for consistency.

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


[clang-tools-extra] [clang-tidy] fix false positives when using name-independent variables after C++26 for bugprone-unused-local-non-trivial-variable (PR #121783)

2025-01-08 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.

LGTM

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


[clang] [llvm] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #122035)

2025-01-08 Thread Carlo Cabrera via cfe-commits

carlocab wrote:

> LLVM Buildbot has detected a new failure on builder `fuchsia-x86_64-linux` 
> running on `fuchsia-debian-64-us-central1-a-1` while building `clang,llvm` at 
> step 4 "annotate".
> 
> Full details are available at: 
> https://lab.llvm.org/buildbot/#/builders/11/builds/10651
> 
> 
> Here is the relevant piece of the build log for the 
> reference
> 
> ```
> Step 4 (annotate) failure: 'python 
> ../llvm-zorg/zorg/buildbot/builders/annotated/fuchsia-linux.py ...' (failure)
> ...
> [1015/1367] Linking CXX executable 
> unittests/DebugInfo/DWARF/DebugInfoDWARFTests
> [1016/1367] Running the Clang regression tests
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
>  note: using clang: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/clang
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/subst.py:126:
>  note: Did not find clang-repl in 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin:/var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
>  note: using ld.lld: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/ld.lld
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
>  note: using lld-link: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/lld-link
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
>  note: using ld64.lld: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/ld64.lld
> llvm-lit: 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
>  note: using wasm-ld: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/wasm-ld
> -- Testing: 21766 tests, 60 workers --
> Testing:  0.. 10.. 20.. 30.. 40..
> FAIL: Clang :: Driver/darwin-embedded-search-paths.c (10801 of 21766)
>  TEST 'Clang :: Driver/darwin-embedded-search-paths.c' 
> FAILED 
> Exit Code: 1
> 
> Command Output (stderr):
> --
> RUN: at line 6: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/clang -x 
> c -target arm64-apple-none-macho -isysroot 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  -### -c 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
>  2>&1  | 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/FileCheck
>  --check-prefixes=CC1,NO-CXX,ULI,CI,UI,NO-FW 
> -DSDKROOT=/var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
> + 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/FileCheck
>  --check-prefixes=CC1,NO-CXX,ULI,CI,UI,NO-FW 
> -DSDKROOT=/var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
> + /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/clang 
> -x c -target arm64-apple-none-macho -isysroot 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  -### -c 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
> RUN: at line 10: 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/clang -x 
> c++ -target arm64-apple-none-macho -isysroot 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  -### -c 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
>  2>&1  | 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/FileCheck
>  --check-prefixes=CC1,NO-CXX,ULI,CI,UI,NO-FW 
> -DSDKROOT=/var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
> + 
> /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/FileCheck
>  --check-prefixes=CC1,NO-CXX,ULI,CI,UI,NO-FW 
> -DSDKROOT=/var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/darwin-embedded-search-paths.c
> + /var/lib/buildbot/fuchsia-x86_64-linux/build/llvm-build-it8eyuar/bin/clang 
> -x c++ -target arm64-apple-none-macho -isysroot 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm-project/clang/test/Driver/Inputs/MacOSX15.1.sdk
>  -### -c 
> /var/lib/buildbot/fuchsia-x86_64-linux/llvm

[clang] [llvm] [Arm] Regenerate tests (NFC) (PR #121801)

2025-01-08 Thread David Green via cfe-commits

davemgreen wrote:

sroa would be ideal if it works, I know a number of test cases use it and it 
shouldn't update too often.

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


[clang] [Clang] Don't form a type constraint if the concept is invalid (PR #122065)

2025-01-08 Thread via cfe-commits

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


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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits


@@ -938,6 +938,37 @@ struct CounterCoverageMappingBuilder
 return Counter::getCounter(CounterMap[S]);
   }
 
+  struct BranchCounterPair {

chapuni wrote:

`BranchCounterPair` is a local type and only `getBranchCounterPair()` emits it 
for now. I think it'd be enough just to annotate members inside.

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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/112702

>From fc697f04fd6c9f3c217ce04e3f1dd082c1f1a705 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Wed, 16 Oct 2024 23:16:53 +0900
Subject: [PATCH 01/11] [Coverage] Introduce `getBranchCounterPair()`. NFC.

This aggregates the generation of branch counter pair as `ExecCnt` and
`SkipCnt`, to aggregate `CounterExpr::subtract`. At the moment:

- This change preserves the behavior of
  `llvm::EnableSingleByteCoverage`. Almost of SingleByteCoverage will
  be cleaned up by coming commits.

- `getBranchCounterPair()` is not called in
  `llvm::EnableSingleByteCoverage`. I will implement the new behavior
  of SingleByteCoverage in it.

- `IsCounterEqual(Out, Par)` is introduced instead of
  `Counter::operator==`. Tweaks would be required for the comparison
  for additional counters.

- Braces around `assert()` is intentional. I will add a statement there.

https://discourse.llvm.org/t/rfc-integrating-singlebytecoverage-with-branch-coverage/82492
---
 clang/lib/CodeGen/CoverageMappingGen.cpp | 177 +--
 1 file changed, 102 insertions(+), 75 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 07015834bc84f3..0bfad9cbcbe12b 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -941,6 +941,19 @@ struct CounterCoverageMappingBuilder
 return Counter::getCounter(CounterMap[S]);
   }
 
+  std::pair getBranchCounterPair(const Stmt *S,
+   Counter ParentCnt) {
+Counter ExecCnt = getRegionCounter(S);
+return {ExecCnt, Builder.subtract(ParentCnt, ExecCnt)};
+  }
+
+  bool IsCounterEqual(Counter OutCount, Counter ParentCount) {
+if (OutCount == ParentCount)
+  return true;
+
+return false;
+  }
+
   /// Push a region onto the stack.
   ///
   /// Returns the index on the stack where the region was pushed. This can be
@@ -1592,6 +1605,13 @@ struct CounterCoverageMappingBuilder
 llvm::EnableSingleByteCoverage
 ? getRegionCounter(S->getCond())
 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
+auto [ExecCount, ExitCount] =
+(llvm::EnableSingleByteCoverage
+ ? std::make_pair(getRegionCounter(S), Counter::getZero())
+ : getBranchCounterPair(S, CondCount));
+if (!llvm::EnableSingleByteCoverage) {
+  assert(ExecCount.isZero() || ExecCount == BodyCount);
+}
 propagateCounts(CondCount, S->getCond());
 adjustForOutOfOrderTraversal(getEnd(S));
 
@@ -1600,13 +1620,11 @@ struct CounterCoverageMappingBuilder
 if (Gap)
   fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
 
-Counter OutCount =
-llvm::EnableSingleByteCoverage
-? getRegionCounter(S)
-: addCounters(BC.BreakCount,
-  subtractCounters(CondCount, BodyCount));
+Counter OutCount = llvm::EnableSingleByteCoverage
+   ? getRegionCounter(S)
+   : addCounters(BC.BreakCount, ExitCount);
 
-if (OutCount != ParentCount) {
+if (!IsCounterEqual(OutCount, ParentCount)) {
   pushRegion(OutCount);
   GapRegionCounter = OutCount;
   if (BodyHasTerminateStmt)
@@ -1615,8 +1633,7 @@ struct CounterCoverageMappingBuilder
 
 // Create Branch Region around condition.
 if (!llvm::EnableSingleByteCoverage)
-  createBranchRegion(S->getCond(), BodyCount,
- subtractCounters(CondCount, BodyCount));
+  createBranchRegion(S->getCond(), BodyCount, ExitCount);
   }
 
   void VisitDoStmt(const DoStmt *S) {
@@ -1645,22 +1662,26 @@ struct CounterCoverageMappingBuilder
 Counter CondCount = llvm::EnableSingleByteCoverage
 ? getRegionCounter(S->getCond())
 : addCounters(BackedgeCount, BC.ContinueCount);
+auto [ExecCount, ExitCount] =
+(llvm::EnableSingleByteCoverage
+ ? std::make_pair(getRegionCounter(S), Counter::getZero())
+ : getBranchCounterPair(S, CondCount));
+if (!llvm::EnableSingleByteCoverage) {
+  assert(ExecCount.isZero() || ExecCount == BodyCount);
+}
 propagateCounts(CondCount, S->getCond());
 
-Counter OutCount =
-llvm::EnableSingleByteCoverage
-? getRegionCounter(S)
-: addCounters(BC.BreakCount,
-  subtractCounters(CondCount, BodyCount));
-if (OutCount != ParentCount) {
+Counter OutCount = llvm::EnableSingleByteCoverage
+   ? getRegionCounter(S)
+   : addCounters(BC.BreakCount, ExitCount);
+if (!IsCounterEqual(OutCount, ParentCount)) {
   pushRegion(OutCount);
   GapRegionCounter = OutCount;
 }
 
 // Create Branch Region around condition.
 if (!llvm::EnableSingleByteCoverage)
-  

[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits


@@ -939,8 +939,17 @@ struct CounterCoverageMappingBuilder
 Counter Skipped;
   };
 
-  BranchCounterPair getBranchCounterPair(const Stmt *S, Counter ParentCnt) {
+  BranchCounterPair
+  getBranchCounterPair(const Stmt *S, Counter ParentCnt,
+   std::optional SkipCntForOld = std::nullopt) {
 Counter ExecCnt = getRegionCounter(S);
+
+// The old behavior of SingleByte shouldn't emit Branches.
+if (llvm::EnableSingleByteCoverage) {
+  assert(SkipCntForOld);

chapuni wrote:

Done.

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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits


@@ -939,8 +939,17 @@ struct CounterCoverageMappingBuilder
 Counter Skipped;
   };
 
-  BranchCounterPair getBranchCounterPair(const Stmt *S, Counter ParentCnt) {
+  BranchCounterPair
+  getBranchCounterPair(const Stmt *S, Counter ParentCnt,
+   std::optional SkipCntForOld = std::nullopt) {

chapuni wrote:

Done.

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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits


@@ -938,6 +938,37 @@ struct CounterCoverageMappingBuilder
 return Counter::getCounter(CounterMap[S]);
   }
 
+  struct BranchCounterPair {
+Counter Executed;
+Counter Skipped;
+  };
+
+  BranchCounterPair getBranchCounterPair(const Stmt *S, Counter ParentCnt) {

chapuni wrote:

Done.

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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2025-01-08 Thread NAKAMURA Takumi via cfe-commits


@@ -939,8 +939,17 @@ struct CounterCoverageMappingBuilder
 Counter Skipped;
   };
 
-  BranchCounterPair getBranchCounterPair(const Stmt *S, Counter ParentCnt) {
+  BranchCounterPair
+  getBranchCounterPair(const Stmt *S, Counter ParentCnt,
+   std::optional SkipCntForOld = std::nullopt) {

chapuni wrote:

FYI, 
https://github.com/llvm/llvm-project/pull/113115/commits/0e2997d02e7c60c698364d6fad234e444bc92851

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


[clang] [Driver][SPIR-V] Use consistent tools to convert between text and binary form (PR #120266)

2025-01-08 Thread Sven van Haastregt via cfe-commits

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

Thanks for drawing this to my attention!

The output produced by llvm-spirv's `-to-text` is an internal textual format, 
intended for testing llvm-spirv only (@MrSidims please correct me if I'm 
wrong).  I don't think we should be exposing that format through the clang 
driver.

What is the use case that you're trying to solve?  Would it be possible to add 
a `spirv-as` invocation before passing textual SPIR-V back to llvm-spirv?  
Alternatively, perhaps we should teach llvm-spirv to be able to consume the 
conventional SPIRV-Tools textual format.  That would be a natural counterpart 
to llvm-spirv's `--spirv-tools-dis` option.

> Once we are using the SPIR-V backend we should be able to get rid of this.

With the current patch, I expect you'd still have the problem that llvm-spirv 
cannot consume the output produced by the SPIR-V backend?

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


[clang] [clang][CodeGen] `sret` args should always point to the `alloca` AS, so use that (PR #114062)

2025-01-08 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx commented:

> In this case I think just using the hardcoded 0 is less wrong than using the 
> "LangAS::Default". This just happens to work out correctly for the OpenCL 1.x 
> hack on amdgpu  

I don't have a strong preference / that makes sense-ish but I was actually 
leaning towards switching this to the AllocaAS, which I think is still safe and 
would do the RightThingTM.

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


[clang] [clang][CodeGen] `sret` args should always point to the `alloca` AS, so use that (PR #114062)

2025-01-08 Thread Alex Voicu via cfe-commits

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


[clang] [clang] Refine the temporay object member access filtering for GSL pointer (PR #122088)

2025-01-08 Thread Haojian Wu via cfe-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/122088

We currently have ad-hoc filtering logic for temporary object member access in 
`VisitGSLPointerArg`. This logic filters out more cases than it should, leading 
to false negatives. Furthermore, this location lacks sufficient context to 
implement a more accurate solution.  

This patch refines the filtering logic by moving it to the central filtering 
location, `analyzePathForGSLPointer`, consolidating the logic and avoiding 
scattered filtering across multiple places. As a result, the special handling 
for conditional operators (#120233) is no longer necessary.  

This change also resolves #120543.  



>From 8c4f9bcb00c56f564abf6cfa115854681b48f7d9 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 17 Dec 2024 14:28:00 +0100
Subject: [PATCH] [clang] Refine the temporay object member access filtering
 for GSL pointer.

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 42 +--
 clang/test/Sema/Inputs/lifetime-analysis.h|  2 +-
 .../Sema/warn-lifetime-analysis-nocfg.cpp | 28 +
 3 files changed, 58 insertions(+), 14 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7109de03cadd12..d0d05e4ed980d5 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -200,6 +200,7 @@ struct IndirectLocalPathEntry {
 LifetimeBoundCall,
 TemporaryCopy,
 LambdaCaptureInit,
+MemberExpr,
 GslReferenceInit,
 GslPointerInit,
 GslPointerAssignment,
@@ -578,19 +579,6 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 Path.pop_back();
   };
   auto VisitGSLPointerArg = [&](const FunctionDecl *Callee, Expr *Arg) {
-// We are not interested in the temporary base objects of gsl Pointers:
-//   Temp().ptr; // Here ptr might not dangle.
-if (isa(Arg->IgnoreImpCasts()))
-  return;
-// Avoid false positives when the object is constructed from a conditional
-// operator argument. A common case is:
-//   // 'ptr' might not be owned by the Owner object.
-//   std::string_view s = cond() ? Owner().ptr : sv;
-if (const auto *Cond =
-dyn_cast(Arg->IgnoreImpCasts());
-Cond && isPointerLikeType(Cond->getType()))
-  return;
-
 auto ReturnType = Callee->getReturnType();
 
 // Once we initialized a value with a non gsl-owner reference, it can no
@@ -710,6 +698,9 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
 Init = ILE->getInit(0);
 }
 
+if (MemberExpr *ME = dyn_cast(Init->IgnoreImpCasts()))
+  Path.push_back(
+  {IndirectLocalPathEntry::MemberExpr, ME, ME->getMemberDecl()});
 // Step over any subobject adjustments; we may have a materialized
 // temporary inside them.
 Init = const_cast(Init->skipRValueSubobjectAdjustments());
@@ -1103,6 +1094,8 @@ shouldLifetimeExtendThroughPath(const IndirectLocalPath 
&Path) {
   for (auto Elem : Path) {
 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
   return PathLifetimeKind::Extend;
+if (Elem.Kind == IndirectLocalPathEntry::MemberExpr)
+  continue;
 if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
   return PathLifetimeKind::NoExtend;
   }
@@ -1122,6 +1115,7 @@ static SourceRange nextPathEntryRange(const 
IndirectLocalPath &Path, unsigned I,
 case IndirectLocalPathEntry::GslPointerInit:
 case IndirectLocalPathEntry::GslPointerAssignment:
 case IndirectLocalPathEntry::ParenAggInit:
+case IndirectLocalPathEntry::MemberExpr:
   // These exist primarily to mark the path as not permitting or
   // supporting lifetime extension.
   break;
@@ -1151,6 +1145,7 @@ static bool pathOnlyHandlesGslPointer(const 
IndirectLocalPath &Path) {
 case IndirectLocalPathEntry::VarInit:
 case IndirectLocalPathEntry::AddressOf:
 case IndirectLocalPathEntry::LifetimeBoundCall:
+case IndirectLocalPathEntry::MemberExpr:
   continue;
 case IndirectLocalPathEntry::GslPointerInit:
 case IndirectLocalPathEntry::GslReferenceInit:
@@ -1184,6 +1179,26 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
   // At this point, Path represents a series of operations involving a
   // GSLPointer, either in the process of initialization or assignment.
 
+  // Process  temporary base objects for MemberExpr cases, e.g. Temp().field.
+  for (const auto &E : Path) {
+if (E.Kind == IndirectLocalPathEntry::MemberExpr) {
+  // Avoid interfering  with the local base object.
+  if (pathContainsInit(Path))
+return Abandon;
+
+  // We are not interested in the temporary base objects of gsl Pointers:
+  //   auto p1 = Temp().ptr; // Here p1 might not dangle.
+  // However, we want to diagnose for gsl owner fields:
+  //   auto p2 = Temp().owner; // Here p2 is dangling.
+  if (c

[clang] [clang] Refine the temporay object member access filtering for GSL pointer (PR #122088)

2025-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

We currently have ad-hoc filtering logic for temporary object member access in 
`VisitGSLPointerArg`. This logic filters out more cases than it should, leading 
to false negatives. Furthermore, this location lacks sufficient context to 
implement a more accurate solution.  

This patch refines the filtering logic by moving it to the central filtering 
location, `analyzePathForGSLPointer`, consolidating the logic and avoiding 
scattered filtering across multiple places. As a result, the special handling 
for conditional operators (#120233) is no longer necessary.  

This change also resolves #120543.  



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


3 Files Affected:

- (modified) clang/lib/Sema/CheckExprLifetime.cpp (+29-13) 
- (modified) clang/test/Sema/Inputs/lifetime-analysis.h (+1-1) 
- (modified) clang/test/Sema/warn-lifetime-analysis-nocfg.cpp (+28) 


``diff
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7109de03cadd12..d0d05e4ed980d5 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -200,6 +200,7 @@ struct IndirectLocalPathEntry {
 LifetimeBoundCall,
 TemporaryCopy,
 LambdaCaptureInit,
+MemberExpr,
 GslReferenceInit,
 GslPointerInit,
 GslPointerAssignment,
@@ -578,19 +579,6 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 Path.pop_back();
   };
   auto VisitGSLPointerArg = [&](const FunctionDecl *Callee, Expr *Arg) {
-// We are not interested in the temporary base objects of gsl Pointers:
-//   Temp().ptr; // Here ptr might not dangle.
-if (isa(Arg->IgnoreImpCasts()))
-  return;
-// Avoid false positives when the object is constructed from a conditional
-// operator argument. A common case is:
-//   // 'ptr' might not be owned by the Owner object.
-//   std::string_view s = cond() ? Owner().ptr : sv;
-if (const auto *Cond =
-dyn_cast(Arg->IgnoreImpCasts());
-Cond && isPointerLikeType(Cond->getType()))
-  return;
-
 auto ReturnType = Callee->getReturnType();
 
 // Once we initialized a value with a non gsl-owner reference, it can no
@@ -710,6 +698,9 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
 Init = ILE->getInit(0);
 }
 
+if (MemberExpr *ME = dyn_cast(Init->IgnoreImpCasts()))
+  Path.push_back(
+  {IndirectLocalPathEntry::MemberExpr, ME, ME->getMemberDecl()});
 // Step over any subobject adjustments; we may have a materialized
 // temporary inside them.
 Init = const_cast(Init->skipRValueSubobjectAdjustments());
@@ -1103,6 +1094,8 @@ shouldLifetimeExtendThroughPath(const IndirectLocalPath 
&Path) {
   for (auto Elem : Path) {
 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
   return PathLifetimeKind::Extend;
+if (Elem.Kind == IndirectLocalPathEntry::MemberExpr)
+  continue;
 if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
   return PathLifetimeKind::NoExtend;
   }
@@ -1122,6 +1115,7 @@ static SourceRange nextPathEntryRange(const 
IndirectLocalPath &Path, unsigned I,
 case IndirectLocalPathEntry::GslPointerInit:
 case IndirectLocalPathEntry::GslPointerAssignment:
 case IndirectLocalPathEntry::ParenAggInit:
+case IndirectLocalPathEntry::MemberExpr:
   // These exist primarily to mark the path as not permitting or
   // supporting lifetime extension.
   break;
@@ -1151,6 +1145,7 @@ static bool pathOnlyHandlesGslPointer(const 
IndirectLocalPath &Path) {
 case IndirectLocalPathEntry::VarInit:
 case IndirectLocalPathEntry::AddressOf:
 case IndirectLocalPathEntry::LifetimeBoundCall:
+case IndirectLocalPathEntry::MemberExpr:
   continue;
 case IndirectLocalPathEntry::GslPointerInit:
 case IndirectLocalPathEntry::GslReferenceInit:
@@ -1184,6 +1179,26 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
   // At this point, Path represents a series of operations involving a
   // GSLPointer, either in the process of initialization or assignment.
 
+  // Process  temporary base objects for MemberExpr cases, e.g. Temp().field.
+  for (const auto &E : Path) {
+if (E.Kind == IndirectLocalPathEntry::MemberExpr) {
+  // Avoid interfering  with the local base object.
+  if (pathContainsInit(Path))
+return Abandon;
+
+  // We are not interested in the temporary base objects of gsl Pointers:
+  //   auto p1 = Temp().ptr; // Here p1 might not dangle.
+  // However, we want to diagnose for gsl owner fields:
+  //   auto p2 = Temp().owner; // Here p2 is dangling.
+  if (const auto *FD = llvm::dyn_cast_or_null(E.D);
+  FD && !FD->getType()->isReferenceType() &&
+  isRecordWithAttr(FD->getType())) {
+return Report;
+  

[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Nathan Gauër via cfe-commits

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

Maybe the renaming shall be done in another PR for both DXIL and SPV, but if 
it's a small change, might want to do it now no?

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


[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Nathan Gauër via cfe-commits

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


[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Nathan Gauër via cfe-commits


@@ -118,6 +118,10 @@ let TargetPrefix = "spv" in {
   : DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_any_ty, llvm_i8_ty],
   [IntrInaccessibleMemOrArgMemOnly]>;
 
+  def int_spv_resource_getpointer

Keenuts wrote:

Shall it be `int_spv_resource_getptr` instead? 
(https://github.com/llvm/wg-hlsl/blob/main/proposals/0014-consistent-naming-for-dx-intrinsics.md)

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


[clang] [Clang] Don't form a type constraint if the concept is invalid (PR #122065)

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

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/122065

>From 312776183068b84ddfea38ea7158c44c1926160a Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 8 Jan 2025 15:40:23 +0800
Subject: [PATCH 1/2] [Clang] Don't form a type constraint if the concept is
 invalid

After 0dedd6fe1 and 03229e7c0, invalid concept declarations might
lack expressions for evaluation and normalization. This could make
it crash in certain scenarios, apart from the one of evaluation
concepts showed in 03229e7c0, there's also an issue when checking
specializations where the normalization also relies on a non-null expression.

This patch prevents that by avoiding building up a type constraint
in such situations, thereafter the template parameter wouldn't
have a concept specialization of a null expression.

With this patch, the assumption in ASTWriterDecl is no longer valid.
Namely, HasConstraint and TypeConstraintInitialized must now represent
different meanings for both source fidelity and semantic requirements.
---
 clang/lib/Sema/SemaTemplate.cpp   |  3 +++
 clang/lib/Serialization/ASTWriterDecl.cpp |  1 -
 clang/test/SemaTemplate/concepts.cpp  | 12 
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 20ec2fbeaa6a8b..ce672b00893b0d 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4557,6 +4557,9 @@ Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
  const TemplateArgumentListInfo *TemplateArgs) {
   assert(NamedConcept && "A concept template id without a template?");
 
+  if (NamedConcept->isInvalidDecl())
+return ExprError();
+
   llvm::SmallVector SugaredConverted, CanonicalConverted;
   if (CheckTemplateArgumentList(
   NamedConcept, ConceptNameInfo.getLoc(),
diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp 
b/clang/lib/Serialization/ASTWriterDecl.cpp
index 75c1d9a6d438ce..c7b8759916f421 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -1951,7 +1951,6 @@ void 
ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   Record.push_back(D->wasDeclaredWithTypename());
 
   const TypeConstraint *TC = D->getTypeConstraint();
-  assert((bool)TC == D->hasTypeConstraint());
   if (TC) {
 auto *CR = TC->getConceptReference();
 Record.push_back(CR != nullptr);
diff --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 312469313fc535..f335ca3bd22bc3 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -1165,3 +1165,15 @@ concept C = invalid; // expected-error {{use of 
undeclared identifier 'invalid'}
 bool val2 = C;
 
 } // namespace GH109780
+
+namespace GH121980 {
+
+template 
+concept has_member_difference_type; // expected-error {{expected '='}}
+
+template  struct incrementable_traits; // 
expected-note {{declared here}}
+
+template 
+struct incrementable_traits; // expected-error {{not more specialized than 
the primary}}
+
+}

>From 202196262cc0864b9cbeb91ea6df6e0cd299fe5d Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 8 Jan 2025 18:43:02 +0800
Subject: [PATCH 2/2] Fix the serialization for invalid constraints

---
 clang/lib/Serialization/ASTReaderDecl.cpp | 6 +-
 clang/lib/Serialization/ASTWriterDecl.cpp | 4 +++-
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index 719bc0d06f5b11..9671492f0d6544 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -2663,7 +2663,11 @@ void 
ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
 
   D->setDeclaredWithTypename(Record.readInt());
 
-  if (D->hasTypeConstraint()) {
+  bool TypeConstraintInitialized = false;
+  if (D->hasTypeConstraint())
+TypeConstraintInitialized = Record.readBool();
+
+  if (D->hasTypeConstraint() && TypeConstraintInitialized) {
 ConceptReference *CR = nullptr;
 if (Record.readBool())
   CR = Record.readConceptReference();
diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp 
b/clang/lib/Serialization/ASTWriterDecl.cpp
index c7b8759916f421..f8ed155ca389d7 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -1951,6 +1951,8 @@ void 
ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   Record.push_back(D->wasDeclaredWithTypename());
 
   const TypeConstraint *TC = D->getTypeConstraint();
+  if (D->hasTypeConstraint())
+Record.push_back(/*TypeConstraintInitialized=*/TC != nullptr);
   if (TC) {
 auto *CR = TC->getConceptReference();
 Record.push_back(CR != nullptr);
@@ -1968,7 +1970,7 @@ void 
ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   if (OwnsDefaultArg)
 Record.AddTemplateAr

[clang] [clang] constexpr atomic builtins (__c11_atomic_OP and __atomic_OP) (PR #98756)

2025-01-08 Thread Hana Dusíková via cfe-commits


@@ -1921,6 +1921,22 @@ static bool EvaluateFixedPointOrInteger(const Expr *E, 
APFixedPoint &Result,
 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
EvalInfo &Info);
 
+/// Support for atomic builtins
+static bool EvaluateAtomicOrder(const AtomicExpr *E, EvalInfo &Info);
+static bool EvaluateAtomicWeak(const AtomicExpr *E, EvalInfo &Info);
+static bool EvaluateAtomicLoad(const AtomicExpr *E, APValue &Result,
+   EvalInfo &Info);
+static bool EvaluatePointerAndStoreValueInto(Expr *ResultPtr,
+ APValue &ValueToStore,
+ EvalInfo &Info);
+static bool EvaluateAtomicLoadInto(const AtomicExpr *E, EvalInfo &Info);
+static bool EvaluateAtomicStore(const AtomicExpr *E, EvalInfo &Info);
+static bool EvaluateAtomicExchangeInto(const AtomicExpr *E, EvalInfo &Info);
+static bool EvaluateAtomicFetchOp(const AtomicExpr *E, APValue &Result,
+  EvalInfo &Info, bool StoreToResultAfter);
+static bool EvaluateAtomicCompareExchange(const AtomicExpr *E, APValue &Result,
+  EvalInfo &Info);
+

hanickadot wrote:

I inlined some small functions in bigger, but I'm not fan of long switches. I 
personally found them one of the reasons I struggle understand what's happening 
in ExprConstant.cpp as I found myself scrolling up/down. So I'm keeping them in 
their own functions.

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


[clang] [llvm] [FMV][AArch64] Simplify version selection according to ACLE. (PR #121921)

2025-01-08 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea updated 
https://github.com/llvm/llvm-project/pull/121921

>From 785c6eca701edbd42686a4adaa2099b55b5271a0 Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Tue, 7 Jan 2025 11:37:32 +
Subject: [PATCH 1/4] [FMV][AArch64] Simplify version selection according to
 ACLE.

Currently, the more features a version has, the higher its priority is.
We are changing ACLE https://github.com/ARM-software/acle/pull/370 as
follows:

"Among any two versions, the higher priority version is determined by
 identifying the highest priority feature that is specified in exactly
 one of the versions, and selecting that version."
---
 .../test/CodeGen/attr-target-clones-aarch64.c |  48 
 clang/test/CodeGen/attr-target-version.c  |  78 ++---
 .../llvm/TargetParser/AArch64CPUFeatures.inc  |  57 +-
 .../llvm/TargetParser/AArch64TargetParser.h   |  10 +-
 llvm/lib/Target/AArch64/AArch64FMV.td | 105 +-
 llvm/lib/TargetParser/AArch64TargetParser.cpp |  15 +--
 .../TableGen/Basic/ARMTargetDefEmitter.cpp|   4 +-
 7 files changed, 183 insertions(+), 134 deletions(-)

diff --git a/clang/test/CodeGen/attr-target-clones-aarch64.c 
b/clang/test/CodeGen/attr-target-clones-aarch64.c
index 50c040f2093b01..b7e3a328db8773 100644
--- a/clang/test/CodeGen/attr-target-clones-aarch64.c
+++ b/clang/test/CodeGen/attr-target-clones-aarch64.c
@@ -64,20 +64,20 @@ inline int __attribute__((target_clones("fp16", 
"sve2-bitperm+fcma", "default"))
 // CHECK-NEXT:  resolver_entry:
 // CHECK-NEXT:call void @__init_cpu_features_resolver()
 // CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 33664
-// CHECK-NEXT:[[TMP2:%.*]] = icmp eq i64 [[TMP1]], 33664
+// CHECK-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 69793284352
+// CHECK-NEXT:[[TMP2:%.*]] = icmp eq i64 [[TMP1]], 69793284352
 // CHECK-NEXT:[[TMP3:%.*]] = and i1 true, [[TMP2]]
 // CHECK-NEXT:br i1 [[TMP3]], label [[RESOLVER_RETURN:%.*]], label 
[[RESOLVER_ELSE:%.*]]
 // CHECK:   resolver_return:
-// CHECK-NEXT:ret ptr @ftc._MaesMlse
+// CHECK-NEXT:ret ptr @ftc._Msve2
 // CHECK:   resolver_else:
 // CHECK-NEXT:[[TMP4:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 69793284352
-// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 69793284352
+// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 33664
+// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 33664
 // CHECK-NEXT:[[TMP7:%.*]] = and i1 true, [[TMP6]]
 // CHECK-NEXT:br i1 [[TMP7]], label [[RESOLVER_RETURN1:%.*]], label 
[[RESOLVER_ELSE2:%.*]]
 // CHECK:   resolver_return1:
-// CHECK-NEXT:ret ptr @ftc._Msve2
+// CHECK-NEXT:ret ptr @ftc._MaesMlse
 // CHECK:   resolver_else2:
 // CHECK-NEXT:ret ptr @ftc.default
 //
@@ -411,20 +411,20 @@ inline int __attribute__((target_clones("fp16", 
"sve2-bitperm+fcma", "default"))
 // CHECK-NEXT:  resolver_entry:
 // CHECK-NEXT:call void @__init_cpu_features_resolver()
 // CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 70369817985280
-// CHECK-NEXT:[[TMP2:%.*]] = icmp eq i64 [[TMP1]], 70369817985280
+// CHECK-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 1125899906842624
+// CHECK-NEXT:[[TMP2:%.*]] = icmp eq i64 [[TMP1]], 1125899906842624
 // CHECK-NEXT:[[TMP3:%.*]] = and i1 true, [[TMP2]]
 // CHECK-NEXT:br i1 [[TMP3]], label [[RESOLVER_RETURN:%.*]], label 
[[RESOLVER_ELSE:%.*]]
 // CHECK:   resolver_return:
-// CHECK-NEXT:ret ptr @ftc_inline3._MsbMsve
+// CHECK-NEXT:ret ptr @ftc_inline3._Mbti
 // CHECK:   resolver_else:
 // CHECK-NEXT:[[TMP4:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 1125899906842624
-// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 1125899906842624
+// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 70369817985280
+// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 70369817985280
 // CHECK-NEXT:[[TMP7:%.*]] = and i1 true, [[TMP6]]
 // CHECK-NEXT:br i1 [[TMP7]], label [[RESOLVER_RETURN1:%.*]], label 
[[RESOLVER_ELSE2:%.*]]
 // CHECK:   resolver_return1:
-// CHECK-NEXT:ret ptr @ftc_inline3._Mbti
+// CHECK-NEXT:ret ptr @ftc_inline3._MsbMsve
 // CHECK:   resolver_else2:
 // CHECK-NEXT:ret ptr @ftc_inline3.default
 //
@@ -521,20 +521,20 @@ inline int __attribute__((target_clones("fp16", 
"sve2-bitperm+fcma", "default"))
 // CHECK-MTE-BTI-NEXT:  resolver_entry:
 // CHECK-MTE-BTI-NEXT:call void @__init_cpu_features_resolver()
 // CHECK-MTE-BTI-NEXT:[[TMP0:%.*]] = load i64, ptr 
@__aarch64_cpu_features, align 8
-// CHECK-MTE-BTI-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 33664
-// CHECK-MTE-BTI-NEXT:[[TMP2:%.*]] = icmp eq i64 [[TMP1]], 33664
+// CHECK-MTE-BTI-NEXT:[[TMP1:%.*]] = 

[clang] [clang] constexpr atomic builtins (__c11_atomic_OP and __atomic_OP) (PR #98756)

2025-01-08 Thread Hana Dusíková via cfe-commits

https://github.com/hanickadot updated 
https://github.com/llvm/llvm-project/pull/98756

From 7d65b133b5f04e078b3b26cee2b4be0fe78d01e6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Mon, 6 Jan 2025 21:06:10 +0100
Subject: [PATCH 1/2] [clang] implement P3309 atomic builtins in constant
 evaluator

---
 clang/include/clang/Basic/Builtins.td |  80 +--
 clang/lib/AST/ExprConstant.cpp| 540 ++
 .../SemaCXX/atomic-constexpr-c11-builtins.cpp | 326 +++
 .../SemaCXX/atomic-constexpr-gcc-builtins.cpp | 504 
 4 files changed, 1410 insertions(+), 40 deletions(-)
 create mode 100644 clang/test/SemaCXX/atomic-constexpr-c11-builtins.cpp
 create mode 100644 clang/test/SemaCXX/atomic-constexpr-gcc-builtins.cpp

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 468c16050e2bf0..797191fba888d2 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1744,97 +1744,97 @@ def SyncSwapN : Builtin, SyncBuiltinsTemplate {
 // C11 _Atomic operations for .
 def C11AtomicInit : AtomicBuiltin {
   let Spellings = ["__c11_atomic_init"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicLoad : AtomicBuiltin {
   let Spellings = ["__c11_atomic_load"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicStore : AtomicBuiltin {
   let Spellings = ["__c11_atomic_store"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicExchange : AtomicBuiltin {
   let Spellings = ["__c11_atomic_exchange"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicCompareExchangeStrong : AtomicBuiltin {
   let Spellings = ["__c11_atomic_compare_exchange_strong"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicCompareExchangeWeak : AtomicBuiltin {
   let Spellings = ["__c11_atomic_compare_exchange_weak"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchAdd : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_add"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchSub : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_sub"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchAnd : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_and"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchOr : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_or"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchXor : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_xor"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchNand : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_nand"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchMax : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_max"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicFetchMin : AtomicBuiltin {
   let Spellings = ["__c11_atomic_fetch_min"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def C11AtomicThreadFence : Builtin {
   let Spellings = ["__c11_atomic_thread_fence"];
-  let Attributes = [NoThrow];
+  let Attributes = [NoThrow, Constexpr];
   let Prototype = "void(int)";
 }
 
 def C11AtomicSignalFence : Builtin {
   let Spellings = ["__c11_atomic_signal_fence"];
-  let Attributes = [NoThrow];
+  let Attributes = [NoThrow, Constexpr];
   let Prototype = "void(int)";
 }
 
@@ -1847,133 +1847,133 @@ def C11AtomicIsLockFree : Builtin {
 // GNU atomic builtins.
 def AtomicLoad : AtomicBuiltin {
   let Spellings = ["__atomic_load"];
-  let Attributes = [CustomTypeChecking];
+  let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
 
 def AtomicLoadN : AtomicBuiltin {
   let Spellings = ["__atomic_load_n"];
-  let

[clang] [Driver][SPIR-V] Use consistent tools to convert between text and binary form (PR #120266)

2025-01-08 Thread Dmitry Sidorov via cfe-commits

MrSidims wrote:

I agree with Sven. We mustn't reuse llvm-spirv's tests format in other 
repositories. 

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


[clang] [clang][bytecode] Implement __builtin_constant_p differently (PR #122099)

2025-01-08 Thread Timm Baeder via cfe-commits

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

See the comment at the beginning of `InterpBuiltinConstantP.h` for an 
explanation.

>From 7fe5944ed5f072c0e74202fd01aa65d87aea3787 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 7 Jan 2025 13:34:08 +0100
Subject: [PATCH] [clang][bytecode] Implement __builtin_constant_p differently

---
 clang/lib/AST/ByteCode/Compiler.cpp   |   3 +
 clang/lib/AST/ByteCode/Function.h |   8 +
 clang/lib/AST/ByteCode/Interp.h   |  11 ++
 clang/lib/AST/ByteCode/InterpBuiltin.cpp  |  76 
 .../AST/ByteCode/InterpBuiltinConstantP.cpp   | 183 ++
 .../lib/AST/ByteCode/InterpBuiltinConstantP.h |  77 
 clang/lib/AST/ByteCode/Opcodes.td |   6 +
 clang/lib/AST/CMakeLists.txt  |   1 +
 .../test/AST/ByteCode/builtin-constant-p.cpp  |  69 ++-
 clang/test/CodeGenCXX/builtin-constant-p.cpp  |   1 +
 10 files changed, 357 insertions(+), 78 deletions(-)
 create mode 100644 clang/lib/AST/ByteCode/InterpBuiltinConstantP.cpp
 create mode 100644 clang/lib/AST/ByteCode/InterpBuiltinConstantP.h

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 036f9608bf3ca1..2ad3514351f357 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -4538,6 +4538,9 @@ bool Compiler::visitAPValueInitializer(const 
APValue &Val,
 template 
 bool Compiler::VisitBuiltinCallExpr(const CallExpr *E,
  unsigned BuiltinID) {
+  if (BuiltinID == Builtin::BI__builtin_constant_p)
+return this->emitBCP(classifyPrim(E), E->getArg(0), E);
+
   const Function *Func = getFunction(E->getDirectCallee());
   if (!Func)
 return false;
diff --git a/clang/lib/AST/ByteCode/Function.h 
b/clang/lib/AST/ByteCode/Function.h
index 409a80f59f1e94..389a57b2d27601 100644
--- a/clang/lib/AST/ByteCode/Function.h
+++ b/clang/lib/AST/ByteCode/Function.h
@@ -226,6 +226,14 @@ class Function final {
 return ParamTypes[ParamIndex];
   }
 
+  std::optional findParam(const ValueDecl *D) const {
+for (auto &[K, V] : Params) {
+  if (V.second->asValueDecl() == D)
+return K;
+}
+return std::nullopt;
+  }
+
 private:
   /// Construct a function representing an actual function.
   Function(Program &P, FunctionDeclTy Source, unsigned ArgSize,
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index d2aec69072e04f..4cffacbd14ad9a 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -22,6 +22,7 @@
 #include "Function.h"
 #include "FunctionPointer.h"
 #include "InterpBuiltinBitCast.h"
+#include "InterpBuiltinConstantP.h"
 #include "InterpFrame.h"
 #include "InterpStack.h"
 #include "InterpState.h"
@@ -3040,6 +3041,16 @@ bool GetTypeid(InterpState &S, CodePtr OpPC, const Type 
*TypePtr,
 bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType);
 bool DiagTypeid(InterpState &S, CodePtr OpPC);
 
+/// __builtin_constant_p.
+template ::T>
+bool BCP(InterpState &S, CodePtr OpPC, const Expr *E) {
+  BCPVisitor BV{S};
+  BV.VisitStmt(const_cast(E));
+
+  S.Stk.push(T::from(BV.Result));
+  return true;
+}
+
 
//===--===//
 // Read opcode arguments
 
//===--===//
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 0d52083b069464..57b946bc02707a 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1505,77 +1505,6 @@ static bool interp__builtin_ptrauth_string_discriminator(
   return true;
 }
 
-// FIXME: This implementation is not complete.
-// The Compiler instance we create cannot access the current stack frame, local
-// variables, function parameters, etc. We also need protection from
-// side-effects, fatal errors, etc.
-static bool interp__builtin_constant_p(InterpState &S, CodePtr OpPC,
-   const InterpFrame *Frame,
-   const Function *Func,
-   const CallExpr *Call) {
-  const Expr *Arg = Call->getArg(0);
-  QualType ArgType = Arg->getType();
-
-  auto returnInt = [&S, Call](bool Value) -> bool {
-pushInteger(S, Value, Call->getType());
-return true;
-  };
-
-  // __builtin_constant_p always has one operand. The rules which gcc follows
-  // are not precisely documented, but are as follows:
-  //
-  //  - If the operand is of integral, floating, complex or enumeration type,
-  //and can be folded to a known value of that type, it returns 1.
-  //  - If the operand can be folded to a pointer to the first character
-  //of a string literal (or such a pointer cast to an integral type)
-  //or to a null pointer or an 

[clang] [clang][bytecode] Implement __builtin_constant_p differently (PR #122099)

2025-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

See the comment at the beginning of `InterpBuiltinConstantP.h` for an 
explanation.

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


10 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+3) 
- (modified) clang/lib/AST/ByteCode/Function.h (+8) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+11) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (-76) 
- (added) clang/lib/AST/ByteCode/InterpBuiltinConstantP.cpp (+183) 
- (added) clang/lib/AST/ByteCode/InterpBuiltinConstantP.h (+77) 
- (modified) clang/lib/AST/ByteCode/Opcodes.td (+6) 
- (modified) clang/lib/AST/CMakeLists.txt (+1) 
- (modified) clang/test/AST/ByteCode/builtin-constant-p.cpp (+67-2) 
- (modified) clang/test/CodeGenCXX/builtin-constant-p.cpp (+1) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 036f9608bf3ca1..2ad3514351f357 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -4538,6 +4538,9 @@ bool Compiler::visitAPValueInitializer(const 
APValue &Val,
 template 
 bool Compiler::VisitBuiltinCallExpr(const CallExpr *E,
  unsigned BuiltinID) {
+  if (BuiltinID == Builtin::BI__builtin_constant_p)
+return this->emitBCP(classifyPrim(E), E->getArg(0), E);
+
   const Function *Func = getFunction(E->getDirectCallee());
   if (!Func)
 return false;
diff --git a/clang/lib/AST/ByteCode/Function.h 
b/clang/lib/AST/ByteCode/Function.h
index 409a80f59f1e94..389a57b2d27601 100644
--- a/clang/lib/AST/ByteCode/Function.h
+++ b/clang/lib/AST/ByteCode/Function.h
@@ -226,6 +226,14 @@ class Function final {
 return ParamTypes[ParamIndex];
   }
 
+  std::optional findParam(const ValueDecl *D) const {
+for (auto &[K, V] : Params) {
+  if (V.second->asValueDecl() == D)
+return K;
+}
+return std::nullopt;
+  }
+
 private:
   /// Construct a function representing an actual function.
   Function(Program &P, FunctionDeclTy Source, unsigned ArgSize,
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index d2aec69072e04f..4cffacbd14ad9a 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -22,6 +22,7 @@
 #include "Function.h"
 #include "FunctionPointer.h"
 #include "InterpBuiltinBitCast.h"
+#include "InterpBuiltinConstantP.h"
 #include "InterpFrame.h"
 #include "InterpStack.h"
 #include "InterpState.h"
@@ -3040,6 +3041,16 @@ bool GetTypeid(InterpState &S, CodePtr OpPC, const Type 
*TypePtr,
 bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType);
 bool DiagTypeid(InterpState &S, CodePtr OpPC);
 
+/// __builtin_constant_p.
+template ::T>
+bool BCP(InterpState &S, CodePtr OpPC, const Expr *E) {
+  BCPVisitor BV{S};
+  BV.VisitStmt(const_cast(E));
+
+  S.Stk.push(T::from(BV.Result));
+  return true;
+}
+
 
//===--===//
 // Read opcode arguments
 
//===--===//
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 0d52083b069464..57b946bc02707a 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1505,77 +1505,6 @@ static bool interp__builtin_ptrauth_string_discriminator(
   return true;
 }
 
-// FIXME: This implementation is not complete.
-// The Compiler instance we create cannot access the current stack frame, local
-// variables, function parameters, etc. We also need protection from
-// side-effects, fatal errors, etc.
-static bool interp__builtin_constant_p(InterpState &S, CodePtr OpPC,
-   const InterpFrame *Frame,
-   const Function *Func,
-   const CallExpr *Call) {
-  const Expr *Arg = Call->getArg(0);
-  QualType ArgType = Arg->getType();
-
-  auto returnInt = [&S, Call](bool Value) -> bool {
-pushInteger(S, Value, Call->getType());
-return true;
-  };
-
-  // __builtin_constant_p always has one operand. The rules which gcc follows
-  // are not precisely documented, but are as follows:
-  //
-  //  - If the operand is of integral, floating, complex or enumeration type,
-  //and can be folded to a known value of that type, it returns 1.
-  //  - If the operand can be folded to a pointer to the first character
-  //of a string literal (or such a pointer cast to an integral type)
-  //or to a null pointer or an integer cast to a pointer, it returns 1.
-  //
-  // Otherwise, it returns 0.
-  //
-  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
-  // its support for this did not work prior to GCC 9 and is not yet well
-  // understood.
-  if (ArgType->isIntegralOrEnumerationType() || ArgType

[clang] [clang-tools-extra] [clang] Avoid re-evaluating field bitwidth (PR #117732)

2025-01-08 Thread Timm Baeder via cfe-commits

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

>From 953ee08b6e8ae9c0b16916e7f31cb9d2f3d5dd8e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 27 Nov 2024 08:54:51 +0100
Subject: [PATCH] Save FieldDecl BitWidth as a ConstantExpr

---
 .../bugprone/NarrowingConversionsCheck.cpp|  2 +-
 .../bugprone/TooSmallLoopVariableCheck.cpp|  2 +-
 .../hicpp/MultiwayPathsCoveredCheck.cpp   |  2 +-
 clang-tools-extra/clangd/Hover.cpp|  2 +-
 clang/include/clang/AST/Decl.h|  6 --
 clang/include/clang/ASTMatchers/ASTMatchers.h |  3 +--
 clang/lib/AST/ASTContext.cpp  | 10 -
 clang/lib/AST/ByteCode/Interp.h   | 10 -
 .../lib/AST/ByteCode/InterpBuiltinBitCast.cpp |  8 +++
 clang/lib/AST/Decl.cpp| 16 +-
 clang/lib/AST/DeclCXX.cpp |  2 +-
 clang/lib/AST/Expr.cpp|  3 +--
 clang/lib/AST/ExprConstant.cpp|  2 +-
 clang/lib/AST/Randstruct.cpp  |  2 +-
 clang/lib/AST/RecordLayoutBuilder.cpp |  6 +++---
 clang/lib/CodeGen/ABIInfo.cpp |  2 +-
 clang/lib/CodeGen/ABIInfoImpl.cpp |  2 +-
 clang/lib/CodeGen/CGCall.cpp  |  6 +++---
 clang/lib/CodeGen/CGClass.cpp |  2 +-
 clang/lib/CodeGen/CGDebugInfo.cpp |  8 +++
 clang/lib/CodeGen/CGNonTrivialStruct.cpp  |  6 +++---
 clang/lib/CodeGen/CGObjCMac.cpp   |  3 +--
 clang/lib/CodeGen/CGObjCRuntime.cpp   |  2 +-
 clang/lib/CodeGen/CGRecordLayoutBuilder.cpp   | 20 +-
 clang/lib/CodeGen/SwiftCallingConv.cpp|  2 +-
 clang/lib/CodeGen/Targets/LoongArch.cpp   |  2 +-
 clang/lib/CodeGen/Targets/RISCV.cpp   |  2 +-
 clang/lib/CodeGen/Targets/X86.cpp |  2 +-
 clang/lib/CodeGen/Targets/XCore.cpp   |  2 +-
 .../Frontend/Rewrite/RewriteModernObjC.cpp|  3 ++-
 clang/lib/Sema/SemaChecking.cpp   | 10 -
 clang/lib/Sema/SemaDecl.cpp   | 21 ++-
 clang/lib/Sema/SemaDeclCXX.cpp|  6 +++---
 clang/lib/Sema/SemaDeclObjC.cpp   |  3 +--
 clang/lib/Sema/SemaOverload.cpp   |  2 +-
 clang/lib/StaticAnalyzer/Core/RegionStore.cpp |  2 +-
 clang/tools/libclang/CXType.cpp   |  2 +-
 clang/unittests/AST/ASTImporterTest.cpp   |  4 ++--
 38 files changed, 96 insertions(+), 94 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
index a950704208c73b..408390ebc70b64 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
@@ -38,7 +38,7 @@ AST_MATCHER(FieldDecl, hasIntBitwidth) {
   assert(Node.isBitField());
   const ASTContext &Ctx = Node.getASTContext();
   unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy);
-  unsigned CurrentBitWidth = Node.getBitWidthValue(Ctx);
+  unsigned CurrentBitWidth = Node.getBitWidthValue();
   return IntBitWidth == CurrentBitWidth;
 }
 
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
index a73d46f01d9b2d..4ceeefb78ee824 100644
--- a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
@@ -124,7 +124,7 @@ static MagnitudeBits calcMagnitudeBits(const ASTContext 
&Context,
   unsigned SignedBits = IntExprType->isUnsignedIntegerType() ? 0U : 1U;
 
   if (const auto *BitField = IntExpr->getSourceBitField()) {
-unsigned BitFieldWidth = BitField->getBitWidthValue(Context);
+unsigned BitFieldWidth = BitField->getBitWidthValue();
 return {BitFieldWidth - SignedBits, BitFieldWidth};
   }
 
diff --git a/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp 
b/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
index 47dafca2d03ff0..7028c3958f103e 100644
--- a/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
+++ b/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
@@ -160,7 +160,7 @@ void MultiwayPathsCoveredCheck::handleSwitchWithoutDefault(
 }
 if (const auto *BitfieldDecl =
 Result.Nodes.getNodeAs("bitfield")) {
-  return twoPow(BitfieldDecl->getBitWidthValue(*Result.Context));
+  return twoPow(BitfieldDecl->getBitWidthValue());
 }
 
 return static_cast(0);
diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 298fa79e3fd0ba..5e136d0e76ece7 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -1018,7 +1018,7 @@ void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
   const ASTRecordLayout &Layou

[clang] [clang-tools-extra] [clang] Avoid re-evaluating field bitwidth (PR #117732)

2025-01-08 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Python binding tests fail for unrelated reasons:
```
  curl: (23) Failure writing output to destination
  Error: Restoring cache failed: Error: The process '/usr/bin/sh' failed with 
exit code 2
```

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Florian Hahn via cfe-commits

https://github.com/fhahn updated 
https://github.com/llvm/llvm-project/pull/121789

>From 596d1346eb806e4c276042e50cca7514d3335f54 Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Mon, 6 Jan 2025 13:39:55 +
Subject: [PATCH 1/2] [Clang] Add __builtin_assume_dereferenceable to encode
 deref assumption.

This patch adds a new __builtin_assume_dereferenceable to encode
dereferenceability of a pointer using llvm.assume with an operand
bundle.

For now the builtin only accepts constant sizes, I am planning to drop
this restriction in a follow-up change.

This can be used to better optimize cases where a pointer is known to be
dereferenceable, e.g. unconditionally loading from p2 when vectorizing the loop.

int *get_ptr();

void foo(int* src, int x) {
  int *p2 = get_ptr();
  __builtin_assume_aligned(p2, 4);
  __builtin_assume_dereferenceable(p2, 4000);
  for (unsigned I = 0; I != 1000; ++I) {
int x = src[I];
if (x == 0)
  x = p2[I];
 src[I] = x;
  }
}
---
 clang/docs/LanguageExtensions.rst | 35 
 clang/include/clang/Basic/Builtins.td |  6 +++
 clang/lib/CodeGen/CGBuiltin.cpp   | 10 +
 .../CodeGen/builtin-assume-dereferenceable.c  | 34 +++
 .../Sema/builtin-assume-dereferenceable.c | 41 +++
 llvm/include/llvm/IR/IRBuilder.h  |  5 +++
 llvm/lib/IR/IRBuilder.cpp | 10 +
 7 files changed, 141 insertions(+)
 create mode 100644 clang/test/CodeGen/builtin-assume-dereferenceable.c
 create mode 100644 clang/test/Sema/builtin-assume-dereferenceable.c

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index e020710c7aa4f5..1a96647ae765e2 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2761,6 +2761,41 @@ etc.).
 
 Query for this feature with 
``__has_builtin(__builtin_assume_separate_storage)``.
 
+``__builtin_assume_dereferenceable``
+-
+
+``__builtin_assume_derefernceable`` is used to provide the optimizer with the
+knowledge that the pointer argument P is dereferenceable up to the specified
+number of bytes.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_assume_dereferenceable(const void *, size_t)
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  int foo(int *x, int y) {
+  __builtin_assume_dereferenceable(x, 4);
+  int z = 0;
+  if (y == 1) {
+// The optimizer may execute the load of x unconditionally.
+z = *x;
+}
+  return z;
+  }
+
+**Description**:
+
+The arguments to this function provide a start pointer ``P`` and a size ``S``.
+``P`` must be non-null and ``S`` at least 1. The optimizer may assume that
+``S`` bytes are dereferenceable starting at ``P``.
+
+Query for this feature with 
``__has_builtin(__builtin_assume_dereferenceable)``.
+
 
 ``__builtin_offsetof``
 --
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 468c16050e2bf0..e9d8c6f621afa9 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -839,6 +839,12 @@ def BuiltinAssumeAligned : Builtin {
   let Prototype = "void*(void const*, size_t, ...)";
 }
 
+def BuiltinAssumeDereferenceable : Builtin {
+  let Spellings = ["__builtin_assume_dereferenceable"];
+  let Attributes = [NoThrow, Const, Constexpr];
+  let Prototype = "void(void const*, _Constant size_t)";
+}
+
 def BuiltinFree : Builtin {
   let Spellings = ["__builtin_free"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index dcea32969fb990..03862b89e05950 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3726,6 +3726,16 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 AlignmentCI, OffsetValue);
 return RValue::get(PtrValue);
   }
+  case Builtin::BI__builtin_assume_dereferenceable: {
+const Expr *Ptr = E->getArg(0);
+Value *PtrValue = EmitScalarExpr(Ptr);
+Value *SizeValue = EmitScalarExpr(E->getArg(1));
+if (SizeValue->getType() != IntPtrTy)
+  SizeValue =
+  Builder.CreateIntCast(SizeValue, IntPtrTy, false, "casted.size");
+Builder.CreateDereferenceableAssumption(PtrValue, SizeValue);
+return RValue::get(nullptr);
+  }
   case Builtin::BI__assume:
   case Builtin::BI__builtin_assume: {
 if (E->getArg(0)->HasSideEffects(getContext()))
diff --git a/clang/test/CodeGen/builtin-assume-dereferenceable.c 
b/clang/test/CodeGen/builtin-assume-dereferenceable.c
new file mode 100644
index 00..cadffd4a84c264
--- /dev/null
+++ b/clang/test/CodeGen/builtin-assume-dereferenceable.c
@@ -0,0 +1,34 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple x86_64-un

[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Florian Hahn via cfe-commits


@@ -2761,6 +2761,41 @@ etc.).
 
 Query for this feature with 
``__has_builtin(__builtin_assume_separate_storage)``.
 
+``__builtin_assume_dereferenceable``
+-
+
+``__builtin_assume_derefernceable`` is used to provide the optimizer with the
+knowledge that the pointer argument P is dereferenceable up to the specified
+number of bytes.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_assume_dereferenceable(const void *, size_t)
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  int foo(int *x, int y) {
+  __builtin_assume_dereferenceable(x, 4);
+  int z = 0;
+  if (y == 1) {
+// The optimizer may execute the load of x unconditionally.
+z = *x;
+}
+  return z;
+  }
+
+**Description**:
+
+The arguments to this function provide a start pointer ``P`` and a size ``S``.
+``P`` must be non-null and ``S`` at least 1. The optimizer may assume that

fhahn wrote:

I think @erichkeane's example should be simplify-able due to the metadata.

I think it should be safe to add nonnull as well, done in the latest update.

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Florian Hahn via cfe-commits


@@ -3726,6 +3726,16 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 AlignmentCI, OffsetValue);
 return RValue::get(PtrValue);
   }
+  case Builtin::BI__builtin_assume_dereferenceable: {
+const Expr *Ptr = E->getArg(0);

fhahn wrote:

Pulled Size out to variable as well, thanks!

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Florian Hahn via cfe-commits


@@ -839,6 +839,12 @@ def BuiltinAssumeAligned : Builtin {
   let Prototype = "void*(void const*, size_t, ...)";
 }
 
+def BuiltinAssumeDereferenceable : Builtin {
+  let Spellings = ["__builtin_assume_dereferenceable"];
+  let Attributes = [NoThrow, Const, Constexpr];

fhahn wrote:

Dropped this for now and added a Sema test.

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Florian Hahn via cfe-commits


@@ -2761,6 +2761,41 @@ etc.).
 
 Query for this feature with 
``__has_builtin(__builtin_assume_separate_storage)``.
 
+``__builtin_assume_dereferenceable``
+-
+
+``__builtin_assume_derefernceable`` is used to provide the optimizer with the
+knowledge that the pointer argument P is dereferenceable up to the specified
+number of bytes.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_assume_dereferenceable(const void *, size_t)

fhahn wrote:

I think this is just Github trying to render this (`*` starts italic mode 
thanks)

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


[clang] [clang] Emit @llvm.assume before streaming_compatible functions when the streaming mode is known (PR #121917)

2025-01-08 Thread Sander de Smalen via cfe-commits

sdesmalen-arm wrote:

@efriedma-quic a motivating example is https://godbolt.org/z/aW9zTrdf9

With @NickGuy-Arm's patch, this would compile to:
```
_Z1xv:
rdvlx0, #1
ret

_Z1yv:
rdsvl   x0, #1
ret
```

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 32bc029be6265838833623fdd88cc665d5658dc7 
0711638af02e7680d35ac7647e96e5778e921320 --extensions h,cpp,c -- 
clang/test/CodeGen/builtin-assume-dereferenceable.c 
clang/test/SemaCXX/builtin-assume-dereferenceable.cpp 
clang/lib/CodeGen/CGBuiltin.cpp llvm/include/llvm/IR/IRBuilder.h 
llvm/lib/IR/IRBuilder.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 7ed3795e90..cb59d191c0 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3728,7 +3728,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   }
   case Builtin::BI__builtin_assume_dereferenceable: {
 const Expr *Ptr = E->getArg(0);
-const Expr *Size= E->getArg(1);
+const Expr *Size = E->getArg(1);
 Value *PtrValue = EmitScalarExpr(Ptr);
 Value *SizeValue = EmitScalarExpr(Size);
 if (SizeValue->getType() != IntPtrTy)

``




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


[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)

2025-01-08 Thread via cfe-commits

cor3ntin wrote:

> @cor3ntin Do we need to revert it for now?

I'd like us to figure out if it's a conformance issue first - but bearing 
resolution we should revert before end of week imo


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


[clang] [clang] Infer capture_by for insert_or_assign (PR #122109)

2025-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Utkarsh Saxena (usx95)


Changes

Useful for maps: 
https://en.cppreference.com/w/cpp/container/map/insert_or_assign



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


1 Files Affected:

- (modified) clang/lib/Sema/SemaAttr.cpp (+2-2) 


``diff
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 44485e71d57a01..42aa68d2905c03 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -307,8 +307,8 @@ void Sema::inferLifetimeCaptureByAttribute(FunctionDecl 
*FD) {
   Annotate(MD);
 return;
   }
-  static const llvm::StringSet<> CapturingMethods{"insert", "push",
-  "push_front", "push_back"};
+  static const llvm::StringSet<> CapturingMethods{
+  "insert", "insert_or_assign", "push", "push_front", "push_back"};
   if (!CapturingMethods.contains(MD->getName()))
 return;
   Annotate(MD);

``




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


[clang] [clang] Infer capture_by for insert_or_assign (PR #122109)

2025-01-08 Thread Utkarsh Saxena via cfe-commits

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


[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)

2025-01-08 Thread via cfe-commits

cor3ntin wrote:

> > We've started seeing libc++ test failures in the Fuchsia toolchain 
> > buildbots for Windows
> 
> We're hitting the same error in Chromium builds. Here is a stand-alone 
> reproducer: https://crbug.com/388428503#comment4

Thanks. @Endilll is working on a reduction, so that we get a better sense of 
what the issue is

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


[clang] [OpenMP] [Debug] Debug support for work sharing iterator variable (PR #122047)

2025-01-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

Maybe it fixes debug info, but definitely breaks some of the OpenMP support

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


[clang] Revert "[Clang] Implement CWG2369 "Ordering between constraints and substitution"" (PR #122130)

2025-01-08 Thread via cfe-commits

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

:cry: 

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


[clang-tools-extra] [clang-tidy] Add QtEnabled option to modernize-use-integer-sign-comprison (PR #122127)

2025-01-08 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tidy

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

Author: None (qt-tatiana)


Changes

- add an option ``QtEnabled``, that makes C++17 ``q20::cmp_*`` alternative 
available for Qt-based applications.

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


5 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp 
(+13-3) 
- (modified) 
clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h (+2-1) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
 (+4) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-integer-sign-comparison-qt.cpp
 (+123) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp
index 8f807bc0a96d56..f5171b0e815cb5 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp
@@ -80,11 +80,13 @@ 
UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
 : ClangTidyCheck(Name, Context),
   IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
utils::IncludeSorter::IS_LLVM),
-  areDiagsSelfContained()) {}
+  areDiagsSelfContained()),
+  QtFrameworkEnabled(Options.get("QtEnabled", false)) {}
 
 void UseIntegerSignComparisonCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
+  Options.store(Opts, "QtEnabled", QtFrameworkEnabled);
 }
 
 void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
@@ -154,8 +156,16 @@ void UseIntegerSignComparisonCheck::check(
   DiagnosticBuilder Diag =
   diag(BinaryOp->getBeginLoc(),
"comparison between 'signed' and 'unsigned' integers");
-  const std::string CmpNamespace = ("std::" + parseOpCode(OpCode)).str();
-  const std::string CmpHeader = "";
+  std::string CmpNamespace;
+  std::string CmpHeader;
+  if (getLangOpts().CPlusPlus17 && QtFrameworkEnabled) {
+CmpHeader = "";
+CmpNamespace = llvm::Twine("q20::" + parseOpCode(OpCode)).str();
+  }
+  if (getLangOpts().CPlusPlus20) {
+CmpHeader = "";
+CmpNamespace = llvm::Twine("std::" + parseOpCode(OpCode)).str();
+  }
   // Prefer modernize-use-integer-sign-comparison when C++20 is available!
   Diag << FixItHint::CreateReplacement(
   CharSourceRange(R1, SubExprLHS != nullptr),
diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h
index a1074829d6eca5..8fcc4f9f5c5c25 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h
@@ -30,11 +30,12 @@ class UseIntegerSignComparisonCheck : public ClangTidyCheck 
{
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
-return LangOpts.CPlusPlus20;
+return LangOpts.CPlusPlus20 || (LangOpts.CPlusPlus17 && 
QtFrameworkEnabled);
   }
 
 private:
   utils::IncludeInserter IncludeInserter;
+  const bool QtFrameworkEnabled;
 };
 
 } // namespace clang::tidy::modernize
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1fd9b6077be5f5..e92021f309d515 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -301,6 +301,11 @@ Changes in existing checks
   ` check to fix a
   crash when a class is declared but not defined.
 
+- Improved :doc:`modernize-use-integer-sign-comparison
+  ` check to
+  add an option ``QtEnabled``, that makes C++17 ``q20::cmp_*`` alternative
+  available for Qt-based applications.
+
 - Improved :doc:`modernize-use-nullptr
   ` check to also recognize
   ``NULL``/``__null`` (but not ``0``) when used with a templated type.
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
index 7e2c13b782694f..63e69e37cd70ca 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
@@ -34,3 +34,7 @@ Options
 
   A string specifying which include-style is used, `llvm` or `google`.
   Default is `llvm`.
+
+.. option:: QtEnabled
+  Makes C++17 ``q20::cmp_*`` alternative available for Qt-based
+  applications. Default is `false`.
diff --git 

[clang-tools-extra] [clang-tidy] Add QtEnabled option to modernize-use-integer-sign-comprison (PR #122127)

2025-01-08 Thread via cfe-commits

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


[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Steven Perron via cfe-commits

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


[clang] [CUDA][HIP] Fix overriding of constexpr virtual function (PR #121986)

2025-01-08 Thread Yaxun Liu via cfe-commits


@@ -1309,6 +1309,16 @@ Sema::CheckOverload(Scope *S, FunctionDecl *New, const 
LookupResult &Old,
   return Ovl_Overload;
 }
 
+template  static bool hasExplicitAttr(const FunctionDecl *D) {
+  if (!D)
+return false;
+  if (auto *A = D->getAttr())
+return !A->isImplicit();
+  return false;
+}
+/// Assuming \p New is either an overload or override of \p Old.
+/// \returns true if \p New is an overload of \p Old,
+///  false if \p New is an override of \p Old.

yxsamliu wrote:

Can you clarify? You mean when UseOverrideRules is true, the function will 
return true if the two function decls are overrides?

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


[clang] 92e575d - [HLSL] Add SPIR-V version of getPointer. (#121963)

2025-01-08 Thread via cfe-commits

Author: Steven Perron
Date: 2025-01-08T10:51:17-05:00
New Revision: 92e575d7e44b0230a27cfb8f6f2e2e3367b19967

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

LOG: [HLSL] Add SPIR-V version of getPointer. (#121963)

Use the spv version of the resource.getpointer intrinsic when targeting
SPIR-V.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CGHLSLRuntime.h
clang/test/CodeGenHLSL/builtins/RWBuffer-subscript.hlsl
llvm/include/llvm/IR/IntrinsicsSPIRV.td

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index dcea32969fb990..573be932f8b1aa 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -19212,8 +19212,9 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 // TODO: Map to an hlsl_device address space.
 llvm::Type *RetTy = llvm::PointerType::getUnqual(getLLVMContext());
 
-return Builder.CreateIntrinsic(RetTy, Intrinsic::dx_resource_getpointer,
-   ArrayRef{HandleOp, IndexOp});
+return Builder.CreateIntrinsic(
+RetTy, CGM.getHLSLRuntime().getCreateResourceGetPointerIntrinsic(),
+ArrayRef{HandleOp, IndexOp});
   }
   case Builtin::BI__builtin_hlsl_all: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));

diff  --git a/clang/lib/CodeGen/CGHLSLRuntime.h 
b/clang/lib/CodeGen/CGHLSLRuntime.h
index 3d5724118611cb..46e472f0aae213 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.h
+++ b/clang/lib/CodeGen/CGHLSLRuntime.h
@@ -104,6 +104,8 @@ class CGHLSLRuntime {
   GENERATE_HLSL_INTRINSIC_FUNCTION(SClamp, sclamp)
   GENERATE_HLSL_INTRINSIC_FUNCTION(UClamp, uclamp)
 
+  GENERATE_HLSL_INTRINSIC_FUNCTION(CreateResourceGetPointer,
+   resource_getpointer)
   GENERATE_HLSL_INTRINSIC_FUNCTION(CreateHandleFromBinding,
resource_handlefrombinding)
   GENERATE_HLSL_INTRINSIC_FUNCTION(BufferUpdateCounter, resource_updatecounter)

diff  --git a/clang/test/CodeGenHLSL/builtins/RWBuffer-subscript.hlsl 
b/clang/test/CodeGenHLSL/builtins/RWBuffer-subscript.hlsl
index 4428b77dd9ec8e..2ad5b82a029129 100644
--- a/clang/test/CodeGenHLSL/builtins/RWBuffer-subscript.hlsl
+++ b/clang/test/CodeGenHLSL/builtins/RWBuffer-subscript.hlsl
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -emit-llvm -o - -O0 
%s | FileCheck %s
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -emit-llvm -o - -O0 
%s | FileCheck %s --check-prefixes=DXC,CHECK
+// RUN: %clang_cc1 -triple spirv1.6-pc-vulkan1.3-compute -emit-llvm -o - -O0 
%s | FileCheck %s --check-prefixes=SPIRV,CHECK
 
 RWBuffer In;
 RWBuffer Out;
@@ -7,15 +8,19 @@ RWBuffer Out;
 void main(unsigned GI : SV_GroupIndex) {
   // CHECK: define void @main()
 
-  // CHECK: %[[INPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) 
ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // DXC: %[[INPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // SPIRV: %[[INPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) 
ptr 
@llvm.spv.resource.getpointer.p0.tspirv.Image_i32_5_2_0_0_2_0t(target("spirv.Image",
 i32, 5, 2, 0, 0, 2, 0) %{{.*}}, i32 %{{.*}})
   // CHECK: %[[LOAD:.*]] = load i32, ptr %[[INPTR]]
-  // CHECK: %[[OUTPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) 
ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // DXC: %[[OUTPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // SPIRV: %[[OUTPTR:.*]] = call noundef nonnull align 4 dereferenceable(4) 
ptr 
@llvm.spv.resource.getpointer.p0.tspirv.Image_i32_5_2_0_0_2_0t(target("spirv.Image",
 i32, 5, 2, 0, 0, 2, 0) %{{.*}}, i32 %{{.*}})
   // CHECK: store i32 %[[LOAD]], ptr %[[OUTPTR]]
   Out[GI] = In[GI];
 
-  // CHECK: %[[INPTR:.*]] = call ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // DXC: %[[INPTR:.*]] = call ptr 
@llvm.dx.resource.getpointer.p0.tdx.TypedBuffer_i32_1_0_1t(target("dx.TypedBuffer",
 i32, 1, 0, 1) %{{.*}}, i32 %{{.*}})
+  // SPIRV: %[[INPTR:.*]] = call ptr 
@llvm.spv.resource.getpointer.p0.tspirv.Image_i32_5_2_0_0_2_0t(target("spirv.Image",
 i32, 5, 2, 0, 0, 2, 0) %{{.*}}, i32 %{{.*}})
   // CHECK: %[[LOAD:.*]] = load i32, ptr %[[INPTR]]
-  // CHECK: %[[OUTPTR:.*]] = call noundef nonnull align 4 

[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Steven Perron via cfe-commits

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

2025-01-08 Thread Nikolas Klauser via cfe-commits

philnik777 wrote:

Thanks, this is awesome! A non-constant version would be even more so :)

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

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


@@ -839,6 +839,12 @@ def BuiltinAssumeAligned : Builtin {
   let Prototype = "void*(void const*, size_t, ...)";
 }
 
+def BuiltinAssumeDereferenceable : Builtin {
+  let Spellings = ["__builtin_assume_dereferenceable"];
+  let Attributes = [NoThrow, Const, Constexpr];

erichkeane wrote:

The constexpr implementation should be pretty easy, since this is effectively a 
no-op, right? Though perhaps you still have to evaluate the arguments.

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


[clang] [clang] Propagate -ftime-report to offload lto (PR #122143)

2025-01-08 Thread Shilei Tian via cfe-commits

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


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


[clang-tools-extra] 35c5e56 - Clean up -Wdangling-assignment-gsl in clang and mlir

2025-01-08 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2025-01-08T14:46:15+01:00
New Revision: 35c5e56b6113b468b521c071ac141b4bb94da1d7

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

LOG: Clean up -Wdangling-assignment-gsl in clang and mlir

These are triggering after b037bceef6a40c5c00c1f67cc5a334e2c4e5e041.

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/Analysis.cpp
clang/tools/driver/driver.cpp
mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
mlir/lib/Dialect/SCF/Utils/Utils.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index 16013f53894e8d..e3a4834cb19aeb 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -85,8 +85,9 @@ analyze(llvm::ArrayRef ASTRoots,
   const auto MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
   llvm::DenseSet Used;
   llvm::StringMap Missing;
+  constexpr auto DefaultHeaderFilter = [](llvm::StringRef) { return false; };
   if (!HeaderFilter)
-HeaderFilter = [](llvm::StringRef) { return false; };
+HeaderFilter = DefaultHeaderFilter;
   OptionalDirectoryEntryRef ResourceDir =
   PP.getHeaderSearchInfo().getModuleMap().getBuiltinDir();
   walkUsed(ASTRoots, MacroRefs, PI, PP,

diff  --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 12038de476ace1..ffd157e60997cd 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -355,10 +355,12 @@ int clang_main(int Argc, char **Argv, const 
llvm::ToolContext &ToolContext) {
   if (!SetBackdoorDriverOutputsFromEnvVars(TheDriver))
 return 1;
 
+  auto ExecuteCC1WithContext =
+  [&ToolContext](SmallVectorImpl &ArgV) {
+return ExecuteCC1Tool(ArgV, ToolContext);
+  };
   if (!UseNewCC1Process) {
-TheDriver.CC1Main = [ToolContext](SmallVectorImpl &ArgV) {
-  return ExecuteCC1Tool(ArgV, ToolContext);
-};
+TheDriver.CC1Main = ExecuteCC1WithContext;
 // Ensure the CC1Command actually catches cc1 crashes
 llvm::CrashRecoveryContext::Enable();
   }

diff  --git a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp 
b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
index 0f2c889d4f390d..4e02559a089493 100644
--- a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
+++ b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
@@ -919,8 +919,9 @@ static void generateUnrolledLoop(
   // 'forOp'.
   auto builder = OpBuilder::atBlockTerminator(loopBodyBlock);
 
+  constexpr auto defaultAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
   if (!annotateFn)
-annotateFn = [](unsigned, Operation *, OpBuilder) {};
+annotateFn = defaultAnnotateFn;
 
   // Keep a pointer to the last non-terminator operation in the original block
   // so that we know what to clone (since we are doing this in-place).

diff  --git a/mlir/lib/Dialect/SCF/Utils/Utils.cpp 
b/mlir/lib/Dialect/SCF/Utils/Utils.cpp
index 41410a0a56aa98..6cda7100fe073d 100644
--- a/mlir/lib/Dialect/SCF/Utils/Utils.cpp
+++ b/mlir/lib/Dialect/SCF/Utils/Utils.cpp
@@ -329,8 +329,9 @@ static void generateUnrolledLoop(
   // 'forOp'.
   auto builder = OpBuilder::atBlockTerminator(loopBodyBlock);
 
+  constexpr auto defaultAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
   if (!annotateFn)
-annotateFn = [](unsigned, Operation *, OpBuilder) {};
+annotateFn = defaultAnnotateFn;
 
   // Keep a pointer to the last non-terminator operation in the original block
   // so that we know what to clone (since we are doing this in-place).



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


[clang] [OpenMP] Change default version to OMP6.0. (PR #122108)

2025-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Zahira Ammarguellat (zahiraam)


Changes

In https://github.com/llvm/llvm-project/pull/119891 we are introducing the 
support for `#pragma omp stripe` which is an OMP6.0 feature (see 
https://github.com/llvm/llvm-project/pull/119891/files#r1896944800). This PR 
changes the default option to 6.0.

---

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


35 Files Affected:

- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+2-2) 
- (modified) clang/lib/Frontend/InitPreprocessor.cpp (+6-3) 
- (modified) clang/lib/Parse/ParseOpenMP.cpp (+3-3) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+1-1) 
- (modified) clang/test/OpenMP/declare_mapper_messages.c (+9-11) 
- (modified) clang/test/OpenMP/declare_mapper_messages.cpp (+2-2) 
- (modified) clang/test/OpenMP/declare_reduction_messages.cpp (+3-3) 
- (modified) clang/test/OpenMP/declare_simd_ast_print.c (-2) 
- (modified) clang/test/OpenMP/declare_simd_ast_print.cpp (+11-11) 
- (modified) clang/test/OpenMP/declare_simd_codegen.cpp (+80-56) 
- (modified) clang/test/OpenMP/declare_simd_messages.cpp (+8-7) 
- (modified) clang/test/OpenMP/declare_target_ast_print.cpp (+32-43) 
- (modified) clang/test/OpenMP/declare_target_codegen.cpp (+12) 
- (modified) clang/test/OpenMP/declare_target_messages.cpp (+21-29) 
- (modified) clang/test/OpenMP/declare_target_only_one_side_compilation.cpp 
(+2-2) 
- (modified) clang/test/OpenMP/declare_target_variables_ast_print.cpp (+1-1) 
- (modified) clang/test/OpenMP/depobj_ast_print.cpp (+6-6) 
- (modified) clang/test/OpenMP/depobj_codegen.cpp (+13-8) 
- (modified) clang/test/OpenMP/depobj_messages.cpp (+6-6) 
- (modified) clang/test/OpenMP/distribute_parallel_for_ast_print.cpp (+6-6) 
- (modified) clang/test/OpenMP/distribute_parallel_for_reduction_messages.cpp 
(+2-2) 
- (modified) clang/test/OpenMP/distribute_parallel_for_simd_ast_print.cpp 
(+6-6) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_simd_reduction_messages.cpp (+2-2) 
- (modified) clang/test/OpenMP/distribute_simd_ast_print.cpp (+6-6) 
- (modified) clang/test/OpenMP/distribute_simd_misc_messages.c (+4-4) 
- (modified) clang/test/OpenMP/distribute_simd_reduction_messages.cpp (+2-2) 
- (modified) clang/test/OpenMP/error_ast_print.cpp (+6-6) 
- (modified) clang/test/OpenMP/error_codegen.cpp (+2-2) 
- (modified) clang/test/OpenMP/error_message.cpp (+2-2) 
- (modified) clang/test/OpenMP/flush_ast_print.cpp (+6-6) 
- (modified) clang/test/OpenMP/flush_codegen.cpp (+9-9) 
- (modified) clang/test/OpenMP/for_linear_codegen.cpp (+193-422) 
- (modified) clang/test/OpenMP/for_linear_messages.cpp (+2-2) 
- (modified) clang/test/OpenMP/for_reduction_messages.cpp (+2-2) 
- (modified) clang/test/OpenMP/for_simd_ast_print.cpp (+6-6) 


``diff
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 348c56cc37da3f..edae9106432117 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -4174,7 +4174,7 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
   }
 
   // Check if -fopenmp is specified and set default version to 5.0.
-  Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
+  Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 60 : 0;
   // Check if -fopenmp-simd is specified.
   bool IsSimdSpecified =
   Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
@@ -4192,7 +4192,7 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
   if (Opts.OpenMP || Opts.OpenMPSimd) {
 if (int Version = getLastArgIntValue(
 Args, OPT_fopenmp_version_EQ,
-(IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
+(IsSimdSpecified || IsTargetSpecified) ? 60 : Opts.OpenMP, Diags))
   Opts.OpenMP = Version;
 // Provide diagnostic when a given target is not expected to be an OpenMP
 // device or host.
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 29723b573e771a..90289c8d81962a 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -1460,12 +1460,15 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
 case 50:
   Builder.defineMacro("_OPENMP", "201811");
   break;
+case 51:
+  Builder.defineMacro("_OPENMP", "202011");
+  break;
 case 52:
   Builder.defineMacro("_OPENMP", "202111");
   break;
-default: // case 51:
-  // Default version is OpenMP 5.1
-  Builder.defineMacro("_OPENMP", "202011");
+default:
+  // Default version is OpenMP 6.0
+  Builder.defineMacro("_OPENMP", "202411");
   break;
 }
   }
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index b4e973bc84a7b0..52adadf47e5103 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/cla

[clang] [OpenMP] Change default version to OMP6.0. (PR #122108)

2025-01-08 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [OpenMP] Change default version to OMP6.0. (PR #122108)

2025-01-08 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

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

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


[clang] [clang-tools-extra] [clang] Avoid re-evaluating field bitwidth (PR #117732)

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

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-arm-ubuntu` running 
on `linaro-lldb-arm-ubuntu` while building `clang-tools-extra,clang` at step 6 
"test".

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


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

```
Step 6 (test) failure: build (failure)
...
PASS: lldb-api :: 
commands/command/script/import/rdar-12586188/TestRdar12586188.py (25 of 2863)
PASS: lldb-api :: commands/command/script/import/TestImport.py (26 of 2863)
PASS: lldb-api :: commands/command/script_alias/TestCommandScriptAlias.py (27 
of 2863)
PASS: lldb-api :: commands/command/source/TestCommandSource.py (28 of 2863)
PASS: lldb-api :: commands/disassemble/basic/TestDisassembleBreakpoint.py (29 
of 2863)
PASS: lldb-api :: commands/disassemble/basic/TestFrameDisassemble.py (30 of 
2863)
PASS: lldb-api :: commands/command/script/TestCommandScript.py (31 of 2863)
PASS: lldb-api :: 
commands/expression/anonymous-struct/TestCallUserAnonTypedef.py (32 of 2863)
PASS: lldb-api :: 
commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py
 (33 of 2863)
UNRESOLVED: lldb-api :: commands/expression/bitfield_enums/TestBitfieldEnums.py 
(34 of 2863)
 TEST 'lldb-api :: 
commands/expression/bitfield_enums/TestBitfieldEnums.py' FAILED 

Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/dotest.py 
-u CXXFLAGS -u CFLAGS --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/include --env 
LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --arch 
armv8l --build-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/dsymutil 
--make /usr/bin/gmake --llvm-tools-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --lldb-obj-root 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/tools/lldb --lldb-libs-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/commands/expression/bitfield_enums
 -p TestBitfieldEnums.py
--
Exit Code: -6

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
81fc3add1e627c23b7270fe2739cdacc09063e54)
  clang revision 81fc3add1e627c23b7270fe2739cdacc09063e54
  llvm revision 81fc3add1e627c23b7270fe2739cdacc09063e54

--
Command Output (stderr):
--
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_bitfield_enums_dsym (TestBitfieldEnums.TestBitfieldEnum) (test case does 
not fall in any category of interest for this run) 
python3.10: ../llvm-project/clang/lib/AST/Decl.cpp:4604: unsigned int 
clang::FieldDecl::getBitWidthValue() const: Assertion 
`isa(getBitWidth())' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace.
Stack dump:
0.   parser at end of file
1.  :43:1: Generating code for declaration 
'$__lldb_expr'
#0 0xf162e0dc llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
Signals.cpp:0:0
#1 0xf162bb3c llvm::sys::RunSignalHandlers() Signals.cpp:0:0
#2 0xf162e970 SignalHandler(int) Signals.cpp:0:0
#3 0xf7d7d6e0 __default_sa_restorer 
./signal/../sysdeps/unix/sysv/linux/arm/sigrestorer.S:67:0
#4 0xf7d6db06 ./csu/../sysdeps/unix/sysv/linux/arm/libc-do-syscall.S:47:0
#5 0xf7dad292 __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
#6 0xf7d7c840 gsignal ./signal/../sysdeps/posix/raise.c:27:6

--


PASS: lldb-api :: commands/expression/calculator_mode/TestCalculatorMode.py (35 
of 2863)
PASS: lldb-api :: commands/expression/call-function/TestCallBuiltinFunction.py 
(36 of 2863)
PASS: lldb-api :: 
commands/expression/call-function/TestCallStdStringFunction.py (37 of 2863)
PASS: lldb-api :: commands/expression/call-function/TestCallStopAndContinue.py 
(38 of 2863)
PASS: lldb-api :: commands/expression/call-restarts/TestCallThatRestarts.py (39 
of 2863)
PASS: lldb-api :: 
commands/expression/call-function/TestCallUserDefinedFunction.py (40 of 2863)

```



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


[clang] [OpenMP] Change default version to OMP6.0. (PR #122108)

2025-01-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

Not sure this level of support is enough to make 6.0 the default version. We're 
missing support for some 5.2 features still

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

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

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

1 more question on the semantics + a typo, but the code LGTM.

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


[clang] [llvm] [Clang] Add __builtin_assume_dereferenceable to encode deref assumption. (PR #121789)

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


@@ -2761,6 +2761,41 @@ etc.).
 
 Query for this feature with 
``__has_builtin(__builtin_assume_separate_storage)``.
 
+``__builtin_assume_dereferenceable``
+-
+
+``__builtin_assume_derefernceable`` is used to provide the optimizer with the

erichkeane wrote:

```suggestion
``__builtin_assume_dereferenceable`` is used to provide the optimizer with the
```

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


[clang] [clang-tools-extra] [clang] Avoid re-evaluating field bitwidth (PR #117732)

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

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-aarch64-ubuntu` 
running on `linaro-lldb-aarch64-ubuntu` while building 
`clang-tools-extra,clang` at step 6 "test".

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


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

```
Step 6 (test) failure: build (failure)
...
PASS: lldb-api :: commands/command/script/import/TestImport.py (24 of 2064)
PASS: lldb-api :: commands/command/script_alias/TestCommandScriptAlias.py (25 
of 2064)
PASS: lldb-api :: commands/command/source/TestCommandSource.py (26 of 2064)
PASS: lldb-api :: commands/command/backticks/TestBackticksInAlias.py (27 of 
2064)
PASS: lldb-api :: commands/disassemble/basic/TestFrameDisassemble.py (28 of 
2064)
PASS: lldb-api :: commands/disassemble/basic/TestDisassembleBreakpoint.py (29 
of 2064)
PASS: lldb-api :: commands/expression/calculator_mode/TestCalculatorMode.py (30 
of 2064)
PASS: lldb-api :: 
commands/expression/anonymous-struct/TestCallUserAnonTypedef.py (31 of 2064)
PASS: lldb-api :: 
commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py
 (32 of 2064)
UNRESOLVED: lldb-api :: commands/expression/bitfield_enums/TestBitfieldEnums.py 
(33 of 2064)
 TEST 'lldb-api :: 
commands/expression/bitfield_enums/TestBitfieldEnums.py' FAILED 

Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/dotest.py
 -u CXXFLAGS -u CFLAGS --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/include 
--env LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin 
--arch aarch64 --build-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/dsymutil 
--make /usr/bin/gmake --llvm-tools-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin --lldb-obj-root 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/tools/lldb --lldb-libs-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/commands/expression/bitfield_enums
 -p TestBitfieldEnums.py
--
Exit Code: -6

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
81fc3add1e627c23b7270fe2739cdacc09063e54)
  clang revision 81fc3add1e627c23b7270fe2739cdacc09063e54
  llvm revision 81fc3add1e627c23b7270fe2739cdacc09063e54

--
Command Output (stderr):
--
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_bitfield_enums_dsym (TestBitfieldEnums.TestBitfieldEnum) (test case does 
not fall in any category of interest for this run) 
python3.10: ../llvm-project/clang/lib/AST/Decl.cpp:4604: unsigned int 
clang::FieldDecl::getBitWidthValue() const: Assertion 
`isa(getBitWidth())' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace.
Stack dump:
0.   parser at end of file
1.  :43:1: Generating code for declaration 
'$__lldb_expr'
  #0 0x7a51ddc0 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
Signals.cpp:0:0
  #1 0x7a51be1c llvm::sys::RunSignalHandlers() Signals.cpp:0:0
  #2 0x7a51e4d0 SignalHandler(int) Signals.cpp:0:0
  #3 0x814337dc (linux-vdso.so.1+0x7dc)
  #4 0x811bf200 __pthread_kill_implementation 
./nptl/./nptl/pthread_kill.c:44:76
  #5 0x8117a67c gsignal ./signal/../sysdeps/posix/raise.c:27:6
  #6 0x81167130 abort ./stdlib/./stdlib/abort.c:81:7
  #7 0x81173fd0 __assert_fail_base ./assert/./assert/assert.c:89:7
  #8 0x81174040 __assert_perror_fail 
./assert/./assert/assert-perr.c:31:1
  #9 0x7e00b5b4 clang::FieldDecl::getBitWidthValue() const Decl.cpp:0:0
 #10 0x7e446dc8 (anonymous 
namespace)::ItaniumRecordLayoutBuilder::LayoutField(clang::FieldDecl const*, 
bool) RecordLayoutBuilder.cpp:0:0
 #11 0x7e4443e4 (anonymous 
namespace)::ItaniumRecordLayoutBuilder::LayoutFields(clang::RecordDecl const*) 
RecordLayoutBuilder.cpp:0:0
 #12 0x7e43c99c clang::ASTContext::getASTRecordLayout(clang::RecordDecl 
const*) const RecordLayoutBuilder.cpp:0:0
 #13 0x7c228f38 
lldb_private::ClangASTImporter::importRecordLayoutFromOrigin(clang::RecordDecl 
const*, unsigned long&, unsigned long&, llvm::Den

[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Steven Perron via cfe-commits


@@ -118,6 +118,10 @@ let TargetPrefix = "spv" in {
   : DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_any_ty, llvm_i8_ty],
   [IntrInaccessibleMemOrArgMemOnly]>;
 
+  def int_spv_resource_getpointer

s-perron wrote:

That proposal is still marked as in progress. I also want to keep the change 
smaller by doing one thing. We can rename it later.

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


[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-01-08 Thread Dan Liew via cfe-commits


@@ -19,13 +19,12 @@ struct on_member_pointer_complete_ty {
 };
 
 struct on_member_pointer_incomplete_ty {
-  struct size_unknown * buf __counted_by(count); // 
expected-error{{'counted_by' cannot be applied to a pointer with pointee of 
unknown size because 'struct size_unknown' is an incomplete type}}
+  struct size_unknown * buf __counted_by(count); // ok

delcypher wrote:

@AaronBallman I should have also noted the current design also allows for 
headers that deliberately don't provide complete types to reduce compile times 
which I believe is fairly common practice.

E.g.

```
// some_data.h

struct SomeData {
 int value;
};

// list_handle.h

// Forward declare to avoid needing to include `some_data.h`
struct SomeData;

struct ListHandle {
  struct SomeData* __counted_by(count) items;
  size_t count;
};
```


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


[clang] [llvm] [HLSL] Add SPIR-V version of getPointer. (PR #121963)

2025-01-08 Thread Steven Perron via cfe-commits


@@ -118,6 +118,10 @@ let TargetPrefix = "spv" in {
   : DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_any_ty, llvm_i8_ty],
   [IntrInaccessibleMemOrArgMemOnly]>;
 
+  def int_spv_resource_getpointer

s-perron wrote:

Also, the current name follows the rules it just does not match the proposed 
name.

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


[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-01-08 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:

@AaronBallman Just drawing attention to this reply. For some reason it isn't 
showing up in the conversation tab (I think it's [this 
problem](https://github.com/orgs/community/discussions/6893#discussioncomment-8309254))

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


[clang] [clang-tools-extra] [clang] Avoid re-evaluating field bitwidth (PR #117732)

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

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-x86_64-debian` 
running on `lldb-x86_64-debian` while building `clang-tools-extra,clang` at 
step 6 "test".

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


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

```
Step 6 (test) failure: build (failure)
...
14.724 [1/2/71] Linking CXX executable 
tools/lldb/unittests/SymbolFile/DWARF/SymbolFileDWARFTests
16.219 [1/1/72] Linking CXX executable bin/lldb-test
16.219 [0/1/72] Running lldb lit test suite
llvm-lit: 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using clang: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang
llvm-lit: 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld.lld: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/ld.lld
llvm-lit: 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/lld-link
llvm-lit: 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/ld64.lld
llvm-lit: 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/wasm-ld
-- Testing: 2738 tests, 72 workers --
UNRESOLVED: lldb-api :: 
functionalities/gdb_remote_client/TestXMLRegisterFlags.py (1 of 2738)
 TEST 'lldb-api :: 
functionalities/gdb_remote_client/TestXMLRegisterFlags.py' FAILED 

Script:
--
/usr/bin/python3 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/API/dotest.py -u 
CXXFLAGS -u CFLAGS --env 
LLVM_LIBS_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/./lib --env 
LLVM_INCLUDE_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/include --env 
LLVM_TOOLS_DIR=/home/worker/2.0.1/lldb-x86_64-debian/build/./bin --arch x86_64 
--build-dir /home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/worker/2.0.1/lldb-x86_64-debian/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/worker/2.0.1/lldb-x86_64-debian/build/./bin/lldb --compiler 
/home/worker/2.0.1/lldb-x86_64-debian/build/./bin/clang --dsymutil 
/home/worker/2.0.1/lldb-x86_64-debian/build/./bin/dsymutil --make 
/usr/bin/gmake --llvm-tools-dir 
/home/worker/2.0.1/lldb-x86_64-debian/build/./bin --lldb-obj-root 
/home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb --lldb-libs-dir 
/home/worker/2.0.1/lldb-x86_64-debian/build/./lib -t 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/API/functionalities/gdb_remote_client
 -p TestXMLRegisterFlags.py
--
Exit Code: -6

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
81fc3add1e627c23b7270fe2739cdacc09063e54)
  clang revision 81fc3add1e627c23b7270fe2739cdacc09063e54
  llvm revision 81fc3add1e627c23b7270fe2739cdacc09063e54
python3  ProcessGDBRemote::ConnectToDebugserver Connecting to 
connect://[::1]:34261
python3  <   1> send packet: +
python3  history[1] tid=0x3c26c <   1> send packet: +
python3  <  19> send packet: $QStartNoAckMode#b0
python3  <   1> read packet: +
python3  <   6> read packet: $OK#9a
python3  <   1> send packet: +
python3  < 104> send packet: 
$qSupported:xmlRegisters=i386,arm,mips,arc;multiprocess+;fork-events+;vfork-events+;swbreak+;hwbreak+#cd
python3  <  57> read packet: 
$qXfer:features:read+;PacketSize=3fff;QStartNoAckMode+#86
python3  <  26> send packet: $QThreadSuffixSupported#e4
python3  <   4> read packet: $#00
python3  <  27> send packet: $QListThreadsInStopReply#21
python3  <   4> read packet: $#00
python3  <  13> send packet: $qHostInfo#9b
python3  <  28> read packet: $ptrsize:8;endian:little;#30
python3  <  10> send packet: $vCont?#49
python3  <   4> read packet: $#00
python3  <  27> send packet: $qVAttachOrWaitSupported#38
python3  <   4> read packet: $#00
python3  <  23> send packet: $QEnableErrorStrings#8c
python3  <   6> read packet: $OK#9a
python3  ProcessGDBRemote::StartAsyncThread ()
python3  <  16> send packet: $qProcessInfo#dc
b-remote.async>  ProcessGDBRemote::AsyncThread(pid = 0) thread starting...
b-remote.async>  ProcessGDBRemote::AsyncThread(pid = 0) listener.WaitForEvent 
(NULL, event_sp)...
python3  <   4> read packet: $#00
python3  <   6> send packet: $qC#b4

```



https://github.com/llvm/llvm-project/pull/117732
___
cfe-commits m

[clang] [clang] constexpr atomic builtins (__c11_atomic_OP and __atomic_OP) (PR #98756)

2025-01-08 Thread Aaron Ballman via cfe-commits
Hana =?utf-8?q?Dusíková?= ,
Hana =?utf-8?q?Dusíková?= 
Message-ID:
In-Reply-To: 



@@ -17893,4 +18005,425 @@ std::optional 
EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
   IsWithinLifetimeHandler handler{Info};
   return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
 }
+
 } // namespace
+
+static bool EvaluateAtomicOrder(const AtomicExpr *E, EvalInfo &Info) {
+  // We need to evaluate Order argument(s), but we ignore it as constant
+  // evaluation is single threaded.
+  APSInt OrderIgnoredResult;
+
+  if (E->getOp() != AtomicExpr::AO__c11_atomic_init) {
+const Expr *OrderSuccess = E->getOrder();
+if (OrderSuccess &&
+!EvaluateInteger(OrderSuccess, OrderIgnoredResult, Info))
+  return false;
+  }
+
+  if (E->isCmpXChg()) {
+const Expr *OrderFail = E->getOrderFail();
+if (!EvaluateInteger(OrderFail, OrderIgnoredResult, Info))
+  return false;
+  }
+
+  return true;
+}
+
+static bool EvaluateAtomicLoad(const AtomicExpr *E, APValue &Result,
+   EvalInfo &Info) {
+  LValue AtomicStorageLV;
+
+  if (!EvaluatePointer(E->getPtr(), AtomicStorageLV, Info))
+return false;
+
+  return handleLValueToRValueConversion(Info, E->getPtr(), E->getValueType(),
+AtomicStorageLV, Result);
+}
+
+static bool EvaluateAtomicLoadInto(const AtomicExpr *E, EvalInfo &Info) {
+  APValue LocalResult;
+
+  if (!EvaluateAtomicLoad(E, LocalResult, Info))
+return false;
+
+  assert(E->getVal1()->getType()->isPointerType());
+  QualType PointeeTy = E->getVal1()->getType()->getPointeeType();
+  LValue PointeeLV;
+
+  if (!EvaluatePointer(E->getVal1(), PointeeLV, Info))
+return false;
+
+  if (!handleAssignment(Info, E->getVal1(), PointeeLV, PointeeTy, LocalResult))
+return false;
+
+  return true;
+}
+
+static bool EvaluateAtomicStore(const AtomicExpr *E, EvalInfo &Info) {
+  LValue AtomicStorageLV;
+
+  if (!EvaluatePointer(E->getPtr(), AtomicStorageLV, Info))
+return false;
+
+  APValue ProvidedValue;
+
+  // GCC's atomic_store takes pointer to value, not value itself.
+  if (E->getOp() == AtomicExpr::AO__atomic_store) {
+LValue ProvidedLV;
+if (!EvaluatePointer(E->getVal1(), ProvidedLV, Info))
+  return false;
+
+if (!handleLValueToRValueConversion(Info, E->getVal1(),
+E->getVal1()->getType(), ProvidedLV,
+ProvidedValue))
+  return false;
+
+  } else {
+if (!Evaluate(ProvidedValue, Info, E->getVal1()))
+  return false;
+  }
+  if (!handleAssignment(Info, E, AtomicStorageLV, E->getValueType(),
+ProvidedValue))
+return false;
+
+  return true;
+}
+
+static bool EvaluateAtomicExchange(const AtomicExpr *E, APValue &Result,
+   EvalInfo &Info) {
+  assert(E->getOp() == AtomicExpr::AO__c11_atomic_exchange ||
+ E->getOp() == AtomicExpr::AO__atomic_exchange_n);
+
+  if (!EvaluateAtomicLoad(E, Result, Info))
+return false;
+
+  if (!EvaluateAtomicStore(E, Info))
+return false;
+
+  return true;
+}
+
+static bool EvaluateAtomicExchangeInto(const AtomicExpr *E, EvalInfo &Info) {
+  assert(E->getOp() == AtomicExpr::AO__atomic_exchange);
+  // Implementation of GCC's exchange (non _n version).
+  LValue AtomicStorageLV;
+  if (!EvaluatePointer(E->getPtr(), AtomicStorageLV, Info))
+return false;
+
+  // Read previous value.
+  APValue PreviousValue;
+  if (!handleLValueToRValueConversion(Info, E->getPtr(), E->getValueType(),
+  AtomicStorageLV, PreviousValue))
+return false;
+
+  // Get value pointer by argument of the exchange operation.
+  LValue ProvidedLV;
+  if (!EvaluatePointer(E->getVal1(), ProvidedLV, Info))
+return false;
+
+  APValue ProvidedValue;
+  if (!handleLValueToRValueConversion(Info, E->getVal1(),
+  E->getVal1()->getType(), ProvidedLV,
+  ProvidedValue))
+return false;
+
+  // Store provided value to atomic value.
+  if (!handleAssignment(Info, E, AtomicStorageLV, E->getValueType(),
+ProvidedValue))
+return false;
+
+  // Store previous value in output pointer.
+  assert(E->getVal2()->getType()->isPointerType());
+  QualType PointeeTy = E->getVal2()->getType()->getPointeeType();
+  LValue PointeeLV;
+
+  if (!EvaluatePointer(E->getVal2(), PointeeLV, Info))
+return false;
+
+  if (!handleAssignment(Info, E->getVal2(), PointeeLV, PointeeTy,
+PreviousValue))
+return false;
+
+  return true;
+}
+
+static bool EvaluateAtomicFetchOp(const AtomicExpr *E, APValue &Result,
+  EvalInfo &Info, bool StoreToResultAfter) {
+  // Read the atomic.
+  LValue AtomicStorageLV;
+  QualType AtomicValueTy = E->getValueType();
+  if (!EvaluatePointer(E->getPtr(), AtomicStorageLV, Info))
+return

[clang] [clang] constexpr atomic builtins (__c11_atomic_OP and __atomic_OP) (PR #98756)

2025-01-08 Thread Aaron Ballman via cfe-commits
Hana =?utf-8?q?Dusíková?= ,
Hana =?utf-8?q?Dusíková?= 
Message-ID:
In-Reply-To: 


https://github.com/AaronBallman commented:

Thank you for working on this! Please be sure to also add release notes to 
`clang/docs/ReleaseNotes.rst` so users know about the new functionality. Also, 
this should update `clang/www/cxx_status.html` to mark that we now implement 
P3309.

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


[clang] b66f6b2 - Revert #116331 & #121852 (#122105)

2025-01-08 Thread via cfe-commits

Author: Chris B
Date: 2025-01-08T08:55:02-06:00
New Revision: b66f6b25cb5107d4c8f78d13b08d2bdba39ad919

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

LOG: Revert #116331 & #121852 (#122105)

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaStmtAttr.cpp
llvm/include/llvm/IR/IntrinsicsSPIRV.td
llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
llvm/lib/Target/SPIRV/SPIRVInstructionSelector.cpp
llvm/lib/Target/SPIRV/SPIRVStructurizer.cpp

Removed: 
clang/test/AST/HLSL/HLSLControlFlowHint.hlsl
clang/test/CodeGenHLSL/HLSLControlFlowHint.hlsl
llvm/test/CodeGen/DirectX/HLSLControlFlowHint.ll
llvm/test/CodeGen/SPIRV/structurizer/HLSLControlFlowHint-pass-check.ll
llvm/test/CodeGen/SPIRV/structurizer/HLSLControlFlowHint.ll



diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 6d7f65ab2c6135..12faf06597008e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4335,16 +4335,6 @@ def HLSLLoopHint: StmtAttr {
   let Documentation = [HLSLLoopHintDocs, HLSLUnrollHintDocs];
 }
 
-def HLSLControlFlowHint: StmtAttr {
-  /// [branch]
-  /// [flatten]
-  let Spellings = [Microsoft<"branch">, Microsoft<"flatten">];
-  let Subjects = SubjectList<[IfStmt],
-  ErrorDiag, "'if' statements">;
-  let LangOpts = [HLSL];
-  let Documentation = [InternalOnly];
-}
-
 def CapturedRecord : InheritableAttr {
   // This attribute has no spellings as it is only ever created implicitly.
   let Spellings = [];

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index c8ff48fc733125..a87c50b8a1cbbf 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -757,8 +757,6 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
   bool noinline = false;
   bool alwaysinline = false;
   bool noconvergent = false;
-  HLSLControlFlowHintAttr::Spelling flattenOrBranch =
-  HLSLControlFlowHintAttr::SpellingNotCalculated;
   const CallExpr *musttail = nullptr;
 
   for (const auto *A : S.getAttrs()) {
@@ -790,9 +788,6 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
 Builder.CreateAssumption(AssumptionVal);
   }
 } break;
-case attr::HLSLControlFlowHint: {
-  flattenOrBranch = 
cast(A)->getSemanticSpelling();
-} break;
 }
   }
   SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
@@ -800,7 +795,6 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
   SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline);
   SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent);
   SaveAndRestore save_musttail(MustTailCall, musttail);
-  SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch);
   EmitStmt(S.getSubStmt(), S.getAttrs());
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 067ff55b87ae63..af58fa64f86585 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -40,7 +40,6 @@
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Dominators.h"
 #include "llvm/IR/FPEnv.h"
-#include "llvm/IR/Instruction.h"
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
@@ -2084,29 +2083,7 @@ void CodeGenFunction::EmitBranchOnBoolExpr(
 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
   }
 
-  llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, 
FalseBlock,
-   Weights, Unpredictable);
-  switch (HLSLControlFlowAttr) {
-  case HLSLControlFlowHintAttr::Microsoft_branch:
-  case HLSLControlFlowHintAttr::Microsoft_flatten: {
-llvm::MDBuilder MDHelper(CGM.getLLVMContext());
-
-llvm::ConstantInt *BranchHintConstant =
-HLSLControlFlowAttr ==
-HLSLControlFlowHintAttr::Spelling::Microsoft_branch
-? llvm::ConstantInt::get(CGM.Int32Ty, 1)
-: llvm::ConstantInt::get(CGM.Int32Ty, 2);
-
-SmallVector Vals(
-{MDHelper.createString("hlsl.controlflow.hint"),
- MDHelper.createConstant(BranchHintConstant)});
-BrInst->setMetadata("hlsl.controlflow.hint",
-llvm::MDNode::get(CGM.getLLVMContext(), Vals));
-break;
-  }
-  case HLSLControlFlowHintAttr::SpellingNotCalculated:
-break;
-  }
+  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
 }
 
 /// ErrorUnsupported - Print out an error that codegen doesn't support the

dif

[clang] [llvm] Revert #116331 & #121852 (PR #122105)

2025-01-08 Thread Chris B via cfe-commits

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


[clang] [llvm] [Arm] Generate explicit bitcasts in NeonEmitter (PR #121802)

2025-01-08 Thread Momchil Velikov via cfe-commits


@@ -1382,14 +1382,15 @@ void Intrinsic::emitBodyAsBuiltinCall() {
 Type CastToType = T;
 
 // Check if an explicit cast is needed.
-if (CastToType.isVector() &&
-(LocalCK == ClassB || (T.isHalf() && !T.isScalarForMangling( {
-  CastToType.makeInteger(8, true);
-  Arg = "(" + CastToType.str() + ")" + Arg;
-} else if (CastToType.isVector() && LocalCK == ClassI) {
-  if (CastToType.isInteger())
-CastToType.makeSigned();
-  Arg = "(" + CastToType.str() + ")" + Arg;
+if (CastToType.isVector()) {

momchil-velikov wrote:

It's an omission. Also the return value cast, it's either redundant or needs to 
be a bitcast too. Will fix.

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


[clang] [CUDA][HIP] Fix overriding of constexpr virtual function (PR #121986)

2025-01-08 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu updated 
https://github.com/llvm/llvm-project/pull/121986

>From ae55b59e9e7d944b02ce0059f879718fd733c301 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Tue, 7 Jan 2025 13:52:09 -0500
Subject: [PATCH] [CUDA][HIP] Fix overriding of constexpr virtual function

In C++20 constexpr virtual function is allowed. In C++17 although non-pure 
virtual function
is not allowed to be constexpr, pure virtual function is allowed to be 
constexpr and is
allowed to be overriden by non-constexpr virtual function in the derived class.

The following code compiles as C++:

```
class A
{
public:
constexpr virtual int f() = 0;
};

class B : public A
{
public:
int f() override
{
return 42;
}
};
```

However, it fails to compile as CUDA or HIP code. The reason: A::f() is 
implicitly
host device function whereas B::f() is a host function. Since they have 
different
targets, clang does not treat B::f() as an override of A::f(). Instead, it 
treats
B::f() as a name-hiding non-virtual function for A::f(), and diagnoses it.

This causes any CUDA/HIP program using C++ standard header file 
from g++-13 to fail to compile since such usage patten show up there:

```
/usr/lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/format:3564:34: 
error: non-virtual member function marked 'override' hides virtual member 
function
 3564 |   _M_format_arg(size_t __id) override
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/format:3538:30: 
note: hidden overloaded virtual function 
'std::__format::_Scanner::_M_format_arg' declared here
 3538 |   constexpr virtual void _M_format_arg(size_t __id) = 0;
  |  ^
```

This is a serious issue and there is no workaround.

This patch allows non-constexpr function to override constexpr virtual function
for CUDA and HIP. This should be OK since non-constexpr function without 
explicit
host or device attribute can only be called in host functions.

Fixes: SWDEV-507350
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/lib/Sema/SemaOverload.cpp   | 21 +-
 clang/test/SemaCUDA/constexpr-virtual-func.cu | 28 +++
 3 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCUDA/constexpr-virtual-func.cu

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 93915e5db7d131..6a3da7f38d9757 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1053,6 +1053,7 @@ RISC-V Support
 
 CUDA/HIP Language Changes
 ^
+- Fixed a bug about overriding a constexpr pure-virtual member function with a 
non-constexpr virtual member function which causes compilation failure when 
including standard C++ header `format`.
 
 CUDA Support
 
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 7589701fb81de9..65530d43a9bb60 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1309,6 +1309,13 @@ Sema::CheckOverload(Scope *S, FunctionDecl *New, const 
LookupResult &Old,
   return Ovl_Overload;
 }
 
+template  static bool hasExplicitAttr(const FunctionDecl *D) {
+  assert(D && "function delc should not be null");
+  if (auto *A = D->getAttr())
+return !A->isImplicit();
+  return false;
+}
+
 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
  FunctionDecl *Old,
  bool UseMemberUsingDeclRules,
@@ -1583,6 +1590,7 @@ static bool IsOverloadOrOverrideImpl(Sema &SemaRef, 
FunctionDecl *New,
   return true;
   }
 
+  // At this point, it is known that the two functions have the same signature.
   if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
 // Don't allow overloading of destructors.  (In theory we could, but it
 // would be a giant change to clang.)
@@ -1595,8 +1603,19 @@ static bool IsOverloadOrOverrideImpl(Sema &SemaRef, 
FunctionDecl *New,
 
 // Allow overloading of functions with same signature and different 
CUDA
 // target attributes.
-if (NewTarget != OldTarget)
+if (NewTarget != OldTarget) {
+  // Special case: non-constexpr function is allowed to override
+  // constexpr virtual function
+  if (OldMethod && NewMethod && OldMethod->isVirtual() &&
+  OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
+  !hasExplicitAttr(Old) &&
+  !hasExplicitAttr(Old) &&
+  !hasExplicitAttr(New) &&
+  !hasExplicitAttr(New)) {
+return false;
+  }
   return true;
+}
   }
 }
   }
diff --git a/clang/test/SemaCUDA/constexpr-virtual-func.cu 
b/clang/test/SemaCUDA/constexpr-virtual-func.cu
new file mode 100644
index 00..89d909181cd94d
--- /dev/null
+++ b/clang/test/SemaCUDA/constexpr-virtual-func

[clang] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`. (PR #122149)

2025-01-08 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/122149

>From 3329b7ae7dc6044f6563f218c65f6af7498290f0 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Wed, 8 Jan 2025 12:19:53 -0600
Subject: [PATCH] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`.

Summary:
Currently we prevent the following from working. However, it is
completely reasonable to be able to target the files individually.
```
$ clang --target=amdgcn-amd-amdhsa -fopenmp
```

This patch lifts this restriction, allowing individual files to be
compiled as standalone OpenMP without the extra offloading overhead. The
main motivation behind this is to update the build of the OpenMP
DeviceRTL. Currently, we do `--offload-device-only -S -emit-llvm` which
is just a hackier version of `-fopenmp -flto -c`.

This patch allows the following to work.
```
$ clang omp.c -fopenmp --target=amdgcn-amd-amdhsa -flto -c
$ clang offload.c -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xoffload-linker 
omp.o
$ ./a.out
```
---
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |   3 -
 clang/lib/CodeGen/CGStmtOpenMP.cpp|   3 +-
 clang/lib/CodeGen/CodeGenModule.cpp   |   2 -
 clang/lib/Frontend/CompilerInvocation.cpp |  13 --
 clang/test/OpenMP/gpu_target.cpp  | 220 ++
 clang/test/OpenMP/target_messages.cpp |   3 -
 6 files changed, 222 insertions(+), 22 deletions(-)
 create mode 100644 clang/test/OpenMP/gpu_target.cpp

diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 756f0482b8ea72..1ad4b4b0e8a7fc 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -870,9 +870,6 @@ CGOpenMPRuntimeGPU::CGOpenMPRuntimeGPU(CodeGenModule &CGM)
   hasRequiresUnifiedSharedMemory(), /*HasRequiresDynamicAllocators*/ 
false);
   OMPBuilder.setConfig(Config);
 
-  if (!CGM.getLangOpts().OpenMPIsTargetDevice)
-llvm_unreachable("OpenMP can only handle device code.");
-
   if (CGM.getLangOpts().OpenMPCUDAMode)
 CurrentDataSharingMode = CGOpenMPRuntimeGPU::DS_CUDA;
 
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 6cb37b20b7aeee..950ed173aecf3a 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -6801,7 +6801,8 @@ static void emitCommonOMPTargetDirective(CodeGenFunction 
&CGF,
   CodeGenModule &CGM = CGF.CGM;
 
   // On device emit this construct as inlined code.
-  if (CGM.getLangOpts().OpenMPIsTargetDevice) {
+  if (CGM.getLangOpts().OpenMPIsTargetDevice ||
+  CGM.getOpenMPRuntime().isGPU()) {
 OMPLexicalScope Scope(CGF, S, OMPD_target);
 CGM.getOpenMPRuntime().emitInlinedDirective(
 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 5f15f0f48c54e4..26abd9a60632ae 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -483,8 +483,6 @@ void CodeGenModule::createOpenMPRuntime() {
   case llvm::Triple::nvptx:
   case llvm::Triple::nvptx64:
   case llvm::Triple::amdgcn:
-assert(getLangOpts().OpenMPIsTargetDevice &&
-   "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
 break;
   default:
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index d711df02ce9503..d2df51593ff62b 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -4210,19 +4210,6 @@ bool CompilerInvocation::ParseLangArgs(LangOptions 
&Opts, ArgList &Args,
 Args, OPT_fopenmp_version_EQ,
 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
   Opts.OpenMP = Version;
-// Provide diagnostic when a given target is not expected to be an OpenMP
-// device or host.
-if (!Opts.OpenMPIsTargetDevice) {
-  switch (T.getArch()) {
-  default:
-break;
-  // Add unsupported host targets here:
-  case llvm::Triple::nvptx:
-  case llvm::Triple::nvptx64:
-Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
-break;
-  }
-}
   }
 
   // Set the flag to prevent the implementation from emitting device exception
diff --git a/clang/test/OpenMP/gpu_target.cpp b/clang/test/OpenMP/gpu_target.cpp
new file mode 100644
index 00..3d5a47d7050436
--- /dev/null
+++ b/clang/test/OpenMP/gpu_target.cpp
@@ -0,0 +1,220 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --check-globals all --include-generated-funcs --replace-value-regex 
"__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" 
"pl_cond[.].+[.|,]" --version 5
+// expected-no-diagnostics
+
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple 
amdgcn-amd-amdhsa -emit-llvm %s -o - | F

[clang] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`. (PR #122149)

2025-01-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

> What code generation path would be used in this case? The GPU code generation 
> or regular host OpenMP?

gpu device code

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


[clang] [test][Driver][clang] Fix darwin-embedded-search-paths.c when CLANG_DEFAULT_CXX_STDLIB is libc++ (PR #122145)

2025-01-08 Thread Ian Anderson via cfe-commits


@@ -1,3 +1,4 @@
+// REQUIRES: default-cxx-stdlib=libstdc++

ian-twilightcoder wrote:

I guess if there was a different cxxlib we would want another version of the 
test to check its paths anyway

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


[clang] [Driver][UEFI] Enable Microsoft extensions (PR #121875)

2025-01-08 Thread Tristan Ross via cfe-commits

RossComputerGuy wrote:

> @RossComputerGuy FYI

Already have seen this, I'm not sure I understand what the flag does exactly. 
I've got LLVM libc PR subscriptions so I'll see any future PR's.

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


[clang] [test][Driver][clang] Fix darwin-embedded-search-paths.c when CLANG_DEFAULT_CXX_STDLIB is libc++ (PR #122145)

2025-01-08 Thread Jon Roelofs via cfe-commits


@@ -1,3 +1,4 @@
+// REQUIRES: default-cxx-stdlib=libstdc++

jroelofs wrote:

I think it's fine. I'm not sure `REQUIRES` has a `!=`

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


[clang] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`. (PR #122149)

2025-01-08 Thread Shilei Tian via cfe-commits

shiltian wrote:

I don't think it should be GPU code generation path as there is no explicit 
`target` region used.

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


[clang] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`. (PR #122149)

2025-01-08 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> I don't think it should be GPU code generation path as there is no explicit 
> `target` region used.

it needs to be, otherwise the code generation for things like `#pragma omp 
parallel` will be wrong. The way I see it, the DeviceRTL is `libomp.a` for the 
GPU target, so we need to emit runtime calls for that runtime.

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


[libunwind] [libunwind][cmake] Compile _Unwind* routines with -fexceptions (PR #121819)

2025-01-08 Thread Alex Rønne Petersen via cfe-commits

alexrp wrote:

> > I wonder if it would be less bug-prone in the long term to just build the 
> > whole library with `-fexceptions` instead of trying to apply `-fexceptions` 
> > to _just_ the right files at this point in time. Feels like a brittle 
> > optimization for not much gain?
> 
> This will break MinGW LTO libunwind.

Can you clarify how?

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


[clang] [OpenMP] Allow GPUs to be targeted directly via `-fopenmp`. (PR #122149)

2025-01-08 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> ~I don't think it should be GPU code generation path as there is no explicit 
> `target` region used.~ Probably I missed something here. Do you expect 
> regular OpenMP stuff such as `parallel` region to be emitted in the same way 
> as offloading code?

Yes, the example in the description is how I can see this being used. It 
basically lets us emit GPU code without the build system complications 
introduced by offloading languages (i.e. we no longer need variants or declare 
target.)

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


[clang] 8e65940 - [FMV][AArch64] Simplify version selection according to ACLE. (#121921)

2025-01-08 Thread via cfe-commits

Author: Alexandros Lamprineas
Date: 2025-01-08T18:59:07Z
New Revision: 8e65940161cd5a7dea5896fe4ae057d4cc07c703

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

LOG: [FMV][AArch64] Simplify version selection according to ACLE. (#121921)

Currently, the more features a version has, the higher its priority is.
We are changing ACLE https://github.com/ARM-software/acle/pull/370 as
follows:

"Among any two versions, the higher priority version is determined by
 identifying the highest priority feature that is specified in exactly
 one of the versions, and selecting that version."

Added: 
clang/test/CodeGen/AArch64/fmv-priority.c
llvm/include/llvm/TargetParser/AArch64FeatPriorities.inc

Modified: 
clang/include/clang/Basic/TargetInfo.h
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/lib/Basic/Targets/RISCV.cpp
clang/lib/Basic/Targets/RISCV.h
clang/lib/Basic/Targets/X86.cpp
clang/lib/Basic/Targets/X86.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/attr-target-clones-aarch64.c
clang/test/CodeGen/attr-target-version.c
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/lib/Target/AArch64/AArch64FMV.td
llvm/lib/TargetParser/AArch64TargetParser.cpp
llvm/utils/TableGen/Basic/ARMTargetDefEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index f2905f30a7c34b..43c09cf1f973e3 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1531,7 +1531,7 @@ class TargetInfo : public TransferrableTargetInfo,
 
   // Return the target-specific priority for features/cpus/vendors so
   // that they can be properly sorted for checking.
-  virtual unsigned getFMVPriority(ArrayRef Features) const {
+  virtual uint64_t getFMVPriority(ArrayRef Features) const {
 return 0;
   }
 

diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 53e102bbe44687..2b4b954d0c27ad 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -714,7 +714,7 @@ AArch64TargetInfo::getVScaleRange(const LangOptions 
&LangOpts) const {
   return std::nullopt;
 }
 
-unsigned AArch64TargetInfo::getFMVPriority(ArrayRef Features) const 
{
+uint64_t AArch64TargetInfo::getFMVPriority(ArrayRef Features) const 
{
   return llvm::AArch64::getFMVPriority(Features);
 }
 

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 68a8b1ebad8cde..4e927c0953b1fc 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -137,7 +137,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   void fillValidCPUList(SmallVectorImpl &Values) const override;
   bool setCPU(const std::string &Name) override;
 
-  unsigned getFMVPriority(ArrayRef Features) const override;
+  uint64_t getFMVPriority(ArrayRef Features) const override;
 
   bool useFP16ConversionIntrinsics() const override {
 return false;

diff  --git a/clang/lib/Basic/Targets/RISCV.cpp 
b/clang/lib/Basic/Targets/RISCV.cpp
index a541dfedc9b8e1..db23b0c2283385 100644
--- a/clang/lib/Basic/Targets/RISCV.cpp
+++ b/clang/lib/Basic/Targets/RISCV.cpp
@@ -489,7 +489,7 @@ ParsedTargetAttr RISCVTargetInfo::parseTargetAttr(StringRef 
Features) const {
   return Ret;
 }
 
-unsigned RISCVTargetInfo::getFMVPriority(ArrayRef Features) const {
+uint64_t RISCVTargetInfo::getFMVPriority(ArrayRef Features) const {
   // Priority is explicitly specified on RISC-V unlike on other targets, where
   // it is derived by all the features of a specific version. Therefore if a
   // feature contains the priority string, then return it immediately.
@@ -501,7 +501,7 @@ unsigned 
RISCVTargetInfo::getFMVPriority(ArrayRef Features) const {
   Feature = RHS;
 else
   continue;
-unsigned Priority;
+uint64_t Priority;
 if (!Feature.getAsInteger(0, Priority))
   return Priority;
   }

diff  --git a/clang/lib/Basic/Targets/RISCV.h b/clang/lib/Basic/Targets/RISCV.h
index 68f10e74ba98c3..bb3f3a5cda7c65 100644
--- a/clang/lib/Basic/Targets/RISCV.h
+++ b/clang/lib/Basic/Targets/RISCV.h
@@ -122,7 +122,7 @@ class RISCVTargetInfo : public TargetInfo {
   void fillValidTuneCPUList(SmallVectorImpl &Values) const override;
   bool supportsTargetAttributeTune() const override { return true; }
   ParsedTargetAttr parseTargetAttr(StringRef Str) const override;
-  unsigned getFMVPriority(ArrayRef Features) const override;
+  uint64_t getFMVPriority(ArrayRef Features) const override;
 
   std::pair hardwareInterferenceSizes() const override {
 return std::make_pair(32, 32);

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Bas

[clang] [clang] [ARM] Explicitly enable NEON for Windows/Darwin targets (PR #122095)

2025-01-08 Thread Dan Albert via cfe-commits

DanAlbert wrote:

It's over 4 years old so unfortunately I'm probably not much help beyond what's 
already written on the old review/commit. At the time we were still using GAS 
though, so perhaps that made it more meaningful? If vfpv3 was already the 
default FPU for armv7 at the time then it's probable that I just misunderstood.

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


[clang] [flang] [Flang][Driver] Add a flag to control zero initialization of global v… (PR #122144)

2025-01-08 Thread Tarun Prabhu via cfe-commits

tarunprabhu wrote:

> Is the name of the flag alrite?

Haha. You read my mind. I spent some time thinking about it and even consulted 
the Fortran standard. They refer to default initialization as well, so I 
eventually decided that it was ok. Maybe 
`-fno-init-global-without-default-init` is clearer, but it's longer. I was 
thinking of `-fno-init-uninitialized-globals`, which I, a C/C++ programmer, 
find more intuitive. But maybe Fortran programmers are used to thinking of 
"default initialization".


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


[clang] [Clang] disallow attributes after namespace identifier (PR #121614)

2025-01-08 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/121614

>From b8f6ffc0a98a0d3ac55fba4e6ee680f1edea4571 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sat, 4 Jan 2025 02:24:26 +0200
Subject: [PATCH 1/4] [Clang] disallow attributes after namespace identifier

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/Basic/DiagnosticParseKinds.td |  2 ++
 clang/lib/Parse/ParseDeclCXX.cpp  |  9 ++---
 clang/test/Parser/namespace-attributes.cpp| 10 +-
 4 files changed, 15 insertions(+), 8 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e0aef1af2135cd..43a95fd022c070 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -553,6 +553,8 @@ Attribute Changes in Clang
 - Clang now permits the usage of the placement new operator in 
``[[msvc::constexpr]]``
   context outside of the std namespace. (#GH74924)
 
+- Clang now disallows the use of attributes after the namespace name. 
(#GH121407)
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 86fcae209c40db..9d76376cd6b015 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -283,6 +283,8 @@ def err_unexpected_qualified_namespace_alias : Error<
   "namespace alias must be a single identifier">;
 def err_unexpected_nested_namespace_attribute : Error<
   "attributes cannot be specified on a nested namespace definition">;
+def err_attribute_after_namespace : Error<
+  "standard attributes cannot appear after the namespace name">;
 def err_inline_namespace_alias : Error<"namespace alias cannot be inline">;
 def err_namespace_nonnamespace_scope : Error<
   "namespaces can only be defined in global or namespace scope">;
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index f30603feb65c5d..ec87163ffb7cee 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -81,7 +81,7 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
 
   ParsedAttributes attrs(AttrFactory);
 
-  auto ReadAttributes = [&] {
+  auto ReadAttributes = [&](bool TrailingAttrs) {
 bool MoreToParse;
 do {
   MoreToParse = false;
@@ -90,6 +90,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
 MoreToParse = true;
   }
   if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
+if (TrailingAttrs)
+  Diag(Tok.getLocation(), diag::err_attribute_after_namespace);
+
 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
 ? diag::warn_cxx14_compat_ns_enum_attribute
 : diag::ext_ns_enum_attribute)
@@ -100,7 +103,7 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
 } while (MoreToParse);
   };
 
-  ReadAttributes();
+  ReadAttributes(/*TrailingAttrs*/ false);
 
   if (Tok.is(tok::identifier)) {
 Ident = Tok.getIdentifierInfo();
@@ -126,7 +129,7 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
 }
   }
 
-  ReadAttributes();
+  ReadAttributes(/*TrailingAttrs*/ true);
 
   SourceLocation attrLoc = attrs.Range.getBegin();
 
diff --git a/clang/test/Parser/namespace-attributes.cpp 
b/clang/test/Parser/namespace-attributes.cpp
index 9f925b742dfebd..8a873c55c5d633 100644
--- a/clang/test/Parser/namespace-attributes.cpp
+++ b/clang/test/Parser/namespace-attributes.cpp
@@ -16,11 +16,11 @@ namespace [[]] __attribute__(()) A
 {
 }
 
-namespace A __attribute__(()) [[]]
+namespace A __attribute__(()) [[]] // expected-error {{standard attributes 
cannot appear after the namespace name}}
 {
 }
 
-namespace A [[]] __attribute__(())
+namespace A [[]] __attribute__(()) // expected-error {{standard attributes 
cannot appear after the namespace name}}
 {
 }
 
@@ -28,14 +28,14 @@ namespace [[]] A __attribute__(())
 {
 }
 
-namespace __attribute__(()) A [[]]
+namespace __attribute__(()) A [[]] // expected-error {{standard attributes 
cannot appear after the namespace name}}
 {
 }
 
-namespace A::B __attribute__(()) // expected-error{{attributes cannot be 
specified on a nested namespace definition}}
+namespace A::B __attribute__(()) // expected-error {{attributes cannot be 
specified on a nested namespace definition}}
 {
 }
 
-namespace __attribute__(()) A::B // expected-error{{attributes cannot be 
specified on a nested namespace definition}}
+namespace __attribute__(()) A::B // expected-error {{attributes cannot be 
specified on a nested namespace definition}}
 {
 }

>From b8bf77687644c035683ae64a0a2a8e788ad74a83 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sun, 5 Jan 2025 12:07:40 +0200
Subject: [PATCH 2/4] change param name from TrailingAttrs to
 Che

[clang] [flang] [Flang][Driver] Add a flag to control zero initialization of global v… (PR #122144)

2025-01-08 Thread Tarun Prabhu via cfe-commits

tarunprabhu wrote:

Perhaps leave this up for a bit longer to see if we can think of something 
better. Or others may have some suggestions

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


[clang] [CUDA][HIP] improve error message for missing cmath (PR #122155)

2025-01-08 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-x86

@llvm/pr-subscribers-clang

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

One common error seen in CUDA/HIP compilation is:

fatal error: 'cmath' file not found

which is due to inproper installation of standard C++ libraries.

Since it happens with #include_next, users may feel confusing which cmath is 
not found and how to fix it.

Add an error directive to help users resolve this issue.

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


1 Files Affected:

- (modified) clang/lib/Headers/cuda_wrappers/cmath (+4) 


``diff
diff --git a/clang/lib/Headers/cuda_wrappers/cmath 
b/clang/lib/Headers/cuda_wrappers/cmath
index 45f89beec9b4df..7deca678bf252e 100644
--- a/clang/lib/Headers/cuda_wrappers/cmath
+++ b/clang/lib/Headers/cuda_wrappers/cmath
@@ -24,7 +24,11 @@
 #ifndef __CLANG_CUDA_WRAPPERS_CMATH
 #define __CLANG_CUDA_WRAPPERS_CMATH
 
+#if __has_include_next()
 #include_next 
+#else
+#error "Could not find standard C++ header 'cmath'. Add -v to your compilation 
command to check the include paths being searched. You may need to install the 
appropriate standard C++ library package corresponding to the search path."
+#endif
 
 #if defined(_LIBCPP_STD_VER)
 

``




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


[clang] [CUDA][HIP] improve error message for missing cmath (PR #122155)

2025-01-08 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu created 
https://github.com/llvm/llvm-project/pull/122155

One common error seen in CUDA/HIP compilation is:

fatal error: 'cmath' file not found

which is due to inproper installation of standard C++ libraries.

Since it happens with #include_next, users may feel confusing which cmath is 
not found and how to fix it.

Add an error directive to help users resolve this issue.

>From cf2586ab3a6afde64b4e9eeb1016a62e28c81cce Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Wed, 8 Jan 2025 13:57:50 -0500
Subject: [PATCH] [CUDA][HIP] improve error message for missing cmath

One common error seen in CUDA/HIP compilation is:

fatal error: 'cmath' file not found

which is due to inproper installation of standard C++ libraries.

Since it happens with #include_next, users may feel confusing
which cmath is not found and how to fix it.

Add an error directive to help users resolve this issue.
---
 clang/lib/Headers/cuda_wrappers/cmath | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang/lib/Headers/cuda_wrappers/cmath 
b/clang/lib/Headers/cuda_wrappers/cmath
index 45f89beec9b4df..7deca678bf252e 100644
--- a/clang/lib/Headers/cuda_wrappers/cmath
+++ b/clang/lib/Headers/cuda_wrappers/cmath
@@ -24,7 +24,11 @@
 #ifndef __CLANG_CUDA_WRAPPERS_CMATH
 #define __CLANG_CUDA_WRAPPERS_CMATH
 
+#if __has_include_next()
 #include_next 
+#else
+#error "Could not find standard C++ header 'cmath'. Add -v to your compilation 
command to check the include paths being searched. You may need to install the 
appropriate standard C++ library package corresponding to the search path."
+#endif
 
 #if defined(_LIBCPP_STD_VER)
 

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


[clang] [llvm] [HLSL] Adding Flatten and Branch if attributes with test fixes (PR #122157)

2025-01-08 Thread via cfe-commits

https://github.com/joaosaffran created 
https://github.com/llvm/llvm-project/pull/122157

- Adding the changes from PRs: 
  - #116331 
  - #121852 
- Fixes test `tools/dxil-dis/debug-info.ll`
- Address some missed comments in the previous PR

>From 636802e324be5b51a96b88b0e72a03ab6fa051c5 Mon Sep 17 00:00:00 2001
From: joaosaffran 
Date: Wed, 8 Jan 2025 18:27:07 +
Subject: [PATCH 1/2] Revert "Revert #116331 & #121852 (#122105)"

This reverts commit b66f6b25cb5107d4c8f78d13b08d2bdba39ad919.
---
 clang/include/clang/Basic/Attr.td | 10 ++
 clang/lib/CodeGen/CGStmt.cpp  |  6 ++
 clang/lib/CodeGen/CodeGenFunction.cpp | 25 -
 clang/lib/CodeGen/CodeGenFunction.h   |  4 +
 clang/lib/Sema/SemaStmtAttr.cpp   |  8 ++
 clang/test/AST/HLSL/HLSLControlFlowHint.hlsl  | 43 
 .../test/CodeGenHLSL/HLSLControlFlowHint.hlsl | 48 +
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |  2 +-
 .../Target/DirectX/DXILTranslateMetadata.cpp  | 37 +++
 .../Target/SPIRV/SPIRVInstructionSelector.cpp | 29 --
 llvm/lib/Target/SPIRV/SPIRVStructurizer.cpp   | 44 ++---
 .../CodeGen/DirectX/HLSLControlFlowHint.ll| 98 +++
 .../HLSLControlFlowHint-pass-check.ll | 90 +
 .../SPIRV/structurizer/HLSLControlFlowHint.ll | 91 +
 14 files changed, 516 insertions(+), 19 deletions(-)
 create mode 100644 clang/test/AST/HLSL/HLSLControlFlowHint.hlsl
 create mode 100644 clang/test/CodeGenHLSL/HLSLControlFlowHint.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/HLSLControlFlowHint.ll
 create mode 100644 
llvm/test/CodeGen/SPIRV/structurizer/HLSLControlFlowHint-pass-check.ll
 create mode 100644 llvm/test/CodeGen/SPIRV/structurizer/HLSLControlFlowHint.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 12faf06597008e..6d7f65ab2c6135 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4335,6 +4335,16 @@ def HLSLLoopHint: StmtAttr {
   let Documentation = [HLSLLoopHintDocs, HLSLUnrollHintDocs];
 }
 
+def HLSLControlFlowHint: StmtAttr {
+  /// [branch]
+  /// [flatten]
+  let Spellings = [Microsoft<"branch">, Microsoft<"flatten">];
+  let Subjects = SubjectList<[IfStmt],
+  ErrorDiag, "'if' statements">;
+  let LangOpts = [HLSL];
+  let Documentation = [InternalOnly];
+}
+
 def CapturedRecord : InheritableAttr {
   // This attribute has no spellings as it is only ever created implicitly.
   let Spellings = [];
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index a87c50b8a1cbbf..c8ff48fc733125 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -757,6 +757,8 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
   bool noinline = false;
   bool alwaysinline = false;
   bool noconvergent = false;
+  HLSLControlFlowHintAttr::Spelling flattenOrBranch =
+  HLSLControlFlowHintAttr::SpellingNotCalculated;
   const CallExpr *musttail = nullptr;
 
   for (const auto *A : S.getAttrs()) {
@@ -788,6 +790,9 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
 Builder.CreateAssumption(AssumptionVal);
   }
 } break;
+case attr::HLSLControlFlowHint: {
+  flattenOrBranch = 
cast(A)->getSemanticSpelling();
+} break;
 }
   }
   SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
@@ -795,6 +800,7 @@ void CodeGenFunction::EmitAttributedStmt(const 
AttributedStmt &S) {
   SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline);
   SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent);
   SaveAndRestore save_musttail(MustTailCall, musttail);
+  SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch);
   EmitStmt(S.getSubStmt(), S.getAttrs());
 }
 
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index af58fa64f86585..067ff55b87ae63 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -40,6 +40,7 @@
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Dominators.h"
 #include "llvm/IR/FPEnv.h"
+#include "llvm/IR/Instruction.h"
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
@@ -2083,7 +2084,29 @@ void CodeGenFunction::EmitBranchOnBoolExpr(
 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
   }
 
-  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
+  llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, 
FalseBlock,
+   Weights, Unpredictable);
+  switch (HLSLControlFlowAttr) {
+  case HLSLControlFlowHintAttr::Microsoft_branch:
+  case HLSLControlFlowHintAttr::Microsoft_flatten: {
+llvm::MDBuilder MDHelper(CGM.getLLVMContext());
+
+llvm::ConstantInt *BranchHintConstant =
+

  1   2   3   4   5   6   >