[clang] [OpenMP] codegen support for masked combined construct masked taskloop simd (PR #121916)

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

chandraghale wrote:

Note : OpenMPSupport.rst is updated in PR : 
https://github.com/llvm/llvm-project/pull/121741

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


[clang] [OpenMP] codegen support for masked combined construct masked taskloop (PR #121914)

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

chandraghale wrote:

Note : OpenMPSupport.rst is updated in PR : 
https://github.com/llvm/llvm-project/pull/121741

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


[clang-tools-extra] [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check against std::unique_ptr type (PR #121266)

2025-01-07 Thread via cfe-commits

github-actions[bot] wrote:



@flovent Congratulations on having your first Pull Request (PR) merged into the 
LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a 
problem with a build, you may receive a report in an email or a comment on this 
PR.

Please check whether problems have been caused by your change specifically, as 
the builds can include changes from many authors. It is not uncommon for your 
change to be included in a build that fails due to someone else's changes, or 
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself. This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang-tools-extra] c274837 - [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check against std::unique_ptr type (#121266)

2025-01-07 Thread via cfe-commits

Author: flovent
Date: 2025-01-07T20:56:21+08:00
New Revision: c27483763c883ad268ba61249d1c0274a719e2d6

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

LOG: [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check 
against std::unique_ptr type (#121266)

Unlike other standard smart pointer types, std::unique_ptr has two
template arguments.
testcase need to be updated too.

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
index 8121a36f803460..1f432c4ccc5f00 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
@@ -74,9 +74,11 @@ void 
UnhandledSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
 // Matcher for standard smart pointers.
 const auto SmartPointerType = qualType(hasUnqualifiedDesugaredType(
 recordType(hasDeclaration(classTemplateSpecializationDecl(
-hasAnyName("::std::shared_ptr", "::std::unique_ptr",
-   "::std::weak_ptr", "::std::auto_ptr"),
-templateArgumentCountIs(1));
+anyOf(allOf(hasAnyName("::std::shared_ptr", "::std::weak_ptr",
+   "::std::auto_ptr"),
+templateArgumentCountIs(1)),
+  allOf(hasName("::std::unique_ptr"),
+templateArgumentCountIs(2;
 
 // We will warn only if the class has a pointer or a C array field which
 // probably causes a problem during self-assignment (e.g. first resetting

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1fd9b6077be5f5..35cb3e387e4e64 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -233,6 +233,10 @@ Changes in existing checks
   `bsl::optional` and `bdlb::NullableValue` from
   _.
 
+- Improved :doc:`bugprone-unhandled-self-assignment
+  ` check by fixing smart
+  pointer check against std::unique_ptr type.
+
 - Improved :doc:`bugprone-unsafe-functions
   ` check to allow specifying
   additional functions to match.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
index 14d27855d7c5a6..8610393449f97f 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
@@ -10,7 +10,9 @@ template 
 T &&move(T &x) {
 }
 
-template 
+template  class default_delete {};
+
+template >
 class unique_ptr {
 };
 



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


[clang-tools-extra] [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check against std::unique_ptr type (PR #121266)

2025-01-07 Thread Congcong Cai via cfe-commits

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


[clang] [analyzer] Simplify PositiveAnalyzerOption handling (PR #121910)

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

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

LGTM, straightforward improvement.

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


[clang] [OpenMP] codegen support for masked combined construct parallel masked taskloop simd. (PR #121746)

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

chandraghale wrote:

> Please update OpenMPSupport.rst

Updated the doc in this PR : https://github.com/llvm/llvm-project/pull/121741

https://github.com/llvm/llvm-project/pull/121746
___
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-07 Thread Dan Liew via cfe-commits


@@ -2440,6 +2440,26 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 return !isFunctionType();
   }
 
+  /// \returns True if the type is incomplete and it is also a type that
+  /// cannot be completed by a later type definition.
+  ///
+  /// E.g. For `void` this is true but for `struct ForwardDecl;` this is false
+  /// because a definition for `ForwardDecl` could be provided later on in the
+  /// translation unit.
+  ///
+  /// Note even for types that this function returns true for it is still
+  /// possible for the declarations that contain this type to later have a
+  /// complete type in a translation unit. E.g.:
+  ///
+  /// \code{.c}
+  /// // This decl has type 'char[]' which is incomplete and cannot be later
+  /// // completed by another by another type declaration.
+  /// extern char foo[];
+  /// // This decl how has complete type 'char[5]'.
+  /// char foo[5]; // foo has a complete type
+  /// \endcode
+  bool isIncompletableIncompleteType() const;

delcypher wrote:

Seems reasonable. I'll do the rename.

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][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2025-01-07 Thread Brad Smith via cfe-commits

brad0 wrote:

@ldionne Ping.

https://github.com/llvm/llvm-project/pull/120149
___
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-07 Thread Matheus Izvekov 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(),

mizvekov wrote:

It's not immediately clear to me, nor explained in the commit message, what 
this RecoveryExpr is expected to buy, versus always initializing to nullptr, 
which is the status quo (most of the time, by accident).

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] [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-07 Thread Dan Liew via cfe-commits


@@ -186,4 +218,216 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr 
*E, bool CountInBytes,
   return false;
 }
 
+SourceRange Sema::BoundsSafetySourceRangeFor(const CountAttributedType *CATy) {
+  // This is an approximation that's not quite right. This points to the
+  // the expression inside the attribute rather than the attribute itself.
+  //
+  // TODO: Implement logic to find the relevant TypeLoc for the attribute and
+  // get the SourceRange from that (#113582).
+  return CATy->getCountExpr()->getSourceRange();
+}
+
+static void EmitIncompleteCountedByPointeeNotes(Sema &S,
+const CountAttributedType 
*CATy,
+NamedDecl *IncompleteTyDecl,
+bool NoteAttrLocation = true) {
+  assert(IncompleteTyDecl == nullptr || isa(IncompleteTyDecl));
+
+  if (NoteAttrLocation) {
+// Note where the attribute is declared
+auto AttrSrcRange = S.BoundsSafetySourceRangeFor(CATy);
+S.Diag(AttrSrcRange.getBegin(), diag::note_named_attribute)
+<< CATy->getAttributeName(/*WithMacroPrefix=*/true) << AttrSrcRange;
+  }
+
+  if (!IncompleteTyDecl)
+return;
+
+  // If there's an associated forward declaration display it to emphasize
+  // why the type is incomplete (all we have is a forward declaration).
+
+  // Note the `IncompleteTyDecl` type is the underlying type which might not
+  // be the same as `CATy->getPointeeType()` which could be a typedef.
+  //
+  // The diagnostic printed will be at the location of the underlying type but
+  // the diagnostic text will print the type of `CATy->getPointeeType()` which
+  // could be a typedef name rather than the underlying type. This is ok
+  // though because the diagnostic will print the underlying type name too.
+  // E.g:
+  //
+  // `forward declaration of 'Incomplete_Struct_t'
+  //  (aka 'struct IncompleteStructTy')`
+  //
+  // If this ends up being confusing we could emit a second diagnostic (one
+  // explaining where the typedef is) but that seems overly verbose.

delcypher wrote:

I removed this part of the comment.

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] Added nullptr check to getFriendDecl access (PR #121056)

2025-01-07 Thread Matheus Izvekov via cfe-commits


@@ -886,6 +886,7 @@ Bug Fixes to C++ Support
   out of a module (which is the case e.g. in MSVC's implementation of ``std`` 
module). (#GH118218)
 - Fixed a pack expansion issue in checking unexpanded parameter sizes. 
(#GH17042)
 - Fixed a bug where captured structured bindings were modifiable inside 
non-mutable lambda (#GH95081)
+- Fixed a crash when parsing a friend declaration and a defaulted operator.

mizvekov wrote:

```suggestion
- Fixed a crash when parsing a friend declaration and a defaulted operator 
(#GH120857).
```

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


[clang] [Clang] Added nullptr check to getFriendDecl access (PR #121056)

2025-01-07 Thread Matheus Izvekov via cfe-commits

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


[clang] [Clang] Added nullptr check to getFriendDecl access (PR #121056)

2025-01-07 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov commented:

We also usually attach the issue number to the test case somehow, either put 
the new test cases under a namespace named `GH120857`, or rename the new test 
file to that same name.

https://github.com/llvm/llvm-project/pull/121056
___
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 #120507)

2025-01-07 Thread Mikael Holmén via cfe-commits

mikaelholmen wrote:

Thanks @nico !

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

2025-01-07 Thread via cfe-commits


@@ -53,3 +53,4 @@ LLVM_FIXED_MD_KIND(MD_DIAssignID, "DIAssignID", 38)
 LLVM_FIXED_MD_KIND(MD_coro_outside_frame, "coro.outside.frame", 39)
 LLVM_FIXED_MD_KIND(MD_mmra, "mmra", 40)
 LLVM_FIXED_MD_KIND(MD_noalias_addrspace, "noalias.addrspace", 41)
+LLVM_FIXED_MD_KIND(MD_unaltered_name, "unaltered.name", 42)

gbMattN wrote:

Aha! I hadn't noticed that metadata type. I've switched to using it

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

2025-01-07 Thread via cfe-commits


@@ -3430,13 +3430,15 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
-  ASan.getAllocaSizeInBytes(*AI),
-  0,
-  AI->getAlign().value(),
-  AI,
-  0,
-  0};
+const char *Name = AI->getName().data();

gbMattN wrote:

It is!

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

2025-01-07 Thread via cfe-commits

https://github.com/gbMattN updated 
https://github.com/llvm/llvm-project/pull/119387

>From 8781ff2355750ae61d140620b1f6862537de07e3 Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 10 Dec 2024 15:01:37 +
Subject: [PATCH 1/6] [ASan] Add metadata to renamed instructions so ASan
 doesn't use the incorrect name

---
 llvm/lib/IR/ValueSymbolTable.cpp | 8 
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 7 ++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/IR/ValueSymbolTable.cpp b/llvm/lib/IR/ValueSymbolTable.cpp
index a020acf22a96c5..81bb3f3c5a5e35 100644
--- a/llvm/lib/IR/ValueSymbolTable.cpp
+++ b/llvm/lib/IR/ValueSymbolTable.cpp
@@ -123,6 +123,14 @@ ValueName *ValueSymbolTable::createValueName(StringRef 
Name, Value *V) {
   }
 
   // Otherwise, there is a naming conflict.  Rename this value.
+  // If we are renaming an instruction, ASan needs to know for it to serialize
+  // properly
+  if (auto *I = dyn_cast(V)) {
+MDString *trueNameMetadata = MDString::get(V->getContext(), Name);
+llvm::MDTuple *tuple =
+llvm::MDTuple::get(V->getContext(), trueNameMetadata);
+I->setMetadata("OriginalName", tuple);
+  }
   SmallString<256> UniqueName(Name.begin(), Name.end());
   return makeUniqueName(V, UniqueName);
 }
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index cb84588318496c..c696cc38167cd4 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,7 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
+std::string Name = AI->getName().data();
+if (AI->hasMetadata("OriginalName")) {
+  MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
+  Name = dyn_cast(tuple->getOperand(0))->getString();
+}
+ASanStackVariableDescription D = {Name.c_str(),
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From 25efafa3d67afb6a9107fdd502f5f6e4f40c311c Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Wed, 11 Dec 2024 11:44:01 +
Subject: [PATCH 2/6] [bugfix] Fixed string pointer being used out of scope

---
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index c696cc38167cd4..2051fa94678175 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,12 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-std::string Name = AI->getName().data();
+const char* Name = AI->getName().data();
 if (AI->hasMetadata("OriginalName")) {
   MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
-  Name = dyn_cast(tuple->getOperand(0))->getString();
+  Name = dyn_cast(tuple->getOperand(0))->getString().data();
 }
-ASanStackVariableDescription D = {Name.c_str(),
+ASanStackVariableDescription D = {Name,
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From c15ec2fe9bbe4855272a519b7f6dccca57a294eb Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 17 Dec 2024 16:47:11 +
Subject: [PATCH 3/6] Now only emit metadata when using a ASan, and tag it with
 an enum rather than a string

---
 clang/lib/CodeGen/CGExpr.cpp|  8 
 llvm/include/llvm/IR/FixedMetadataKinds.def |  1 +
 llvm/lib/IR/ValueSymbolTable.cpp|  8 
 .../Instrumentation/AddressSanitizer.cpp| 17 +++--
 4 files changed, 16 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 5fccc9cbb37ec1..d8fdacf30e12e3 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -137,6 +137,14 @@ llvm::AllocaInst 
*CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
 Alloca =
 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  ArraySize, Name, AllocaInsertPt->getIterator());
+  if (Alloca->getName() != Name.str() &&
+  SanOpts.Mask & SanitizerKind::Address) {
+
+llvm::LLVMContext &ctx = Alloca->getContext();
+llvm::MDString *trueNameMetadata = llvm::MDString::get(ctx, Name.str());
+llvm::MDTuple *tuple = llvm::MDTuple::get(ctx, trueNameMetadata);
+  

[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

2025-01-07 Thread via cfe-commits

https://github.com/gbMattN updated 
https://github.com/llvm/llvm-project/pull/119387

>From 8781ff2355750ae61d140620b1f6862537de07e3 Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 10 Dec 2024 15:01:37 +
Subject: [PATCH 1/7] [ASan] Add metadata to renamed instructions so ASan
 doesn't use the incorrect name

---
 llvm/lib/IR/ValueSymbolTable.cpp | 8 
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 7 ++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/IR/ValueSymbolTable.cpp b/llvm/lib/IR/ValueSymbolTable.cpp
index a020acf22a96c5..81bb3f3c5a5e35 100644
--- a/llvm/lib/IR/ValueSymbolTable.cpp
+++ b/llvm/lib/IR/ValueSymbolTable.cpp
@@ -123,6 +123,14 @@ ValueName *ValueSymbolTable::createValueName(StringRef 
Name, Value *V) {
   }
 
   // Otherwise, there is a naming conflict.  Rename this value.
+  // If we are renaming an instruction, ASan needs to know for it to serialize
+  // properly
+  if (auto *I = dyn_cast(V)) {
+MDString *trueNameMetadata = MDString::get(V->getContext(), Name);
+llvm::MDTuple *tuple =
+llvm::MDTuple::get(V->getContext(), trueNameMetadata);
+I->setMetadata("OriginalName", tuple);
+  }
   SmallString<256> UniqueName(Name.begin(), Name.end());
   return makeUniqueName(V, UniqueName);
 }
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index cb84588318496c..c696cc38167cd4 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,7 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
+std::string Name = AI->getName().data();
+if (AI->hasMetadata("OriginalName")) {
+  MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
+  Name = dyn_cast(tuple->getOperand(0))->getString();
+}
+ASanStackVariableDescription D = {Name.c_str(),
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From 25efafa3d67afb6a9107fdd502f5f6e4f40c311c Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Wed, 11 Dec 2024 11:44:01 +
Subject: [PATCH 2/7] [bugfix] Fixed string pointer being used out of scope

---
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index c696cc38167cd4..2051fa94678175 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,12 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-std::string Name = AI->getName().data();
+const char* Name = AI->getName().data();
 if (AI->hasMetadata("OriginalName")) {
   MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
-  Name = dyn_cast(tuple->getOperand(0))->getString();
+  Name = dyn_cast(tuple->getOperand(0))->getString().data();
 }
-ASanStackVariableDescription D = {Name.c_str(),
+ASanStackVariableDescription D = {Name,
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From c15ec2fe9bbe4855272a519b7f6dccca57a294eb Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 17 Dec 2024 16:47:11 +
Subject: [PATCH 3/7] Now only emit metadata when using a ASan, and tag it with
 an enum rather than a string

---
 clang/lib/CodeGen/CGExpr.cpp|  8 
 llvm/include/llvm/IR/FixedMetadataKinds.def |  1 +
 llvm/lib/IR/ValueSymbolTable.cpp|  8 
 .../Instrumentation/AddressSanitizer.cpp| 17 +++--
 4 files changed, 16 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 5fccc9cbb37ec1..d8fdacf30e12e3 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -137,6 +137,14 @@ llvm::AllocaInst 
*CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
 Alloca =
 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  ArraySize, Name, AllocaInsertPt->getIterator());
+  if (Alloca->getName() != Name.str() &&
+  SanOpts.Mask & SanitizerKind::Address) {
+
+llvm::LLVMContext &ctx = Alloca->getContext();
+llvm::MDString *trueNameMetadata = llvm::MDString::get(ctx, Name.str());
+llvm::MDTuple *tuple = llvm::MDTuple::get(ctx, trueNameMetadata);
+  

[clang] [libc] enable ms extensions (PR #121875)

2025-01-07 Thread via cfe-commits

https://github.com/Prabhuk converted_to_draft 
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] [libc] enable ms extensions (PR #121875)

2025-01-07 Thread via cfe-commits

Prabhuk wrote:

> Why is the libc patch included in this one?

Thank you! It was a mistake. I'll upload the right version and marking this PR 
as draft until then.

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] [llvm] [AMDGPU][True16][MC] true16 for v_alignbyte_b32 (PR #119750)

2025-01-07 Thread Ivan Kosarev via cfe-commits


@@ -2353,8 +2353,8 @@ def int_amdgcn_writelane :
   [IntrNoMem, IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]
 >;
 
-def int_amdgcn_alignbyte : ClangBuiltin<"__builtin_amdgcn_alignbyte">,
-  DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+def int_amdgcn_alignbyte : DefaultAttrsIntrinsic<[llvm_i32_ty],
+  [llvm_i32_ty, llvm_i32_ty, llvm_anyint_ty],

kosarev wrote:

> pattern match extract of high bits. We generally shouldn't expose the direct 
> op_sel reads

That's what I meant by masking subtarget specifics. Nevermind then.

(Though I do still have doubts as to whether having pattern matching on top of 
such as a no-side-effects intrinsic is a good idea, because normally the 
intention behind using intrinsics would be not to rely on pattern matching and 
get it translated with guarantee to something of a very particular form. 
Otherwise, we could just pattern-match an equivalent tree that doesn't use any 
intrinsics at all.)

@broxigarchen Guo, so can we leave the intrinsic as is and on codegen just use 
the low half of src2 on GFX11+?

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


[clang] [Clang] Added nullptr check to getFriendDecl access (PR #121056)

2025-01-07 Thread via cfe-commits

https://github.com/GrumpyPigSkin updated 
https://github.com/llvm/llvm-project/pull/121056

>From a6c7f0dfd1da4b17118f25023cf2f5da70ee3dab Mon Sep 17 00:00:00 2001
From: GrumpyPigSkin 
Date: Tue, 24 Dec 2024 15:18:29 +
Subject: [PATCH 1/5] Added nullptr check to getFriendDecl access

---
 clang/lib/Sema/SemaDeclCXX.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index c5a72cf812ebc9..64b1fb28e2e184 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -8871,8 +8871,9 @@ bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, 
FunctionDecl *FD,
   return true;
 
 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
-  return FD->getCanonicalDecl() ==
- F->getFriendDecl()->getCanonicalDecl();
+  if (NamedDecl* Ffd = F->getFriendDecl())
+return FD->getCanonicalDecl() == Ffd->getCanonicalDecl();
+  return false;
 })) {
   Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
   << int(DCK) << int(0) << RD;

>From 884100d515904ebba05172a3a6a535b34d8a91dd Mon Sep 17 00:00:00 2001
From: GrumpyPigSkin 
Date: Tue, 24 Dec 2024 15:24:08 +
Subject: [PATCH 2/5] Applied formatting

---
 clang/lib/Sema/SemaDeclCXX.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 64b1fb28e2e184..973318c7060a6a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -8871,7 +8871,7 @@ bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, 
FunctionDecl *FD,
   return true;
 
 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
-  if (NamedDecl* Ffd = F->getFriendDecl())
+  if (NamedDecl *Ffd = F->getFriendDecl())
 return FD->getCanonicalDecl() == Ffd->getCanonicalDecl();
   return false;
 })) {

>From 7846c140110ed87d9d7997c7ac792c5d5aa92972 Mon Sep 17 00:00:00 2001
From: GrumpyPigSkin 
Date: Thu, 26 Dec 2024 13:19:20 +
Subject: [PATCH 3/5] Added test and release note

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/test/SemaCXX/friend-default-operator.cpp | 12 
 2 files changed, 13 insertions(+)
 create mode 100644 clang/test/SemaCXX/friend-default-operator.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8b984ecaefecaf..cf0148296254a0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -885,6 +885,7 @@ Bug Fixes to C++ Support
 - Fixed recognition of ``std::initializer_list`` when it's surrounded with 
``extern "C++"`` and exported
   out of a module (which is the case e.g. in MSVC's implementation of ``std`` 
module). (#GH118218)
 - Fixed a pack expansion issue in checking unexpanded parameter sizes. 
(#GH17042)
+- Fixed a crash when parsing a friend declaration and a defaulted operator.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/test/SemaCXX/friend-default-operator.cpp 
b/clang/test/SemaCXX/friend-default-operator.cpp
new file mode 100644
index 00..cbb18f99416378
--- /dev/null
+++ b/clang/test/SemaCXX/friend-default-operator.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// ; Ensure the following out of line friend declaration doesn't cause the 
compiler to crash.
+
+class A {
+  friend bool operator==(const A&, const A&);
+  friend class B;
+};
+
+bool operator==(const A&, const A&) = default;
+

>From 5d31475ab3bfd8349087b625dff2d009adef8c39 Mon Sep 17 00:00:00 2001
From: GrumpyPigSkin 
Date: Thu, 26 Dec 2024 13:28:29 +
Subject: [PATCH 4/5] removed redundant ;

---
 clang/test/SemaCXX/friend-default-operator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/SemaCXX/friend-default-operator.cpp 
b/clang/test/SemaCXX/friend-default-operator.cpp
index cbb18f99416378..b92e417a1e313c 100644
--- a/clang/test/SemaCXX/friend-default-operator.cpp
+++ b/clang/test/SemaCXX/friend-default-operator.cpp
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
 // expected-no-diagnostics
 
-// ; Ensure the following out of line friend declaration doesn't cause the 
compiler to crash.
+// Ensure the following out of line friend declaration doesn't cause the 
compiler to crash.
 
 class A {
   friend bool operator==(const A&, const A&);

>From 025f7240e45fc5b365daca09bfab4ce2637d1bf8 Mon Sep 17 00:00:00 2001
From: GrumpyPigSkin 
Date: Tue, 7 Jan 2025 17:28:43 +
Subject: [PATCH 5/5] Added issue number to test and release note

---
 clang/docs/ReleaseNotes.rst| 2 +-
 clang/test/SemaCXX/friend-default-operator.cpp | 5 +
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b15cb0f7f0f99c..711286d984a1c6 

[clang] [clang] Emit @llvm.assume when we know the streaming mode of the function (PR #121917)

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


@@ -11335,6 +11335,13 @@ Value 
*CodeGenFunction::EmitAArch64SMEBuiltinExpr(unsigned BuiltinID,
   unsigned SMEAttrs = FPT->getAArch64SMEAttributes();
   if (!(SMEAttrs & FunctionType::SME_PStateSMCompatibleMask)) {
 bool IsStreaming = SMEAttrs & FunctionType::SME_PStateSMEnabledMask;
+// Emit the llvm.assume intrinsic so that called functions can use the
+// streaming mode information discerned here
+Value *call =
+Builder.CreateCall(CGM.getIntrinsic(Builtin->LLVMIntrinsic));
+if (!IsStreaming)
+  call = Builder.CreateNot(call);
+Builder.CreateIntrinsic(Intrinsic::assume, {}, {call});

sdesmalen-arm wrote:

Emitting the llvm.assume only for calls to `__arm_in_streaming_mode()` only has 
any effect if it is followed by a call to a streaming-compatible function.

To make this more useful generically, I think it needs to be emitted before any 
call from a streaming- or non-streaming function, to a streaming-compatible 
function. Then the partial-inliner, ipsccp pass, or function specialization 
pass can use the information to specialize or inline the callee.

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] [AArch64][Clang] Add support for __arm_agnostic("sme_za_state") (PR #121788)

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

https://github.com/sdesmalen-arm updated 
https://github.com/llvm/llvm-project/pull/121788

>From 159bc2ccdab5457d997c9fc8ed679e4607db0b79 Mon Sep 17 00:00:00 2001
From: Sander de Smalen 
Date: Mon, 9 Sep 2024 15:20:26 +0100
Subject: [PATCH 1/2] [AArch64][Clang] Add support for
 __arm_agnostic("sme_za_state")

This adds support for parsing the attribute and codegen to
map it to "aarch64_za_state_agnostic" LLVM IR attribute.

This attribute is described in the Arm C Language Extensions
(ACLE) document:

  https://github.com/ARM-software/acle/blob/main/main/acle.md#__arm_agnostic
---
 clang/include/clang/AST/Type.h| 13 --
 clang/include/clang/Basic/Attr.td |  7 +++
 clang/include/clang/Basic/AttrDocs.td | 20 
 .../clang/Basic/DiagnosticSemaKinds.td|  5 ++
 clang/lib/AST/TypePrinter.cpp |  2 +
 clang/lib/CodeGen/CGCall.cpp  |  2 +
 clang/lib/Sema/SemaDecl.cpp   |  8 
 clang/lib/Sema/SemaType.cpp   | 46 ++-
 .../sme-intrinsics/aarch64-sme-attrs.cpp  | 24 ++
 clang/test/Sema/aarch64-sme-func-attrs.c  | 21 +
 10 files changed, 143 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 09c98f642852fc..49c1681d84dd52 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4593,9 +4593,14 @@ class FunctionType : public Type {
 SME_ZT0Shift = 5,
 SME_ZT0Mask = 0b111 << SME_ZT0Shift,
 
+// A bit to tell whether a function is agnostic about sme ZA state.
+SME_AgnosticZAStateShift = 8,
+SME_AgnosticZAStateMask = 1 << SME_AgnosticZAStateShift,
+
 SME_AttributeMask =
-0b111'111'11 // We can't support more than 8 bits because of
- // the bitmask in FunctionTypeExtraBitfields.
+0b1'111'111'11 // We can't support more than 16 bits because of
+   // the bitmask in FunctionTypeArmAttributes
+   // and ExtProtoInfo.
   };
 
   enum ArmStateValue : unsigned {
@@ -4620,7 +4625,7 @@ class FunctionType : public Type {
   struct alignas(void *) FunctionTypeArmAttributes {
 /// Any AArch64 SME ACLE type attributes that need to be propagated
 /// on declarations and function pointers.
-unsigned AArch64SMEAttributes : 8;
+unsigned AArch64SMEAttributes : 9;
 
 FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
   };
@@ -5188,7 +5193,7 @@ class FunctionProtoType final
 FunctionType::ExtInfo ExtInfo;
 unsigned Variadic : 1;
 unsigned HasTrailingReturn : 1;
-unsigned AArch64SMEAttributes : 8;
+unsigned AArch64SMEAttributes : 9;
 Qualifiers TypeQuals;
 RefQualifierKind RefQualifier = RQ_None;
 ExceptionSpecInfo ExceptionSpec;
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 52ad72eb608c31..de8c951f66f416 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2866,6 +2866,13 @@ def ArmPreserves : TypeAttr, 
TargetSpecificAttr {
   let Documentation = [ArmPreservesDocs];
 }
 
+def ArmAgnostic : TypeAttr, TargetSpecificAttr {
+  let Spellings = [RegularKeyword<"__arm_agnostic">];
+  let Args = [VariadicStringArgument<"AgnosticArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [ArmAgnosticDocs];
+}
+
 def ArmLocallyStreaming : InheritableAttr, TargetSpecificAttr {
   let Spellings = [RegularKeyword<"__arm_locally_streaming">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index fdad4c9a3ea191..2b2c6f0691b0ce 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7559,6 +7559,26 @@ The attributes ``__arm_in(S)``, ``__arm_out(S)``, 
``__arm_inout(S)`` and
   }];
 }
 
+def ArmAgnosticDocs : Documentation {
+  let Category = DocCatArmSmeAttributes;
+  let Content = [{
+The ``__arm_agnostic`` keyword applies to prototyped function types and
+specifies that the function is agnostic about the given state S and
+returns with state S unchanged if state S exists.
+
+The attribute takes string arguments to instruct the compiler which state
+the function is agnostic about.  The supported states for S are:
+
+* ``"sme_za_state"`` for any state enabled by PSTATE.ZA (including the
+  bit itself)
+
+The attributes ``__arm_agnostic("sme_za_state") cannot be used in conjunction
+with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
+``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
+such as "za" or "zt0".
+  }];
+}
+
 def ArmSmeLocallyStreamingDocs : Documentation {
   let Category = DocCatArmSmeAttributes;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 03fb7

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

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


@@ -49,6 +49,8 @@ class ABIInfo {
   CodeGen::CodeGenTypes &CGT;
   llvm::CallingConv::ID RuntimeCC;
 
+  unsigned getTargetDefaultAS() const;

arsenm wrote:

I'm fine with the getContext().get 

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] [TySan] Don't report globals with incomplete types. (PR #121922)

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

https://github.com/fhahn created 
https://github.com/llvm/llvm-project/pull/121922

Type metadata for incomplete types should also get handled at the place they 
are defined.

Fixes https://github.com/llvm/llvm-project/issues/121014.

>From d5f66784891b0bd1d8a23060ec104b3a7d07dbec Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Tue, 7 Jan 2025 11:44:53 +
Subject: [PATCH] [TySan] Don't report globals with incomplete types.

Type metadata for incomplete types should also get handled at the place
they are defined.

Fixes https://github.com/llvm/llvm-project/issues/121014.
---
 clang/lib/CodeGen/SanitizerMetadata.cpp  |  4 ++-
 clang/test/CodeGen/sanitize-type-globals.cpp | 35 
 2 files changed, 31 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/SanitizerMetadata.cpp 
b/clang/lib/CodeGen/SanitizerMetadata.cpp
index 61fdf3399ff3c3..b7b212ba46efd3 100644
--- a/clang/lib/CodeGen/SanitizerMetadata.cpp
+++ b/clang/lib/CodeGen/SanitizerMetadata.cpp
@@ -145,7 +145,9 @@ void SanitizerMetadata::reportGlobal(llvm::GlobalVariable 
*GV, const VarDecl &D,
 for (auto *Attr : D.specific_attrs())
   NoSanitizeMask |= Attr->getMask();
 
-if (D.hasExternalStorage())
+// External definitions and incomplete types get handled at the place they
+// are defined.
+if (D.hasExternalStorage() || D.getType()->isIncompleteType())
   NoSanitizeMask |= SanitizerKind::Type;
 
 return NoSanitizeMask;
diff --git a/clang/test/CodeGen/sanitize-type-globals.cpp 
b/clang/test/CodeGen/sanitize-type-globals.cpp
index 7cb8de8b238cc8..1154ab4ca5df27 100644
--- a/clang/test/CodeGen/sanitize-type-globals.cpp
+++ b/clang/test/CodeGen/sanitize-type-globals.cpp
@@ -3,7 +3,10 @@
 
 //.
 // CHECK: @x = global %struct.CompleteS zeroinitializer, align 8
+// CHECK: @xExtern = external global %struct.CompleteS, align 8
 // CHECK: @y = external global %struct.S, align 1
+// CHECK: @d = global %class.b zeroinitializer, align 1
+// CHECK: @_ZN1b1eE = external global %class.a, align 1
 // CHECK: @__tysan_shadow_memory_address = external global i64
 // CHECK: @__tysan_app_memory_mask = external global i64
 // CHECK: @__tysan_v1_Simple_20C_2b_2b_20TBAA = linkonce_odr constant { i64, 
i64, [16 x i8] } { i64 2, i64 0, [16 x i8] c"Simple C++ TBAA\00" }, comdat
@@ -12,8 +15,9 @@
 // CHECK: @__tysan_v1_any_20pointer = linkonce_odr constant { i64, i64, ptr, 
i64, [12 x i8] } { i64 2, i64 1, ptr @__tysan_v1_omnipotent_20char, i64 0, [12 
x i8] c"any pointer\00" }, comdat
 // CHECK: @__tysan_v1_p1_20int = linkonce_odr constant { i64, i64, ptr, i64, 
[7 x i8] } { i64 2, i64 1, ptr @__tysan_v1_any_20pointer, i64 0, [7 x i8] c"p1 
int\00" }, comdat
 // CHECK: @__tysan_v1___ZTS9CompleteS = linkonce_odr constant { i64, i64, ptr, 
i64, ptr, i64, [15 x i8] } { i64 2, i64 2, ptr @__tysan_v1_int, i64 0, ptr 
@__tysan_v1_p1_20int, i64 8, [15 x i8] c"_ZTS9CompleteS\00" }, comdat
-// CHECK: @llvm.used = appending global [7 x ptr] [ptr @tysan.module_ctor, ptr 
@__tysan_v1_Simple_20C_2b_2b_20TBAA, ptr @__tysan_v1_omnipotent_20char, ptr 
@__tysan_v1_int, ptr @__tysan_v1_any_20pointer, ptr @__tysan_v1_p1_20int, ptr 
@__tysan_v1___ZTS9CompleteS], section "llvm.metadata"
-// CHECK: @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ 
i32, ptr, ptr } { i32 0, ptr @tysan.module_ctor, ptr null }]
+// CHECK: @__tysan_v1___ZTS1b = linkonce_odr constant { i64, i64, [7 x i8] } { 
i64 2, i64 0, [7 x i8] c"_ZTS1b\00" }, comdat
+// CHECK: @llvm.used = appending global [8 x ptr] [ptr @tysan.module_ctor, ptr 
@__tysan_v1_Simple_20C_2b_2b_20TBAA, ptr @__tysan_v1_omnipotent_20char, ptr 
@__tysan_v1_int, ptr @__tysan_v1_any_20pointer, ptr @__tysan_v1_p1_20int, ptr 
@__tysan_v1___ZTS9CompleteS, ptr @__tysan_v1___ZTS1b], section "llvm.metadata"
+// CHECK: @llvm.global_ctors = appending global [2 x { i32, ptr, ptr }] [{ 
i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_sanitize_type_globals.cpp, ptr 
null }, { i32, ptr, ptr } { i32 0, ptr @tysan.module_ctor, ptr null }]
 //.
 struct CompleteS {
   int x;
@@ -22,13 +26,18 @@ struct CompleteS {
 
 void f(CompleteS *);
 CompleteS x;
+extern CompleteS xExtern;
 // CHECK-LABEL: define dso_local void @_Z1gv(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK:  [[ENTRY:.*:]]
 // CHECK:call void @_Z1fP9CompleteS(ptr noundef @x)
+// CHECK:call void @_Z1fP9CompleteS(ptr noundef @xExtern)
 // CHECK:ret void
 //
-void g() { f(&x); }
+void g() {
+  f(&x);
+  f(&xExtern);
+}
 
 typedef struct S IncompleteS;
 void f(IncompleteS *);
@@ -40,11 +49,21 @@ extern IncompleteS y;
 // CHECK:ret void
 //
 void h() { f(&y); }
+
+class a;
+class b {
+public:
+  using c = a;
+  static c e;
+  b(int, c & = e);
+} d = 0;
+
 //.
 // CHECK: attributes #[[ATTR0]] = { mustprogress noinline nounwind optnone 
sanitize_type "min-legal-vector-width"="0" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" 
}
 // CHECK: attributes #[[ATTR1:[0

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

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


@@ -814,7 +816,10 @@ static ABIArgInfo classifyType(CodeGenModule &CGM, 
CanQualType type,
 auto &layout = CGM.getContext().getASTRecordLayout(record);
 
 if (mustPassRecordIndirectly(CGM, record))
-  return ABIArgInfo::getIndirect(layout.getAlignment(), /*byval*/ false);
+  return ABIArgInfo::getIndirect(
+  layout.getAlignment(),
+  /*AddrSpace*/ 
CGM.getContext().getTargetAddressSpace(LangAS::Default),
+  /*byval*/ false);

AlexVlx wrote:

Reworked altogether.

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] [TySan] Don't report globals with incomplete types. (PR #121922)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Florian Hahn (fhahn)


Changes

Type metadata for incomplete types should also get handled at the place they 
are defined.

Fixes https://github.com/llvm/llvm-project/issues/121014.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/SanitizerMetadata.cpp (+3-1) 
- (modified) clang/test/CodeGen/sanitize-type-globals.cpp (+28-7) 


``diff
diff --git a/clang/lib/CodeGen/SanitizerMetadata.cpp 
b/clang/lib/CodeGen/SanitizerMetadata.cpp
index 61fdf3399ff3c3..b7b212ba46efd3 100644
--- a/clang/lib/CodeGen/SanitizerMetadata.cpp
+++ b/clang/lib/CodeGen/SanitizerMetadata.cpp
@@ -145,7 +145,9 @@ void SanitizerMetadata::reportGlobal(llvm::GlobalVariable 
*GV, const VarDecl &D,
 for (auto *Attr : D.specific_attrs())
   NoSanitizeMask |= Attr->getMask();
 
-if (D.hasExternalStorage())
+// External definitions and incomplete types get handled at the place they
+// are defined.
+if (D.hasExternalStorage() || D.getType()->isIncompleteType())
   NoSanitizeMask |= SanitizerKind::Type;
 
 return NoSanitizeMask;
diff --git a/clang/test/CodeGen/sanitize-type-globals.cpp 
b/clang/test/CodeGen/sanitize-type-globals.cpp
index 7cb8de8b238cc8..1154ab4ca5df27 100644
--- a/clang/test/CodeGen/sanitize-type-globals.cpp
+++ b/clang/test/CodeGen/sanitize-type-globals.cpp
@@ -3,7 +3,10 @@
 
 //.
 // CHECK: @x = global %struct.CompleteS zeroinitializer, align 8
+// CHECK: @xExtern = external global %struct.CompleteS, align 8
 // CHECK: @y = external global %struct.S, align 1
+// CHECK: @d = global %class.b zeroinitializer, align 1
+// CHECK: @_ZN1b1eE = external global %class.a, align 1
 // CHECK: @__tysan_shadow_memory_address = external global i64
 // CHECK: @__tysan_app_memory_mask = external global i64
 // CHECK: @__tysan_v1_Simple_20C_2b_2b_20TBAA = linkonce_odr constant { i64, 
i64, [16 x i8] } { i64 2, i64 0, [16 x i8] c"Simple C++ TBAA\00" }, comdat
@@ -12,8 +15,9 @@
 // CHECK: @__tysan_v1_any_20pointer = linkonce_odr constant { i64, i64, ptr, 
i64, [12 x i8] } { i64 2, i64 1, ptr @__tysan_v1_omnipotent_20char, i64 0, [12 
x i8] c"any pointer\00" }, comdat
 // CHECK: @__tysan_v1_p1_20int = linkonce_odr constant { i64, i64, ptr, i64, 
[7 x i8] } { i64 2, i64 1, ptr @__tysan_v1_any_20pointer, i64 0, [7 x i8] c"p1 
int\00" }, comdat
 // CHECK: @__tysan_v1___ZTS9CompleteS = linkonce_odr constant { i64, i64, ptr, 
i64, ptr, i64, [15 x i8] } { i64 2, i64 2, ptr @__tysan_v1_int, i64 0, ptr 
@__tysan_v1_p1_20int, i64 8, [15 x i8] c"_ZTS9CompleteS\00" }, comdat
-// CHECK: @llvm.used = appending global [7 x ptr] [ptr @tysan.module_ctor, ptr 
@__tysan_v1_Simple_20C_2b_2b_20TBAA, ptr @__tysan_v1_omnipotent_20char, ptr 
@__tysan_v1_int, ptr @__tysan_v1_any_20pointer, ptr @__tysan_v1_p1_20int, ptr 
@__tysan_v1___ZTS9CompleteS], section "llvm.metadata"
-// CHECK: @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ 
i32, ptr, ptr } { i32 0, ptr @tysan.module_ctor, ptr null }]
+// CHECK: @__tysan_v1___ZTS1b = linkonce_odr constant { i64, i64, [7 x i8] } { 
i64 2, i64 0, [7 x i8] c"_ZTS1b\00" }, comdat
+// CHECK: @llvm.used = appending global [8 x ptr] [ptr @tysan.module_ctor, ptr 
@__tysan_v1_Simple_20C_2b_2b_20TBAA, ptr @__tysan_v1_omnipotent_20char, ptr 
@__tysan_v1_int, ptr @__tysan_v1_any_20pointer, ptr @__tysan_v1_p1_20int, ptr 
@__tysan_v1___ZTS9CompleteS, ptr @__tysan_v1___ZTS1b], section "llvm.metadata"
+// CHECK: @llvm.global_ctors = appending global [2 x { i32, ptr, ptr }] [{ 
i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_sanitize_type_globals.cpp, ptr 
null }, { i32, ptr, ptr } { i32 0, ptr @tysan.module_ctor, ptr null }]
 //.
 struct CompleteS {
   int x;
@@ -22,13 +26,18 @@ struct CompleteS {
 
 void f(CompleteS *);
 CompleteS x;
+extern CompleteS xExtern;
 // CHECK-LABEL: define dso_local void @_Z1gv(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK:  [[ENTRY:.*:]]
 // CHECK:call void @_Z1fP9CompleteS(ptr noundef @x)
+// CHECK:call void @_Z1fP9CompleteS(ptr noundef @xExtern)
 // CHECK:ret void
 //
-void g() { f(&x); }
+void g() {
+  f(&x);
+  f(&xExtern);
+}
 
 typedef struct S IncompleteS;
 void f(IncompleteS *);
@@ -40,11 +49,21 @@ extern IncompleteS y;
 // CHECK:ret void
 //
 void h() { f(&y); }
+
+class a;
+class b {
+public:
+  using c = a;
+  static c e;
+  b(int, c & = e);
+} d = 0;
+
 //.
 // CHECK: attributes #[[ATTR0]] = { mustprogress noinline nounwind optnone 
sanitize_type "min-legal-vector-width"="0" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" 
}
 // CHECK: attributes #[[ATTR1:[0-9]+]] = { "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" 
}
-// CHECK: attributes #[[ATTR2:[0-9]+]] = { nounwind 
"target-features"="+cx8,+mmx,+sse,+sse2,+x87" }
-// CHECK: attributes #[[ATTR3:[0-9]+]] = { nounwind }
+// CHECK: attr

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

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


@@ -21,9 +21,12 @@ ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) 
const {
 // Records with non-trivial destructors/copy-constructors should not be
 // passed by value.
 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
-  return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
+  return getNaturalAlignIndirect(
+  Ty, getContext().getTargetAddressSpace(LangAS::Default),
+  RAA == CGCXXABI::RAA_DirectInMemory);
 
-return getNaturalAlignIndirect(Ty);
+return getNaturalAlignIndirect(
+Ty, getContext().getTargetAddressSpace(LangAS::Default));

arsenm wrote:

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 

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] [AArch64][Clang] Add support for __arm_agnostic("sme_za_state") (PR #121788)

2025-01-07 Thread Richard Sandiford via cfe-commits


@@ -7559,6 +7559,26 @@ The attributes ``__arm_in(S)``, ``__arm_out(S)``, 
``__arm_inout(S)`` and
   }];
 }
 
+def ArmAgnosticDocs : Documentation {
+  let Category = DocCatArmSmeAttributes;
+  let Content = [{
+The ``__arm_agnostic`` keyword applies to prototyped function types and
+specifies that the function is agnostic about the given state S and

rsandifo-arm wrote:

I wonder whether “is agnostic about” will mean much to someone who doesn't 
already know what the attribute does.  Perhaps we should instead present this 
as an alternative calling convention for functions that do not share particular 
state with their callers.

That is, the effect of calling:
```
  void f(void) __attribute__((arm_agnostic("sme")));
```
on C/C++ SME state is equivalent to calling:
```
  void f(void);
```
since both share no SME state with their callers.  But if these two `f`s were 
exposed at ABI boundaries, they would have different calling conventions, and 
the object code would take a different approach to managing the state.

(That isn't suggested wording!  Just trying to describe what I mean.)

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


[clang] [RISCV] Teach Barmetal toolchain about GCC installation(1/3) (PR #121829)

2025-01-07 Thread Garvit Gupta via cfe-commits

https://github.com/quic-garvgupt updated 
https://github.com/llvm/llvm-project/pull/121829

>From 02d70a2c1fa746eafa87308f0c8109bb2c91164f Mon Sep 17 00:00:00 2001
From: Garvit Gupta 
Date: Fri, 13 Dec 2024 05:31:56 -0800
Subject: [PATCH] [RISCV] Teach Barmetal toolchain about GCC installation(1/3)

This patch introduces the baretmetal toolchain object about GCC Installation.
Currently, if `--gcc-installation` ot `--gcc-install-dir` options are passed on
commandline, then sysroot will be formed from there if paths will be valid.
Otherwise, it will be fallback to as it already existed in the Baremetal
toolchaibn object.

Additionally, the restriction to always use integrated assembler is removed
because with valid gcc installation, gnu assembler can be invoked as well.

This patch currently adds and modifies arm related test only. The riscv specific
test will be added in the last PR when driver code related to calling of
RISCVToolchain object will be removed. Currently in this PR, there is no way to
test riscv target.

This is the first PR in the series of 3 PRs for merging and extending Baremetal
toolchain object. The division of the PRs is as follows:
- Teach Baremetal toolchain about GCC installation and make sysroot and 
assembler
  related changes.
- Changes related to linker job and defaults for CXXStdlib and other runtime 
libs.
- Finally removing the call to RISCVToolchain object.

The above division will also ensure that riscv and arm specific tests are not
modified in the same PR.

RFC: 
https://discourse.llvm.org/t/merging-riscvtoolchain-and-baremetal-toolchains/75524

Change-Id: Ibaeb569cf7e2cee03c022aa9ecd1abe29d5c30d4
---
 clang/lib/Driver/ToolChains/BareMetal.cpp | 121 +++---
 clang/lib/Driver/ToolChains/BareMetal.h   |   8 +-
 .../aarch64-none-elf/bin/ld   |   1 +
 .../aarch64-none-elf/include/c++/8.2.1/.keep  |   0
 .../aarch64-none-elf/lib/.keep|   0
 .../aarch64-none-elf/lib/crt0.o   |   0
 .../lib/gcc/aarch64-none-elf/8.2.1/crtbegin.o |   0
 .../lib/gcc/aarch64-none-elf/8.2.1/crtend.o   |   0
 .../aarch64-none-elf/bin/ld   |   1 +
 .../aarch64-none-elf/lib/.keep|   0
 .../aarch64-none-elf/lib/crt0.o   |   0
 .../aarch64-none-elf/lib/crtbegin.o   |   0
 .../aarch64-none-elf/lib/crtend.o |   0
 .../armv6m-none-eabi/bin/ld   |   1 +
 .../armv6m-none-eabi/include/c++/8.2.1/.keep  |   0
 .../armv6m-none-eabi/lib/.keep|   0
 .../armv6m-none-eabi/lib/crt0.o   |   0
 .../lib/gcc/armv6m-none-eabi/8.2.1/crtbegin.o |   0
 .../lib/gcc/armv6m-none-eabi/8.2.1/crtend.o   |   0
 .../armv6m-none-eabi/bin/ld   |   1 +
 .../armv6m-none-eabi/lib/.keep|   0
 .../armv6m-none-eabi/lib/crt0.o   |   0
 .../armv6m-none-eabi/lib/crtbegin.o   |   0
 .../armv6m-none-eabi/lib/crtend.o |   0
 clang/test/Driver/aarch64-toolchain-extra.c   |  28 
 clang/test/Driver/aarch64-toolchain.c |  61 +
 clang/test/Driver/arm-gnutools.c  |  12 ++
 clang/test/Driver/arm-toolchain-extra.c   |  29 +
 clang/test/Driver/arm-toolchain.c |  62 +
 clang/test/Driver/baremetal.cpp   |  16 +++
 30 files changed, 321 insertions(+), 20 deletions(-)
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/aarch64-none-elf/bin/ld
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/aarch64-none-elf/include/c++/8.2.1/.keep
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/aarch64-none-elf/lib/.keep
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/aarch64-none-elf/lib/crt0.o
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/lib/gcc/aarch64-none-elf/8.2.1/crtbegin.o
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_gcc_tree/lib/gcc/aarch64-none-elf/8.2.1/crtend.o
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_nogcc_tree/aarch64-none-elf/bin/ld
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_nogcc_tree/aarch64-none-elf/lib/.keep
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_nogcc_tree/aarch64-none-elf/lib/crt0.o
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_nogcc_tree/aarch64-none-elf/lib/crtbegin.o
 create mode 100644 
clang/test/Driver/Inputs/basic_aarch64_nogcc_tree/aarch64-none-elf/lib/crtend.o
 create mode 100644 
clang/test/Driver/Inputs/basic_arm_gcc_tree/armv6m-none-eabi/bin/ld
 create mode 100644 
clang/test/Driver/Inputs/basic_arm_gcc_tree/armv6m-none-eabi/include/c++/8.2.1/.keep
 create mode 100644 
clang/test/Driver/Inputs/basic_arm_gcc_tree/armv6m-none-eabi/lib/.keep
 create mode 100644 
clang/test/Driver/Inputs/basic_arm_gcc_tree/armv6m-none-eabi/lib/crt0.o
 create mode 100644 
clang/test/Driver/Inputs/basic_arm_gcc_tree/lib/gcc/armv6m-none-eabi/8.2.1/crtbegin.o
 create mode 100644 
cla

[clang] [llvm] [AMDGPU][True16][MC] true16 for v_alignbyte_b32 (PR #119750)

2025-01-07 Thread Ivan Kosarev via cfe-commits


@@ -2353,8 +2353,8 @@ def int_amdgcn_writelane :
   [IntrNoMem, IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]
 >;
 
-def int_amdgcn_alignbyte : ClangBuiltin<"__builtin_amdgcn_alignbyte">,
-  DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+def int_amdgcn_alignbyte : DefaultAttrsIntrinsic<[llvm_i32_ty],
+  [llvm_i32_ty, llvm_i32_ty, llvm_anyint_ty],

kosarev wrote:

The intrinsic currently doesn't support using the high half of src2 on 
pre-GFX11. If it ever will have to (I don't know that), then it seems there 
should be two separate intrinsics for pre-GFX11 and GFX11+.

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


[clang] [llvm] [AMDGPU][True16][MC] true16 for v_alignbyte_b32 (PR #119750)

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


@@ -2353,8 +2353,8 @@ def int_amdgcn_writelane :
   [IntrNoMem, IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]
 >;
 
-def int_amdgcn_alignbyte : ClangBuiltin<"__builtin_amdgcn_alignbyte">,
-  DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+def int_amdgcn_alignbyte : DefaultAttrsIntrinsic<[llvm_i32_ty],
+  [llvm_i32_ty, llvm_i32_ty, llvm_anyint_ty],

arsenm wrote:

It doesn't need to. We can just pattern match extract of high bits. We 
generally shouldn't expose the direct op_sel reads 

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


[clang] [NFC] [analyzer] Factor out SymbolManager::get<*> (PR #121781)

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


@@ -525,14 +527,14 @@ class SymbolManager {
 
   static bool canSymbolicate(QualType T);
 
-  /// Make a unique symbol for MemRegion R according to its kind.
-  const SymbolRegionValue* getRegionValueSymbol(const TypedValueRegion* R);
+  template  const T *get(Args &&...args);

NagyDonat wrote:

> I was considering "make" briefly, but it is not entirely correct: this 
> function doesn't always make a `SymExpr`, sometimes it retrieves an existing 
> one matching the arguments. Besides, most of the replaced member functions 
> were called `get*`.

I would say that "`make`" is still reasonable in this case, because 
semantically it _makes the symbol_ which is determined by the arguments passed 
to it -- and it's just an implementation detail that symbols are immutable 
objects and the `make` call returns already created symbols instead of 
recreating them. However, I can accept a different name if you're opposed to 
"`make`".

> How do you like `findOrCreate`, `createIfNone`, `ensureExists`, `obtain`, 
> `acquire`, `procure`?

I think `acquire` would be the best choice, followed by something like 
`makeOrGet` or `findOrCreate`. IMO `obtain` suggests that we're getting the 
symbol from an external source, [`procure` has unfortunate connections to 
sexual services](https://www.merriam-webster.com/dictionary/procure) and in my 
opinion `createIfNone` and `ensureExists` don't clearly imply that these 
functions _return the symbol_ in addition to just initializing it in some 
internal table.

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


[clang] [NFC] [analyzer] Factor out SymbolManager::get<*> (PR #121781)

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

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


[clang-tools-extra] Add bugprone-sprintf-argument-overlap (PR #114244)

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

AaronBallman wrote:

> > Is this still worth adding here? I didn't see an equivalent in clang's 
> > -Wall.
> 
> Indeed Clang is missing this check in -Wall. For parity with GCC it probably 
> makes sense to add it to -Wall as well instead of being a clang-tidy check. 
> What do you think @AaronBallman ?

In general, this requires dataflow analysis to get a low false-positive rate, 
which is typically handled via static analysis or a CFG-based analysis (which 
are expensive to construct for `-Wall` and thus usually opt-in, but we do have 
some such checks that have crept in so there is precedence).

Ideally, I think this check would either live in Clang under an opt-in analysis 
warning flag (similar to implicit fallthrough checks) or in the Clang static 
analyzer (CC @steakhal @haoNoQ @Xazax-hun for additional opinions). If we did 
that, I think this check should be generalized a bit more. 1) We could have a 
`restrict`-based check for any APIs with pointers marked `restrict`. 2) We 
could handle C library functions specially: `sprintf` and friends, `mbstowcs`, 
`wcstombs`, `memcpy`, `memccpy`, `strcpy`, etc.

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


[clang] [OpenMP] codegen support for masked combined construct parallel masked taskloop (PR #121741)

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

chandraghale wrote:

> Update OpenMPSupport.rst

Updated OpenMPSupport.rst . Updated the doc for all the related split-ed  PRs ( 
[PR-121746](https://github.com/llvm/llvm-project/pull/121746) , 
[121914](https://github.com/llvm/llvm-project/pull/121914) , 
[121916](https://github.com/llvm/llvm-project/pull/121916)  ) for combined 
masked construct in this PR only to avoid merge conflict. 

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


[clang-tools-extra] Add bugprone-sprintf-argument-overlap (PR #114244)

2025-01-07 Thread Gábor Horváth via cfe-commits

Xazax-hun wrote:

>  this requires dataflow analysis to get a low false-positive rate

I think it might be possible to have low false positive rates without dataflow 
analysis. Currently, it looks like the check is looking for syntactically 
identical subexpressions.  Those tend to overlap in most cases. That being 
said, I can imagine some cases where it is not really the case, like:
```
sprintf(st1.buf, return_format_string_and_modify_buf("%s", &st1.buf), st1.buf);
```

To filter these, the check would need to ensure that the pointer cannot be 
modified while the arguments are evaluated. 

Are there any other false positives you anticipate?

That being said, we'd absolutely need dataflow analysis to reduce the number of 
false negatives when the arguments are not syntactically equivalent. 

I think it would be OK to have a fast, syntactic check in `-Wall` and have a 
smarted dataflow-based check as opt-in somewhere else (can be compiler, tidy, 
or the clang static analyzer). I think implementing this check in the clang 
static analyzer would be relatively straightforward.

> I think this check should be generalized a bit more

Huge +1. I like the generalization ideas. No matter in what form we land this, 
I think people would benefit a lot from that. 


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


[clang] [AArch64][SME] Add diagnostics for SME attributes on lambda functions (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits

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


[clang] 5f6b714 - [analyzer][NFC] Simplify PositiveAnalyzerOption handling (#121910)

2025-01-07 Thread via cfe-commits

Author: Balazs Benics
Date: 2025-01-07T15:19:16+01:00
New Revision: 5f6b7145077386afac806eec1bb8e866c6166034

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

LOG: [analyzer][NFC] Simplify PositiveAnalyzerOption handling (#121910)

This simplifies #120239
Addresses my comment at:
https://github.com/llvm/llvm-project/pull/120239#issuecomment-2574600543

CPP-5920

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
clang/lib/Frontend/CompilerInvocation.cpp
clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
index 3f341ecf8c1e4f..2c970301879d24 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -126,11 +126,18 @@ enum class CTUPhase1InliningKind { None, Small, All };
 
 class PositiveAnalyzerOption {
 public:
-  PositiveAnalyzerOption() = default;
-  PositiveAnalyzerOption(const PositiveAnalyzerOption &) = default;
-  PositiveAnalyzerOption &operator=(const PositiveAnalyzerOption &) = default;
+  constexpr PositiveAnalyzerOption() = default;
+  constexpr PositiveAnalyzerOption(unsigned Value) : Value(Value) {
+assert(Value > 0 && "only positive values are accepted");
+  }
+  constexpr PositiveAnalyzerOption(const PositiveAnalyzerOption &) = default;
+  constexpr PositiveAnalyzerOption &
+  operator=(const PositiveAnalyzerOption &Other) {
+Value = Other.Value;
+return *this;
+  }
 
-  static std::optional create(unsigned Val) {
+  static constexpr std::optional create(unsigned Val) {
 if (Val == 0)
   return std::nullopt;
 return PositiveAnalyzerOption{Val};
@@ -141,11 +148,9 @@ class PositiveAnalyzerOption {
   return std::nullopt;
 return PositiveAnalyzerOption::create(Parsed);
   }
-  operator unsigned() const { return Value; }
+  constexpr operator unsigned() const { return Value; }
 
 private:
-  explicit constexpr PositiveAnalyzerOption(unsigned Value) : Value(Value) {}
-
   unsigned Value = 1;
 };
 

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 6e47b374d4ed86..d711df02ce9503 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1274,9 +1274,7 @@ static void initOption(AnalyzerOptions::ConfigTable 
&Config,
 Diags->Report(diag::err_analyzer_config_invalid_input)
 << Name << "a positive";
 
-  auto Default = PositiveAnalyzerOption::create(DefaultVal);
-  assert(Default.has_value());
-  OptionField = Default.value();
+  OptionField = DefaultVal;
 }
 
 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,

diff  --git a/clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp 
b/clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp
index ed8627c500098a..626f5c163d17d0 100644
--- a/clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp
+++ b/clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp
@@ -27,22 +27,13 @@ static constexpr std::optional UNDEF = std::nullopt;
 static unsigned operator""_ms(unsigned long long ms) { return ms; }
 static unsigned operator""_step(unsigned long long rlimit) { return rlimit; }
 
-template  static Ret makeDefaultOption(Arg Value) {
-  return Value;
-}
-template <> PositiveAnalyzerOption makeDefaultOption(int Value) {
-  auto DefaultVal = PositiveAnalyzerOption::create(Value);
-  assert(DefaultVal.has_value());
-  return DefaultVal.value();
-}
-
 static const AnalyzerOptions DefaultOpts = [] {
   AnalyzerOptions Config;
 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,
\
  SHALLOW_VAL, DEEP_VAL)
\
   ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEEP_VAL)
 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)
\
-  Config.NAME = makeDefaultOption(DEFAULT_VAL);
+  Config.NAME = DEFAULT_VAL;
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
 
   // Remember to update the tests in this file when these values change.



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


[clang] [analyzer][NFC] Simplify PositiveAnalyzerOption handling (PR #121910)

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

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


[clang] [NFC][analyzer][docs] Crosslink MallocChecker's ownership attributes (PR #121939)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




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

Author: Kristóf Umann (Szelethus)


Changes

Forgot to mention these in the checker docs.

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


2 Files Affected:

- (modified) clang/docs/analyzer/checkers.rst (+18) 
- (modified) clang/include/clang/Basic/AttrDocs.td (+1) 


``diff
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 29d5e1f92a69c2..e093b2d672a74e 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -476,6 +476,9 @@ cplusplus.NewDelete (C++)
 "
 Check for double-free and use-after-free problems. Traces memory managed by 
new/delete.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/newdelete_example.cpp
 :language: cpp
 
@@ -485,6 +488,9 @@ cplusplus.NewDeleteLeaks (C++)
 ""
 Check for memory leaks. Traces memory managed by new/delete.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: cpp
 
  void test() {
@@ -1263,6 +1269,9 @@ You can silence this warning either by bound checking the 
``size`` parameter, or
 by explicitly marking the ``size`` parameter as sanitized. See the
 :ref:`optin-taint-GenericTaint` checker for an example.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: c
 
   void vulnerable(void) {
@@ -1857,6 +1866,9 @@ unix.Malloc (C)
 """
 Check for memory leaks, double free, and use-after-free problems. Traces 
memory managed by malloc()/free().
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/unix_malloc_example.c
 :language: c
 
@@ -1866,6 +1878,9 @@ unix.MallocSizeof (C)
 "
 Check for dubious ``malloc`` arguments involving ``sizeof``.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: c
 
  void test() {
@@ -1881,6 +1896,9 @@ unix.MismatchedDeallocator (C, C++)
 """
 Check for mismatched deallocators.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/mismatched_deallocator_example.cpp
 :language: c
 
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index ba581e02542fc6..b8d702e41aa0bb 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1393,6 +1393,7 @@ def OwnershipDocs : Documentation {
   let Heading = "ownership_holds, ownership_returns, ownership_takes (Clang "
 "Static Analyzer)";
   let Category = DocCatFunction;
+  let Label = "analyzer-ownership-attrs";
   let Content = [{
 
 .. note::

``




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


[clang] [NFC][analyzer][docs] Crosslink MallocChecker's ownership attributes (PR #121939)

2025-01-07 Thread Kristóf Umann via cfe-commits

https://github.com/Szelethus created 
https://github.com/llvm/llvm-project/pull/121939

Forgot to mention these in the checker docs.

From 80a8cb8425c4c588659e1153fe0834d6514070d0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Krist=C3=B3f=20Umann?= 
Date: Tue, 7 Jan 2025 13:30:28 +0100
Subject: [PATCH] [NFC][analyzer][docs] Crosslink MallocChecker's ownership
 attributes

Forgot to mention these in the checker docs.
---
 clang/docs/analyzer/checkers.rst  | 18 ++
 clang/include/clang/Basic/AttrDocs.td |  1 +
 2 files changed, 19 insertions(+)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 29d5e1f92a69c2..e093b2d672a74e 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -476,6 +476,9 @@ cplusplus.NewDelete (C++)
 "
 Check for double-free and use-after-free problems. Traces memory managed by 
new/delete.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/newdelete_example.cpp
 :language: cpp
 
@@ -485,6 +488,9 @@ cplusplus.NewDeleteLeaks (C++)
 ""
 Check for memory leaks. Traces memory managed by new/delete.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: cpp
 
  void test() {
@@ -1263,6 +1269,9 @@ You can silence this warning either by bound checking the 
``size`` parameter, or
 by explicitly marking the ``size`` parameter as sanitized. See the
 :ref:`optin-taint-GenericTaint` checker for an example.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: c
 
   void vulnerable(void) {
@@ -1857,6 +1866,9 @@ unix.Malloc (C)
 """
 Check for memory leaks, double free, and use-after-free problems. Traces 
memory managed by malloc()/free().
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/unix_malloc_example.c
 :language: c
 
@@ -1866,6 +1878,9 @@ unix.MallocSizeof (C)
 "
 Check for dubious ``malloc`` arguments involving ``sizeof``.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. code-block:: c
 
  void test() {
@@ -1881,6 +1896,9 @@ unix.MismatchedDeallocator (C, C++)
 """
 Check for mismatched deallocators.
 
+Custom allocation/deallocation functions can be defined using
+:ref:`ownership attributes`.
+
 .. literalinclude:: checkers/mismatched_deallocator_example.cpp
 :language: c
 
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index ba581e02542fc6..b8d702e41aa0bb 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1393,6 +1393,7 @@ def OwnershipDocs : Documentation {
   let Heading = "ownership_holds, ownership_returns, ownership_takes (Clang "
 "Static Analyzer)";
   let Category = DocCatFunction;
+  let Label = "analyzer-ownership-attrs";
   let Content = [{
 
 .. note::

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


[clang] [analyzer][NFC] Simplify PositiveAnalyzerOption handling (PR #121910)

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

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


[clang] [Clang] Remove 3-element vector load and store special handling (PR #104661)

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


@@ -52,6 +52,12 @@ class AMDGPUABIInfo final : public DefaultABIInfo {
   void computeInfo(CGFunctionInfo &FI) const override;
   RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
AggValueSlot Slot) const override;
+
+  llvm::FixedVectorType *
+  getOptimalVectorType(llvm::FixedVectorType *T,
+   const LangOptions &) const override {
+return T;

shiltian wrote:

Is that the only case that we can support?

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


[clang] [AArch64][SME] Add diagnostics to CheckConstexprFunctionDefinition (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits

https://github.com/kmclaughlin-arm updated 
https://github.com/llvm/llvm-project/pull/121777

>From 00772b871de43a5e30aca2a65a89675117cafbf1 Mon Sep 17 00:00:00 2001
From: Kerry McLaughlin 
Date: Tue, 31 Dec 2024 17:22:02 +
Subject: [PATCH 1/3] [AArch64][SME] Add diagnostics to
 CheckConstexprFunctionDefinition

CheckFunctionDeclaration emits diagnostics if any SME attributes are used
by a function definition without the required +sme or +sme2 target features.
This patch adds similar diagnostics to CheckConstexprFunctionDefinition to
ensure this emits the same errors when attributes such as __arm_new("za")
are found without +sme/+sme2.
---
 clang/lib/Sema/SemaDeclCXX.cpp| 22 +++
 ...-sme-func-attrs-without-target-feature.cpp |  8 ++-
 2 files changed, 29 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index c5a72cf812ebc9..3ee26ebabcfdd5 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -1854,6 +1854,28 @@ bool Sema::CheckConstexprFunctionDefinition(const 
FunctionDecl *NewFD,
 }
   }
 
+  if (Context.getTargetInfo().getTriple().isAArch64()) {
+const auto *Attr = NewFD->getAttr();
+bool LocallyStreaming = NewFD->hasAttr();
+llvm::StringMap FeatureMap;
+Context.getFunctionFeatureMap(FeatureMap, NewFD);
+if (!FeatureMap.contains("sme") && LocallyStreaming) {
+  Diag(NewFD->getLocation(),
+   diag::err_sme_definition_using_sm_in_non_sme_target);
+  return false;
+}
+if (Attr && Attr->isNewZA() && !FeatureMap.contains("sme")) {
+  Diag(NewFD->getLocation(),
+   diag::err_sme_definition_using_za_in_non_sme_target);
+  return false;
+}
+if (Attr && Attr->isNewZT0() && !FeatureMap.contains("sme2")) {
+  Diag(NewFD->getLocation(),
+   diag::err_sme_definition_using_zt0_in_non_sme2_target);
+  return false;
+}
+  }
+
   // - each of its parameter types shall be a literal type; (removed in C++23)
   if (!getLangOpts().CPlusPlus23 &&
   !CheckConstexprParameterTypes(*this, NewFD, Kind))
diff --git a/clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp 
b/clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp
index ec6bb6f5035784..a046b5aa1325cc 100644
--- a/clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp
+++ b/clang/test/Sema/aarch64-sme-func-attrs-without-target-feature.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -std=c++23 -fsyntax-only 
-verify %s
 
 // This test is testing the diagnostics that Clang emits when compiling 
without '+sme'.
 
@@ -48,3 +48,9 @@ void streaming_compatible_def2(void (*streaming_fn_ptr)(void) 
__arm_streaming,
 // Also test when call-site is not a function.
 int streaming_decl_ret_int() __arm_streaming;
 int x = streaming_decl_ret_int(); // expected-error {{call to a streaming 
function requires 'sme'}}
+
+void sme_attrs_method_decls() {
+  [&] __arm_locally_streaming () { return; }();  // expected-error {{function 
executed in streaming-SVE mode requires 'sme'}}
+  [&] __arm_new("za") () { return; }();  // expected-error {{function using ZA 
state requires 'sme'}}
+  [&] __arm_new("zt0") () { return; }();  // expected-error {{function using 
ZT0 state requires 'sme2'}}
+}

>From bbc80c21e66958a149cdfcf37a56ea5825728a2d Mon Sep 17 00:00:00 2001
From: Kerry McLaughlin 
Date: Mon, 6 Jan 2025 15:55:36 +
Subject: [PATCH 2/3] - Move diagnostics to SemaARM.cpp

---
 clang/include/clang/Sema/SemaARM.h|  1 +
 clang/lib/Sema/SemaARM.cpp| 53 ++
 clang/lib/Sema/SemaDecl.cpp   | 55 +--
 clang/lib/Sema/SemaDeclCXX.cpp| 24 +---
 ...-sme-func-attrs-without-target-feature.cpp |  2 +-
 5 files changed, 61 insertions(+), 74 deletions(-)

diff --git a/clang/include/clang/Sema/SemaARM.h 
b/clang/include/clang/Sema/SemaARM.h
index 8c4c56e2221301..08b03af7fd4bc6 100644
--- a/clang/include/clang/Sema/SemaARM.h
+++ b/clang/include/clang/Sema/SemaARM.h
@@ -79,6 +79,7 @@ class SemaARM : public SemaBase {
   void handleNewAttr(Decl *D, const ParsedAttr &AL);
   void handleCmseNSEntryAttr(Decl *D, const ParsedAttr &AL);
   void handleInterruptAttr(Decl *D, const ParsedAttr &AL);
+  void CheckSMEFunctionDefAttributes(const FunctionDecl *FD);
 };
 
 SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
diff --git a/clang/lib/Sema/SemaARM.cpp b/clang/lib/Sema/SemaARM.cpp
index 411baa066f7097..eafd43eb979ba0 100644
--- a/clang/lib/Sema/SemaARM.cpp
+++ b/clang/lib/Sema/SemaARM.cpp
@@ -1328,4 +1328,57 @@ void SemaARM::handleInterruptAttr(Decl *D, const 
ParsedAttr &AL) {
  ARMInterruptAttr(getASTContext(), AL, Kind));
 }
 
+// Check if the function definition uses any AArch64 SME features without
+// having the '+sme'

[clang] [C++20] [Modules] [Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2025-01-07 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Can you reduce your modules test case into a self contained project with build 
system?

If so, you can use [cvise](https://github.com/marxin/cvise) for reducing a 
whole project directory recursively in one invocation.

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


[clang] [AArch64][SME] Add diagnostics to CheckConstexprFunctionDefinition (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits


@@ -1854,6 +1855,9 @@ bool Sema::CheckConstexprFunctionDefinition(const 
FunctionDecl *NewFD,
 }
   }
 
+  if (Context.getTargetInfo().getTriple().isAArch64())
+ARM().CheckSMEFunctionDefAttributes(NewFD);
+

kmclaughlin-arm wrote:

Thanks, `ActOnStartOfLambdaDefinition` does seem like a better place to check 
the attributes.

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


[clang] [AArch64][SME] Add diagnostics to CheckConstexprFunctionDefinition (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits


@@ -1328,4 +1328,57 @@ void SemaARM::handleInterruptAttr(Decl *D, const 
ParsedAttr &AL) {
  ARMInterruptAttr(getASTContext(), AL, Kind));
 }
 
+// Check if the function definition uses any AArch64 SME features without
+// having the '+sme' feature enabled and warn user if sme locally streaming
+// function returns or uses arguments with VL-based types.
+void SemaARM::CheckSMEFunctionDefAttributes(const FunctionDecl *FD) {

kmclaughlin-arm wrote:

I've changed this to `static` and added `Sema` as a parameter, so that the 
function can still use `Diag()` for emitting the diagnostics.

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


[clang] [AArch64][SME] Add diagnostics to CheckConstexprFunctionDefinition (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits


@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -std=c++23 -fsyntax-only 
-verify %s

kmclaughlin-arm wrote:

I think adding attributes to lambdas before the parameter list was only allowed 
in C++23. If I don't pass this flag, the error emitted is instead `"'attribute' 
in this position is a C++23 extension"`.

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


[clang] [AArch64][SME] Add diagnostics for SME attributes on lambda functions (PR #121777)

2025-01-07 Thread Kerry McLaughlin via cfe-commits

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


[clang] [Clang] Remove 3-element vector load and store special handling (PR #104661)

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


@@ -1,77 +0,0 @@
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple spir-unknown-unknown 
-fpreserve-vec3-type | FileCheck %s
-
-typedef char char3 __attribute__((ext_vector_type(3)));

shiltian wrote:

The point of the test is for preserving vec3, as the name of the file 
indicates, which is no longer the case. Why do we want to keep it?

https://github.com/llvm/llvm-project/pull/104661
___
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 #120507)

2025-01-07 Thread Nico Weber via cfe-commits

nico wrote:

Reverted in ab5133bbc62af4686f305a3c7d85f74b9f5b949f for now.

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


[clang] [Clang] Re-write codegen for atomic_test_and_set and atomic_clear (PR #121943)

2025-01-07 Thread Oliver Stannard via cfe-commits

https://github.com/ostannard created 
https://github.com/llvm/llvm-project/pull/121943

Re-write the sema and codegen for the atomic_test_and_set and atomic_clear 
builtin functions to go via AtomicExpr, like the other atomic builtins do. This 
simplifies the code, because AtomicExpr already handles things like generating 
code for to dynamically select the memory ordering, which was duplicated for 
these builtins. This also fixes a few crash bugs, one when passing an integer 
to the pointer argument, and one when using an array.

This also adds diagnostics for the memory orderings which are not valid for 
atomic_clear according to 
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html, which were 
missing before.

Fixes https://github.com/llvm/llvm-project/issues/111293.

This is a re-land of #120449, modified to allow any non-const pointer type for 
the first argument.

>From 2a69ca9ba3b67967e0f88a9b96ac8bea44220842 Mon Sep 17 00:00:00 2001
From: Oliver Stannard 
Date: Thu, 19 Dec 2024 09:12:19 +
Subject: [PATCH 1/2] [Clang] Re-write codegen for atomic_test_and_set and
 atomic_clear (#120449)

Re-write the sema and codegen for the atomic_test_and_set and
atomic_clear builtin functions to go via AtomicExpr, like the other
atomic builtins do. This simplifies the code, because AtomicExpr already
handles things like generating code for to dynamically select the memory
ordering, which was duplicated for these builtins. This also fixes a few
crash bugs, one when passing an integer to the pointer argument, and one
when using an array.

This also adds diagnostics for the memory orderings which are not valid
for atomic_clear according to
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html, which
were missing before.

Fixes #111293.
---
 clang/include/clang/Basic/Builtins.td|  12 +-
 clang/lib/AST/Expr.cpp   |   2 +
 clang/lib/CodeGen/CGAtomic.cpp   |  25 ++-
 clang/lib/CodeGen/CGBuiltin.cpp  | 141 -
 clang/lib/Sema/SemaChecking.cpp  |  35 +++-
 clang/test/CodeGen/atomic-test-and-set.c | 250 +++
 clang/test/Sema/atomic-ops.c |   8 +-
 7 files changed, 316 insertions(+), 157 deletions(-)
 create mode 100644 clang/test/CodeGen/atomic-test-and-set.c

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 468c16050e2bf08..5bbab148f50a9d5 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1977,16 +1977,16 @@ def AtomicNandFetch : AtomicBuiltin {
   let Prototype = "void(...)";
 }
 
-def AtomicTestAndSet : Builtin {
+def AtomicTestAndSet : AtomicBuiltin {
   let Spellings = ["__atomic_test_and_set"];
-  let Attributes = [NoThrow];
-  let Prototype = "bool(void volatile*, int)";
+  let Attributes = [NoThrow, CustomTypeChecking];
+  let Prototype = "void(...)";
 }
 
-def AtomicClear : Builtin {
+def AtomicClear : AtomicBuiltin {
   let Spellings = ["__atomic_clear"];
-  let Attributes = [NoThrow];
-  let Prototype = "void(void volatile*, int)";
+  let Attributes = [NoThrow, CustomTypeChecking];
+  let Prototype = "void(...)";
 }
 
 def AtomicThreadFence : Builtin {
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index ba66d3627856748..b6a86d82473d3dc 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -5070,6 +5070,8 @@ unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
   case AO__opencl_atomic_init:
   case AO__c11_atomic_load:
   case AO__atomic_load_n:
+  case AO__atomic_test_and_set:
+  case AO__atomic_clear:
 return 2;
 
   case AO__scoped_atomic_load_n:
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index f6cb2ad421e9060..3adb2a7ad207f0c 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -723,6 +723,24 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr 
*E, Address Dest,
   case AtomicExpr::AO__scoped_atomic_fetch_nand:
 Op = llvm::AtomicRMWInst::Nand;
 break;
+
+  case AtomicExpr::AO__atomic_test_and_set: {
+llvm::AtomicRMWInst *RMWI =
+CGF.emitAtomicRMWInst(llvm::AtomicRMWInst::Xchg, Ptr,
+  CGF.Builder.getInt8(1), Order, Scope, E);
+RMWI->setVolatile(E->isVolatile());
+llvm::Value *Result = CGF.Builder.CreateIsNotNull(RMWI, "tobool");
+CGF.Builder.CreateStore(Result, Dest);
+return;
+  }
+
+  case AtomicExpr::AO__atomic_clear: {
+llvm::StoreInst *Store =
+CGF.Builder.CreateStore(CGF.Builder.getInt8(0), Ptr);
+Store->setAtomic(Order, Scope);
+Store->setVolatile(E->isVolatile());
+return;
+  }
   }
 
   llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
@@ -878,6 +896,8 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
   case AtomicExpr::AO__c11_atomic_load:
   case AtomicExpr::AO__opencl_atomic_load:
   case AtomicExpr::AO__hip_atomic_load:
+  case AtomicExpr::AO__atomic_test_and_set:
+  case AtomicExpr:

[clang] [Clang] Re-write codegen for atomic_test_and_set and atomic_clear (PR #121943)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Oliver Stannard (ostannard)


Changes

Re-write the sema and codegen for the atomic_test_and_set and atomic_clear 
builtin functions to go via AtomicExpr, like the other atomic builtins do. This 
simplifies the code, because AtomicExpr already handles things like generating 
code for to dynamically select the memory ordering, which was duplicated for 
these builtins. This also fixes a few crash bugs, one when passing an integer 
to the pointer argument, and one when using an array.

This also adds diagnostics for the memory orderings which are not valid for 
atomic_clear according to 
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html, which were 
missing before.

Fixes https://github.com/llvm/llvm-project/issues/111293.

This is a re-land of #120449, modified to allow any non-const pointer 
type for the first argument.

---

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


7 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6-6) 
- (modified) clang/lib/AST/Expr.cpp (+2) 
- (modified) clang/lib/CodeGen/CGAtomic.cpp (+24-1) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (-141) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+55-17) 
- (added) clang/test/CodeGen/atomic-test-and-set.c (+345) 
- (modified) clang/test/Sema/atomic-ops.c (+17-2) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 468c16050e2bf0..5bbab148f50a9d 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1977,16 +1977,16 @@ def AtomicNandFetch : AtomicBuiltin {
   let Prototype = "void(...)";
 }
 
-def AtomicTestAndSet : Builtin {
+def AtomicTestAndSet : AtomicBuiltin {
   let Spellings = ["__atomic_test_and_set"];
-  let Attributes = [NoThrow];
-  let Prototype = "bool(void volatile*, int)";
+  let Attributes = [NoThrow, CustomTypeChecking];
+  let Prototype = "void(...)";
 }
 
-def AtomicClear : Builtin {
+def AtomicClear : AtomicBuiltin {
   let Spellings = ["__atomic_clear"];
-  let Attributes = [NoThrow];
-  let Prototype = "void(void volatile*, int)";
+  let Attributes = [NoThrow, CustomTypeChecking];
+  let Prototype = "void(...)";
 }
 
 def AtomicThreadFence : Builtin {
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index ba66d362785674..b6a86d82473d3d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -5070,6 +5070,8 @@ unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
   case AO__opencl_atomic_init:
   case AO__c11_atomic_load:
   case AO__atomic_load_n:
+  case AO__atomic_test_and_set:
+  case AO__atomic_clear:
 return 2;
 
   case AO__scoped_atomic_load_n:
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index f6cb2ad421e906..3adb2a7ad207f0 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -723,6 +723,24 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr 
*E, Address Dest,
   case AtomicExpr::AO__scoped_atomic_fetch_nand:
 Op = llvm::AtomicRMWInst::Nand;
 break;
+
+  case AtomicExpr::AO__atomic_test_and_set: {
+llvm::AtomicRMWInst *RMWI =
+CGF.emitAtomicRMWInst(llvm::AtomicRMWInst::Xchg, Ptr,
+  CGF.Builder.getInt8(1), Order, Scope, E);
+RMWI->setVolatile(E->isVolatile());
+llvm::Value *Result = CGF.Builder.CreateIsNotNull(RMWI, "tobool");
+CGF.Builder.CreateStore(Result, Dest);
+return;
+  }
+
+  case AtomicExpr::AO__atomic_clear: {
+llvm::StoreInst *Store =
+CGF.Builder.CreateStore(CGF.Builder.getInt8(0), Ptr);
+Store->setAtomic(Order, Scope);
+Store->setVolatile(E->isVolatile());
+return;
+  }
   }
 
   llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
@@ -878,6 +896,8 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
   case AtomicExpr::AO__c11_atomic_load:
   case AtomicExpr::AO__opencl_atomic_load:
   case AtomicExpr::AO__hip_atomic_load:
+  case AtomicExpr::AO__atomic_test_and_set:
+  case AtomicExpr::AO__atomic_clear:
 break;
 
   case AtomicExpr::AO__atomic_load:
@@ -1200,6 +1220,8 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
 case AtomicExpr::AO__opencl_atomic_fetch_max:
 case AtomicExpr::AO__scoped_atomic_fetch_max:
 case AtomicExpr::AO__scoped_atomic_max_fetch:
+case AtomicExpr::AO__atomic_test_and_set:
+case AtomicExpr::AO__atomic_clear:
   llvm_unreachable("Integral atomic operations always become atomicrmw!");
 }
 
@@ -1239,7 +1261,8 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
  E->getOp() == AtomicExpr::AO__atomic_store ||
  E->getOp() == AtomicExpr::AO__atomic_store_n ||
  E->getOp() == AtomicExpr::AO__scoped_atomic_store ||
- E->getOp() == AtomicExpr::AO__scoped_atomic_store_n;
+ E->getOp() =

[clang] [clang][dataflow] Use smart pointer caching in unchecked optional accessor (PR #120249)

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

https://github.com/jvoung updated 
https://github.com/llvm/llvm-project/pull/120249

>From c526263a7accc434dbf6e93c2995ceb2f95873b8 Mon Sep 17 00:00:00 2001
From: Jan Voung 
Date: Tue, 17 Dec 2024 15:38:19 +
Subject: [PATCH 1/7] [clang][dataflow] Use smart pointer caching in unchecked
 optional accessor

Part 2 (and final part) following 
https://github.com/llvm/llvm-project/pull/120102
Allows users to do things like:

```
if (o->x.has_value()) {
  ((*o).x).value();
}
```
where the `->` and `*` are operator overload calls.

A user could instead extract the nested optional into a local variable
once instead of doing two accessor calls back to back, but currently
they are unsure why the code is flagged.
---
 .../CachedConstAccessorsLattice.h |  41 
 .../SmartPointerAccessorCaching.h | 168 +++
 .../lib/Analysis/FlowSensitive/CMakeLists.txt |   1 +
 .../Models/UncheckedOptionalAccessModel.cpp   |  58 +-
 .../SmartPointerAccessorCaching.cpp   | 153 ++
 .../Analysis/FlowSensitive/CMakeLists.txt |   1 +
 .../CachedConstAccessorsLatticeTest.cpp   |  32 +++
 .../SmartPointerAccessorCachingTest.cpp   | 194 ++
 .../UncheckedOptionalAccessModelTest.cpp  |  50 +
 9 files changed, 692 insertions(+), 6 deletions(-)
 create mode 100644 
clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
 create mode 100644 
clang/lib/Analysis/FlowSensitive/SmartPointerAccessorCaching.cpp
 create mode 100644 
clang/unittests/Analysis/FlowSensitive/SmartPointerAccessorCachingTest.cpp

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..6b5dacf9f66d2d 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -13,7 +13,9 @@
 #ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CACHED_CONST_ACCESSORS_LATTICE_H
 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CACHED_CONST_ACCESSORS_LATTICE_H
 
+#include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
@@ -71,10 +73,28 @@ template  class CachedConstAccessorsLattice 
: public Base {
   /// Requirements:
   ///
   ///  - `CE` should return a location (GLValue or a record type).
+  ///
+  /// DEPRECATED: switch users to the below overload which takes Callee and 
Type
+  /// directly.
   StorageLocation *getOrCreateConstMethodReturnStorageLocation(
   const RecordStorageLocation &RecordLoc, const CallExpr *CE,
   Environment &Env, llvm::function_ref 
Initialize);
 
+  /// Creates or returns a previously created `StorageLocation` associated with
+  /// a const method call `obj.getFoo()` where `RecordLoc` is the
+  /// `RecordStorageLocation` of `obj`, `Callee` is the decl for `getFoo`,
+  /// and `Type` is the return type of `getFoo`.
+  ///
+  /// The callback `Initialize` runs on the storage location if newly created.
+  ///
+  /// Requirements:
+  ///
+  ///  - `Type` should return a location (GLValue or a record type).
+  StorageLocation &getOrCreateConstMethodReturnStorageLocation(
+  const RecordStorageLocation &RecordLoc, const FunctionDecl *Callee,
+  QualType Type, Environment &Env,
+  llvm::function_ref Initialize);
+
   void clearConstMethodReturnValues(const RecordStorageLocation &RecordLoc) {
 ConstMethodReturnValues.erase(&RecordLoc);
   }
@@ -212,6 +232,27 @@ 
CachedConstAccessorsLattice::getOrCreateConstMethodReturnStorageLocation(
   return &Loc;
 }
 
+template 
+StorageLocation &
+CachedConstAccessorsLattice::getOrCreateConstMethodReturnStorageLocation(
+const RecordStorageLocation &RecordLoc, const FunctionDecl *Callee,
+QualType Type, Environment &Env,
+llvm::function_ref Initialize) {
+  assert(Callee != nullptr);
+  assert(!Type.isNull());
+  assert(Type->isReferenceType() || Type->isRecordType());
+  auto &ObjMap = ConstMethodReturnStorageLocations[&RecordLoc];
+  auto it = ObjMap.find(Callee);
+  if (it != ObjMap.end())
+return *it->second;
+
+  StorageLocation &Loc = Env.createStorageLocation(Type.getNonReferenceType());
+  Initialize(Loc);
+
+  ObjMap.insert({Callee, &Loc});
+  return Loc;
+}
+
 } // namespace dataflow
 } // namespace clang
 
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h 
b/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
new file mode 100644
index 00..e89e82c893d8cb
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
@@ -0,0 +1,168 @@
+//===-- SmartPointerAccessorCaching.h ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, u

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

2025-01-07 Thread via cfe-commits

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

This is neat.
Sorry for the delay

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] [IR][AsmParser] Revamp how floating-point literals in LLVM IR. (PR #121838)

2025-01-07 Thread Joshua Cranmer via cfe-commits

https://github.com/jcranmer-intel edited 
https://github.com/llvm/llvm-project/pull/121838
___
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-07 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}}
+  void *tmp2 = explicit_desig_init.buf_typedef;
+
+  struct CBBufDeclPos partial_explicit_desig_init = {
+.count = 0,
+// .buf and .buf_typedef are implicit zero initialized
+// expected-error@+2{{cannot implicitly 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 defin

[clang] [OpenMP] codegen support for masked combined construct parallel masked taskloop (PR #121741)

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

alexey-bataev wrote:

Also update ReleaseNotes.rst here and in other patches

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


[clang] [clang][OpenMP] Add 'align' modifier for 'allocate' clause (PR #121814)

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


@@ -4530,32 +4530,87 @@ static bool parseStepSize(Parser &P, 
SemaOpenMP::OpenMPVarListDataTy &Data,
 }
 
 /// Parse 'allocate' clause modifiers.
-///   If allocator-modifier exists, return an expression for it and set
-///   Data field noting modifier was specified.
-///
+///   If allocator-modifier exists, return an expression for it. For both
+///   allocator and align modifiers, set Data fields as appropriate.
 static ExprResult
 parseOpenMPAllocateClauseModifiers(Parser &P, OpenMPClauseKind Kind,
SemaOpenMP::OpenMPVarListDataTy &Data) {
   const Token &Tok = P.getCurToken();
   Preprocessor &PP = P.getPreprocessor();
   ExprResult Tail;
-  auto Modifier = static_cast(
+  ExprResult Val;
+  SourceLocation RLoc;
+  bool AllocatorSeen = false;
+  bool AlignSeen = false;
+  SourceLocation CurrentModifierLoc = Tok.getLocation();
+  auto CurrentModifier = static_cast(
   getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), P.getLangOpts()));
-  if (Modifier == OMPC_ALLOCATE_allocator) {
-Data.AllocClauseModifier = Modifier;
+
+  // Modifiers did not exist before 5.1
+  if (P.getLangOpts().OpenMP < 51)
+return P.ParseAssignmentExpression();
+
+  // An allocator-simple-modifier is exclusive and must appear alone. See
+  // OpenMP6.0 spec, pg. 313, L1 on Modifiers, as well as Table 5.1, pg. 50,
+  // description of "exclusive" property. If we don't recognized an explicit
+  // simple-/complex- modifier, assume we're looking at expression
+  // representing allocator and consider ourselves done.
+  if (CurrentModifier == OMPC_ALLOCATE_unknown)
+return P.ParseAssignmentExpression();
+
+  do {
 P.ConsumeToken();
-BalancedDelimiterTracker AllocateT(P, tok::l_paren,
-   tok::annot_pragma_openmp_end);
 if (Tok.is(tok::l_paren)) {
-  AllocateT.consumeOpen();
-  Tail = P.ParseAssignmentExpression();
-  AllocateT.consumeClose();
+  switch (CurrentModifier) {
+  case OMPC_ALLOCATE_allocator: {
+if (AllocatorSeen) {
+  P.Diag(Tok, diag::err_omp_duplicate_modifier)
+  << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
+  << getOpenMPClauseName(Kind);
+} else {
+  Data.AllocClauseModifiers.push_back(CurrentModifier);
+  Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
+}
+BalancedDelimiterTracker AllocateT(P, tok::l_paren,
+   tok::annot_pragma_openmp_end);
+AllocateT.consumeOpen();
+Tail = P.ParseAssignmentExpression();
+AllocateT.consumeClose();
+AllocatorSeen = true;
+  } break;

alexey-bataev wrote:

and format

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


[clang] [clang][OpenMP] Add 'align' modifier for 'allocate' clause (PR #121814)

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


@@ -4530,32 +4530,87 @@ static bool parseStepSize(Parser &P, 
SemaOpenMP::OpenMPVarListDataTy &Data,
 }
 
 /// Parse 'allocate' clause modifiers.
-///   If allocator-modifier exists, return an expression for it and set
-///   Data field noting modifier was specified.
-///
+///   If allocator-modifier exists, return an expression for it. For both
+///   allocator and align modifiers, set Data fields as appropriate.
 static ExprResult
 parseOpenMPAllocateClauseModifiers(Parser &P, OpenMPClauseKind Kind,
SemaOpenMP::OpenMPVarListDataTy &Data) {
   const Token &Tok = P.getCurToken();
   Preprocessor &PP = P.getPreprocessor();
   ExprResult Tail;
-  auto Modifier = static_cast(
+  ExprResult Val;
+  SourceLocation RLoc;
+  bool AllocatorSeen = false;
+  bool AlignSeen = false;
+  SourceLocation CurrentModifierLoc = Tok.getLocation();
+  auto CurrentModifier = static_cast(
   getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), P.getLangOpts()));
-  if (Modifier == OMPC_ALLOCATE_allocator) {
-Data.AllocClauseModifier = Modifier;
+
+  // Modifiers did not exist before 5.1
+  if (P.getLangOpts().OpenMP < 51)
+return P.ParseAssignmentExpression();
+
+  // An allocator-simple-modifier is exclusive and must appear alone. See
+  // OpenMP6.0 spec, pg. 313, L1 on Modifiers, as well as Table 5.1, pg. 50,
+  // description of "exclusive" property. If we don't recognized an explicit
+  // simple-/complex- modifier, assume we're looking at expression
+  // representing allocator and consider ourselves done.
+  if (CurrentModifier == OMPC_ALLOCATE_unknown)
+return P.ParseAssignmentExpression();
+
+  do {
 P.ConsumeToken();
-BalancedDelimiterTracker AllocateT(P, tok::l_paren,
-   tok::annot_pragma_openmp_end);
 if (Tok.is(tok::l_paren)) {
-  AllocateT.consumeOpen();
-  Tail = P.ParseAssignmentExpression();
-  AllocateT.consumeClose();
+  switch (CurrentModifier) {
+  case OMPC_ALLOCATE_allocator: {
+if (AllocatorSeen) {
+  P.Diag(Tok, diag::err_omp_duplicate_modifier)
+  << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
+  << getOpenMPClauseName(Kind);
+} else {
+  Data.AllocClauseModifiers.push_back(CurrentModifier);
+  Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
+}
+BalancedDelimiterTracker AllocateT(P, tok::l_paren,
+   tok::annot_pragma_openmp_end);
+AllocateT.consumeOpen();
+Tail = P.ParseAssignmentExpression();
+AllocateT.consumeClose();
+AllocatorSeen = true;
+  } break;
+  case OMPC_ALLOCATE_align: {
+if (AlignSeen) {
+  P.Diag(Tok, diag::err_omp_duplicate_modifier)
+  << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
+  << getOpenMPClauseName(Kind);
+} else {
+  Data.AllocClauseModifiers.push_back(CurrentModifier);
+  Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
+}
+Val = P.ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
+if (Val.isUsable())
+  Data.AllocateAlignment = Val.get();
+AlignSeen = true;
+  } break;

alexey-bataev wrote:

Same

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


[clang] [clang][OpenMP] Add 'align' modifier for 'allocate' clause (PR #121814)

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


@@ -5285,6 +5285,7 @@ static void checkAllocateClauses(Sema &S, DSAStackTy 
*Stack,
   }
   for (OMPClause *C : AllocateRange) {
 auto *AC = cast(C);
+// TODO: Check alignment?

alexey-bataev wrote:

What are the missing checks here?

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


[clang] db81e8c - [OpenACC] Initial sema implementation of 'update' construct

2025-01-07 Thread via cfe-commits

Author: erichkeane
Date: 2025-01-07T08:20:20-08:00
New Revision: db81e8c42e121e62a00587b12d2b972dfcfb98c0

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

LOG: [OpenACC] Initial sema implementation of 'update' construct

This executable construct has a larger list of clauses than some of the
others, plus has some additional restrictions.  This patch implements
the AST node, plus the 'cannot be the body of a if, while, do, switch,
or label' statement restriction.  Future patches will handle the
rest of the restrictions, which are based on clauses.

Added: 
clang/test/AST/ast-print-openacc-update-construct.cpp
clang/test/SemaOpenACC/update-construct-ast.cpp
clang/test/SemaOpenACC/update-construct.cpp

Modified: 
clang/include/clang-c/Index.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/AST/StmtOpenACC.h
clang/include/clang/AST/TextNodeDumper.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/StmtNodes.td
clang/include/clang/Serialization/ASTBitCodes.h
clang/lib/AST/StmtOpenACC.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/AST/TextNodeDumper.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaExceptionSpec.cpp
clang/lib/Sema/SemaOpenACC.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/ParserOpenACC/parse-clauses.c
clang/test/ParserOpenACC/parse-constructs.c
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXCursor.cpp

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 3f95f1db2fbe51..63d266dc60ec73 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2202,7 +2202,11 @@ enum CXCursorKind {
*/
   CXCursor_OpenACCSetConstruct = 330,
 
-  CXCursor_LastStmt = CXCursor_OpenACCSetConstruct,
+  /** OpenACC update Construct.
+   */
+  CXCursor_OpenACCUpdateConstruct = 331,
+
+  CXCursor_LastStmt = CXCursor_OpenACCUpdateConstruct,
 
   /**
* Cursor that represents the translation unit itself.

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 92954cf566c832..d500f4eadef757 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -4082,6 +4082,8 @@ DEF_TRAVERSE_STMT(OpenACCShutdownConstruct,
   { TRY_TO(VisitOpenACCClauseList(S->clauses())); })
 DEF_TRAVERSE_STMT(OpenACCSetConstruct,
   { TRY_TO(VisitOpenACCClauseList(S->clauses())); })
+DEF_TRAVERSE_STMT(OpenACCUpdateConstruct,
+  { TRY_TO(VisitOpenACCClauseList(S->clauses())); })
 
 // Traverse HLSL: Out argument expression
 DEF_TRAVERSE_STMT(HLSLOutArgExpr, {})

diff  --git a/clang/include/clang/AST/StmtOpenACC.h 
b/clang/include/clang/AST/StmtOpenACC.h
index d3cc106ff00812..ebbee152f918f8 100644
--- a/clang/include/clang/AST/StmtOpenACC.h
+++ b/clang/include/clang/AST/StmtOpenACC.h
@@ -712,5 +712,44 @@ class OpenACCSetConstruct final
  SourceLocation End,
  ArrayRef Clauses);
 };
+// This class represents an 'update' construct, which has just a clause list.
+class OpenACCUpdateConstruct final
+: public OpenACCConstructStmt,
+  private llvm::TrailingObjects {
+  friend TrailingObjects;
+  OpenACCUpdateConstruct(unsigned NumClauses)
+  : OpenACCConstructStmt(OpenACCUpdateConstructClass,
+ OpenACCDirectiveKind::Update, SourceLocation{},
+ SourceLocation{}, SourceLocation{}) {
+std::uninitialized_value_construct(
+getTrailingObjects(),
+getTrailingObjects() + NumClauses);
+setClauseList(MutableArrayRef(getTrailingObjects(),
+  NumClauses));
+  }
+
+  OpenACCUpdateConstruct(SourceLocation Start, SourceLocation DirectiveLoc,
+ SourceLocation End,
+ ArrayRef Clauses)
+  : OpenACCConstructStmt(OpenACCUpdateConstructClass,
+ OpenACCDirectiveKind::Update, Start, DirectiveLoc,
+ End) {
+std::uninitialized_copy(Clauses.begin(), Clauses.end(),
+getTrailingObjects());
+setClauseList(MutableArrayRef(getTrailingObjects(),
+  Clauses.size()));
+  }
+
+public:
+  static bool classof(const Stmt *T) {
+return T->getStmtClass() == OpenACCUpdateConstructClass;
+  }
+  st

[clang] dd1e8aa - [OpenACC] Enable 'if' and 'if_present' for 'update' construct

2025-01-07 Thread via cfe-commits

Author: erichkeane
Date: 2025-01-07T08:20:20-08:00
New Revision: dd1e8aa09c0ab453a0566165b68e6a62fcd055e1

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

LOG: [OpenACC] Enable 'if' and 'if_present' for 'update' construct

The only restriction on 'if' is that only 1 can appear on an update
construct, so this enforces that.  'if_present' has no restrictions.

Added: 


Modified: 
clang/lib/Sema/SemaOpenACC.cpp
clang/test/AST/ast-print-openacc-update-construct.cpp
clang/test/ParserOpenACC/parse-clauses.c
clang/test/SemaOpenACC/update-construct-ast.cpp
clang/test/SemaOpenACC/update-construct.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenACC.cpp b/clang/lib/Sema/SemaOpenACC.cpp
index 1ab033cbbfc1a8..716749f08c5831 100644
--- a/clang/lib/Sema/SemaOpenACC.cpp
+++ b/clang/lib/Sema/SemaOpenACC.cpp
@@ -709,18 +709,11 @@ OpenACCClause *SemaOpenACCClauseVisitor::VisitTileClause(
 
 OpenACCClause *SemaOpenACCClauseVisitor::VisitIfClause(
 SemaOpenACC::OpenACCParsedClause &Clause) {
-  // Restrictions only properly implemented on 'compute'/'combined'/'data'
-  // constructs, and 'compute'/'combined'/'data' constructs are the only
-  // constructs that can do anything with this yet, so skip/treat as
-  // unimplemented in this case.
-  if (!isDirectiveKindImplemented(Clause.getDirectiveKind()))
-return isNotImplemented();
-
   // There is no prose in the standard that says duplicates aren't allowed,
   // but this diagnostic is present in other compilers, as well as makes
   // sense. Prose DOES exist for 'data' and 'host_data', 'set', 'enter data' 
and
   // 'exit data' both don't, but other implmementations do this.  OpenACC issue
-  // 519 filed for the latter two.
+  // 519 filed for the latter two. Prose also exists for 'update'.
   // GCC allows this on init/shutdown, presumably for good reason, so we do 
too.
   if (Clause.getDirectiveKind() != OpenACCDirectiveKind::Init &&
   Clause.getDirectiveKind() != OpenACCDirectiveKind::Shutdown &&
@@ -1744,8 +1737,6 @@ OpenACCClause 
*SemaOpenACCClauseVisitor::VisitFinalizeClause(
 
 OpenACCClause *SemaOpenACCClauseVisitor::VisitIfPresentClause(
 SemaOpenACC::OpenACCParsedClause &Clause) {
-  if (!isDirectiveKindImplemented(Clause.getDirectiveKind()))
-return isNotImplemented();
   // There isn't anything to do here, this is only valid on one construct, and
   // has no associated rules.
   return OpenACCIfPresentClause::Create(Ctx, Clause.getBeginLoc(),

diff  --git a/clang/test/AST/ast-print-openacc-update-construct.cpp 
b/clang/test/AST/ast-print-openacc-update-construct.cpp
index db9d1c0855c982..89210cc0124ca1 100644
--- a/clang/test/AST/ast-print-openacc-update-construct.cpp
+++ b/clang/test/AST/ast-print-openacc-update-construct.cpp
@@ -1,5 +1,10 @@
 // RUN: %clang_cc1 -fopenacc -ast-print %s -o - | FileCheck %s
-void uses() {
+void uses(bool cond) {
   // CHECK: #pragma acc update
 #pragma acc update
+
+// CHECK: #pragma acc update if_present
+#pragma acc update if_present
+// CHECK: #pragma acc update if(cond)
+#pragma acc update if(cond)
 }

diff  --git a/clang/test/ParserOpenACC/parse-clauses.c 
b/clang/test/ParserOpenACC/parse-clauses.c
index 3da06c3af63f37..9b88c147d0faa2 100644
--- a/clang/test/ParserOpenACC/parse-clauses.c
+++ b/clang/test/ParserOpenACC/parse-clauses.c
@@ -347,16 +347,14 @@ void SelfUpdate() {
 #pragma acc update self
   for(int i = 0; i < 5;++i) {}
 
-  // expected-error@+5{{use of undeclared identifier 'zero'}}
-  // expected-error@+4{{expected ','}}
-  // expected-error@+3{{expected expression}}
-  // expected-warning@+2{{OpenACC clause 'self' not yet implemented, clause 
ignored}}
-  // expected-warning@+1{{OpenACC clause 'if_present' not yet implemented, 
clause ignored}}
+  // expected-error@+4{{use of undeclared identifier 'zero'}}
+  // expected-error@+3{{expected ','}}
+  // expected-error@+2{{expected expression}}
+  // expected-warning@+1{{OpenACC clause 'self' not yet implemented, clause 
ignored}}
 #pragma acc update self(zero : s.array[s.value : 5], s.value), if_present
   for(int i = 0; i < 5;++i) {}
 
-  // expected-warning@+2{{OpenACC clause 'self' not yet implemented, clause 
ignored}}
-  // expected-warning@+1{{OpenACC clause 'if_present' not yet implemented, 
clause ignored}}
+  // expected-warning@+1{{OpenACC clause 'self' not yet implemented, clause 
ignored}}
 #pragma acc update self(s.array[s.value : 5], s.value), if_present
   for(int i = 0; i < 5;++i) {}
 }

diff  --git a/clang/test/SemaOpenACC/update-construct-ast.cpp 
b/clang/test/SemaOpenACC/update-construct-ast.cpp
index 0e793428ec9b82..097ca6fc97d405 100644
--- a/clang/test/SemaOpenACC/update-construct-ast.cpp
+++ b/clang/test/SemaOpenACC/update-construct-ast.cpp
@@ -6,12 +6,26 @@
 
 #i

[clang] [clang][OpenMP] Add 'align' modifier for 'allocate' clause (PR #121814)

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


@@ -4530,32 +4530,87 @@ static bool parseStepSize(Parser &P, 
SemaOpenMP::OpenMPVarListDataTy &Data,
 }
 
 /// Parse 'allocate' clause modifiers.
-///   If allocator-modifier exists, return an expression for it and set
-///   Data field noting modifier was specified.
-///
+///   If allocator-modifier exists, return an expression for it. For both
+///   allocator and align modifiers, set Data fields as appropriate.
 static ExprResult
 parseOpenMPAllocateClauseModifiers(Parser &P, OpenMPClauseKind Kind,
SemaOpenMP::OpenMPVarListDataTy &Data) {
   const Token &Tok = P.getCurToken();
   Preprocessor &PP = P.getPreprocessor();
   ExprResult Tail;
-  auto Modifier = static_cast(
+  ExprResult Val;
+  SourceLocation RLoc;
+  bool AllocatorSeen = false;
+  bool AlignSeen = false;
+  SourceLocation CurrentModifierLoc = Tok.getLocation();
+  auto CurrentModifier = static_cast(
   getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), P.getLangOpts()));
-  if (Modifier == OMPC_ALLOCATE_allocator) {
-Data.AllocClauseModifier = Modifier;
+
+  // Modifiers did not exist before 5.1
+  if (P.getLangOpts().OpenMP < 51)
+return P.ParseAssignmentExpression();
+
+  // An allocator-simple-modifier is exclusive and must appear alone. See
+  // OpenMP6.0 spec, pg. 313, L1 on Modifiers, as well as Table 5.1, pg. 50,
+  // description of "exclusive" property. If we don't recognized an explicit
+  // simple-/complex- modifier, assume we're looking at expression
+  // representing allocator and consider ourselves done.
+  if (CurrentModifier == OMPC_ALLOCATE_unknown)
+return P.ParseAssignmentExpression();
+
+  do {
 P.ConsumeToken();
-BalancedDelimiterTracker AllocateT(P, tok::l_paren,
-   tok::annot_pragma_openmp_end);
 if (Tok.is(tok::l_paren)) {
-  AllocateT.consumeOpen();
-  Tail = P.ParseAssignmentExpression();
-  AllocateT.consumeClose();
+  switch (CurrentModifier) {
+  case OMPC_ALLOCATE_allocator: {
+if (AllocatorSeen) {
+  P.Diag(Tok, diag::err_omp_duplicate_modifier)
+  << getOpenMPSimpleClauseTypeName(OMPC_allocate, CurrentModifier)
+  << getOpenMPClauseName(Kind);
+} else {
+  Data.AllocClauseModifiers.push_back(CurrentModifier);
+  Data.AllocClauseModifiersLoc.push_back(CurrentModifierLoc);
+}
+BalancedDelimiterTracker AllocateT(P, tok::l_paren,
+   tok::annot_pragma_openmp_end);
+AllocateT.consumeOpen();
+Tail = P.ParseAssignmentExpression();
+AllocateT.consumeClose();
+AllocatorSeen = true;
+  } break;

alexey-bataev wrote:

```suggestion
  break;}
```


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


[clang-tools-extra] [clang-tidy] Address false positives in misc-redundant-expression checker (PR #121960)

2025-01-07 Thread via cfe-commits

https://github.com/earnol created 
https://github.com/llvm/llvm-project/pull/121960

This patch addresses situations when misc-redundant-expression checker provides 
excessive diagnostics for situations with different macros having the same 
value. In particular it addresses situations described in the initial report of 
https://github.com/llvm/llvm-project/issues/118885 are addressed. The 
situations which are popped inside discussion like if (A + B == B + A) for 
macros are not properly addressed by this patch.

>From abd79628aa576709dcbce3c755d1aa98087c0f04 Mon Sep 17 00:00:00 2001
From: Vladislav Aranov 
Date: Tue, 7 Jan 2025 11:11:44 -0500
Subject: [PATCH] [clang-tidy] Address false positives in
 misc-redundant-expression checker

Address situations when misc-redundant-expression checker provides excessive
diagnostics for situations with different macros having the same value.
In perticular situations described in the initial report of
https://github.com/llvm/llvm-project/issues/118885 are addressed.
The situations which are popped inside discussion like
if (A + B == B + A) for macros are not properly addressed by this patch.
But i still believe even in the current state the patch can be useful.
---
 .../misc/RedundantExpressionCheck.cpp | 118 +++---
 .../checkers/misc/redundant-expression.cpp| 150 ++
 2 files changed, 249 insertions(+), 19 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
index fc35bc22c52e04..d6136c40d64cc8 100644
--- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -139,10 +139,8 @@ static bool areEquivalentExpr(const Expr *Left, const Expr 
*Right) {
 return cast(Left)->getOpcode() ==
cast(Right)->getOpcode();
   case Stmt::UnaryExprOrTypeTraitExprClass:
-const auto *LeftUnaryExpr =
-cast(Left);
-const auto *RightUnaryExpr =
-cast(Right);
+const auto *LeftUnaryExpr = cast(Left);
+const auto *RightUnaryExpr = cast(Right);
 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
   return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
  LeftUnaryExpr->getArgumentType() ==
@@ -699,7 +697,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 
 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
 OperandExpr = OverloadedOperatorExpr;
-Opcode = 
BinaryOperator::getOverloadedOpcode(OverloadedOperatorExpr->getOperator());
+Opcode = BinaryOperator::getOverloadedOpcode(
+OverloadedOperatorExpr->getOperator());
 
 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
   return false;
@@ -728,7 +727,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 }
 
 // Checks for expressions like (X == 4) && (Y != 9)
-static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const 
ASTContext *AstCtx) {
+static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp,
+   const ASTContext *AstCtx) {
   const auto *LhsBinOp = dyn_cast(BinOp->getLHS());
   const auto *RhsBinOp = dyn_cast(BinOp->getRHS());
 
@@ -747,6 +747,31 @@ static bool areSidesBinaryConstExpressions(const 
BinaryOperator *&BinOp, const A
   return false;
 }
 
+static bool
+areSidesBinaryConstExpressionsOrDefines(const BinaryOperator *&BinOp,
+const ASTContext *AstCtx) {
+  if (areSidesBinaryConstExpressions(BinOp, AstCtx))
+return true;
+
+  const auto *Lhs = BinOp->getLHS();
+  const auto *Rhs = BinOp->getRHS();
+
+  if (!Lhs || !Rhs)
+return false;
+
+  auto IsDefineExpr = [AstCtx](const Expr *E) {
+SourceRange Lsr = E->getSourceRange();
+if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
+!E->isIntegerConstantExpr(*AstCtx))
+  return false;
+return true;
+  };
+
+  if (IsDefineExpr(Lhs) || IsDefineExpr(Rhs))
+return true;
+  return false;
+}
+
 // Retrieves integer constant subexpressions from binary operator expressions
 // that have two equivalent sides.
 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
@@ -785,7 +810,7 @@ static bool retrieveConstExprFromBothSides(const 
BinaryOperator *&BinOp,
 }
 
 static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
-const SourceManager &SM) {
+ const SourceManager &SM) {
   if (T1.getKind() != T2.getKind())
 return false;
   if (T1.isNot(tok::raw_identifier))
@@ -852,6 +877,58 @@ static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
 
   return LhsLoc.isMacroID() != RhsLoc.isMacroID();
 }
+
+static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
+   const ASTContext *Context) {
+
+  if (!BinOp)
+return false;
+

[clang-tools-extra] [clang-tidy] Address false positives in misc-redundant-expression checker (PR #121960)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: None (earnol)


Changes

This patch addresses situations when misc-redundant-expression checker provides 
excessive diagnostics for situations with different macros having the same 
value. In particular it addresses situations described in the initial report of 
https://github.com/llvm/llvm-project/issues/118885 are addressed. The 
situations which are popped inside discussion like if (A + B == B + A) for 
macros are not properly addressed by this patch.

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp 
(+99-19) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp (+150) 


``diff
diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
index fc35bc22c52e04..d6136c40d64cc8 100644
--- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -139,10 +139,8 @@ static bool areEquivalentExpr(const Expr *Left, const Expr 
*Right) {
 return cast(Left)->getOpcode() ==
cast(Right)->getOpcode();
   case Stmt::UnaryExprOrTypeTraitExprClass:
-const auto *LeftUnaryExpr =
-cast(Left);
-const auto *RightUnaryExpr =
-cast(Right);
+const auto *LeftUnaryExpr = cast(Left);
+const auto *RightUnaryExpr = cast(Right);
 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
   return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
  LeftUnaryExpr->getArgumentType() ==
@@ -699,7 +697,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 
 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
 OperandExpr = OverloadedOperatorExpr;
-Opcode = 
BinaryOperator::getOverloadedOpcode(OverloadedOperatorExpr->getOperator());
+Opcode = BinaryOperator::getOverloadedOpcode(
+OverloadedOperatorExpr->getOperator());
 
 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
   return false;
@@ -728,7 +727,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 }
 
 // Checks for expressions like (X == 4) && (Y != 9)
-static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const 
ASTContext *AstCtx) {
+static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp,
+   const ASTContext *AstCtx) {
   const auto *LhsBinOp = dyn_cast(BinOp->getLHS());
   const auto *RhsBinOp = dyn_cast(BinOp->getRHS());
 
@@ -747,6 +747,31 @@ static bool areSidesBinaryConstExpressions(const 
BinaryOperator *&BinOp, const A
   return false;
 }
 
+static bool
+areSidesBinaryConstExpressionsOrDefines(const BinaryOperator *&BinOp,
+const ASTContext *AstCtx) {
+  if (areSidesBinaryConstExpressions(BinOp, AstCtx))
+return true;
+
+  const auto *Lhs = BinOp->getLHS();
+  const auto *Rhs = BinOp->getRHS();
+
+  if (!Lhs || !Rhs)
+return false;
+
+  auto IsDefineExpr = [AstCtx](const Expr *E) {
+SourceRange Lsr = E->getSourceRange();
+if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
+!E->isIntegerConstantExpr(*AstCtx))
+  return false;
+return true;
+  };
+
+  if (IsDefineExpr(Lhs) || IsDefineExpr(Rhs))
+return true;
+  return false;
+}
+
 // Retrieves integer constant subexpressions from binary operator expressions
 // that have two equivalent sides.
 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
@@ -785,7 +810,7 @@ static bool retrieveConstExprFromBothSides(const 
BinaryOperator *&BinOp,
 }
 
 static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
-const SourceManager &SM) {
+ const SourceManager &SM) {
   if (T1.getKind() != T2.getKind())
 return false;
   if (T1.isNot(tok::raw_identifier))
@@ -852,6 +877,58 @@ static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
 
   return LhsLoc.isMacroID() != RhsLoc.isMacroID();
 }
+
+static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
+   const ASTContext *Context) {
+
+  if (!BinOp)
+return false;
+
+  const auto *Lhs = BinOp->getLHS();
+  const auto *Rhs = BinOp->getRHS();
+  const SourceManager &SM = Context->getSourceManager();
+
+  SourceRange Lsr = Lhs->getSourceRange();
+  SourceRange Rsr = Rhs->getSourceRange();
+  if (Lsr.getBegin().isMacroID()) {
+// Left is macro so right macro too
+if (Rsr.getBegin().isMacroID()) {
+  // Both sides are macros so they are same macro or literal
+  llvm::StringRef L = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Lsr), SM, LangOptions(), 0);
+  llvm::StringRef R = Lexer::getSourceText(
+  CharSourceRange::getTo

[clang-tools-extra] [clang-tidy] Address false positives in misc-redundant-expression checker (PR #121960)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




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

Author: None (earnol)


Changes

This patch addresses situations when misc-redundant-expression checker provides 
excessive diagnostics for situations with different macros having the same 
value. In particular it addresses situations described in the initial report of 
https://github.com/llvm/llvm-project/issues/118885 are addressed. The 
situations which are popped inside discussion like if (A + B == B + A) for 
macros are not properly addressed by this patch.

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp 
(+99-19) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp (+150) 


``diff
diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
index fc35bc22c52e04..d6136c40d64cc8 100644
--- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -139,10 +139,8 @@ static bool areEquivalentExpr(const Expr *Left, const Expr 
*Right) {
 return cast(Left)->getOpcode() ==
cast(Right)->getOpcode();
   case Stmt::UnaryExprOrTypeTraitExprClass:
-const auto *LeftUnaryExpr =
-cast(Left);
-const auto *RightUnaryExpr =
-cast(Right);
+const auto *LeftUnaryExpr = cast(Left);
+const auto *RightUnaryExpr = cast(Right);
 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
   return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
  LeftUnaryExpr->getArgumentType() ==
@@ -699,7 +697,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 
 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
 OperandExpr = OverloadedOperatorExpr;
-Opcode = 
BinaryOperator::getOverloadedOpcode(OverloadedOperatorExpr->getOperator());
+Opcode = BinaryOperator::getOverloadedOpcode(
+OverloadedOperatorExpr->getOperator());
 
 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
   return false;
@@ -728,7 +727,8 @@ static bool retrieveRelationalIntegerConstantExpr(
 }
 
 // Checks for expressions like (X == 4) && (Y != 9)
-static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const 
ASTContext *AstCtx) {
+static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp,
+   const ASTContext *AstCtx) {
   const auto *LhsBinOp = dyn_cast(BinOp->getLHS());
   const auto *RhsBinOp = dyn_cast(BinOp->getRHS());
 
@@ -747,6 +747,31 @@ static bool areSidesBinaryConstExpressions(const 
BinaryOperator *&BinOp, const A
   return false;
 }
 
+static bool
+areSidesBinaryConstExpressionsOrDefines(const BinaryOperator *&BinOp,
+const ASTContext *AstCtx) {
+  if (areSidesBinaryConstExpressions(BinOp, AstCtx))
+return true;
+
+  const auto *Lhs = BinOp->getLHS();
+  const auto *Rhs = BinOp->getRHS();
+
+  if (!Lhs || !Rhs)
+return false;
+
+  auto IsDefineExpr = [AstCtx](const Expr *E) {
+SourceRange Lsr = E->getSourceRange();
+if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
+!E->isIntegerConstantExpr(*AstCtx))
+  return false;
+return true;
+  };
+
+  if (IsDefineExpr(Lhs) || IsDefineExpr(Rhs))
+return true;
+  return false;
+}
+
 // Retrieves integer constant subexpressions from binary operator expressions
 // that have two equivalent sides.
 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
@@ -785,7 +810,7 @@ static bool retrieveConstExprFromBothSides(const 
BinaryOperator *&BinOp,
 }
 
 static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
-const SourceManager &SM) {
+ const SourceManager &SM) {
   if (T1.getKind() != T2.getKind())
 return false;
   if (T1.isNot(tok::raw_identifier))
@@ -852,6 +877,58 @@ static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
 
   return LhsLoc.isMacroID() != RhsLoc.isMacroID();
 }
+
+static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
+   const ASTContext *Context) {
+
+  if (!BinOp)
+return false;
+
+  const auto *Lhs = BinOp->getLHS();
+  const auto *Rhs = BinOp->getRHS();
+  const SourceManager &SM = Context->getSourceManager();
+
+  SourceRange Lsr = Lhs->getSourceRange();
+  SourceRange Rsr = Rhs->getSourceRange();
+  if (Lsr.getBegin().isMacroID()) {
+// Left is macro so right macro too
+if (Rsr.getBegin().isMacroID()) {
+  // Both sides are macros so they are same macro or literal
+  llvm::StringRef L = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Lsr), SM, LangOptions(), 0);
+  llvm::StringRef R = Lexer::getSourceText(
+  CharSourceRange

[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2025-01-07 Thread Louis Dionne via cfe-commits

https://github.com/ldionne updated 
https://github.com/llvm/llvm-project/pull/120149

>From ac165075f270af65395a3709a1457b61ed97ea31 Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Mon, 16 Dec 2024 13:28:38 -0500
Subject: [PATCH 1/6] [clang][Darwin] Remove legacy framework search path logic
 in the frontend

This removes a long standing piece of technical debt. Most other platforms
have moved all their header search path logic to the driver, but Darwin
still had some logic for setting framework search paths present in the
frontend. This patch moves that logic to the driver alongside existing
logic that already handles part of these search paths.

To achieve parity with the previous search path order, this patch
introduces the -internal-iframework flag which is used to pass
system framework paths from the driver to the frontend. These paths
are handled specially in that they are added after normal framework
search paths, which preserves the old frontend behavior for system
frameworks.

This patch is a re-application of 
https://github.com/llvm/llvm-project/pull/75841
which was reverted in d34901f30 because it broke framework search paths.
In fact, the original patch was only adding framework search paths to
the linker job, but was not adding search paths for finding headers.
That issue is resolved in this version of the patch, with added tests.

Fixes #75638
---
 clang/include/clang/Driver/Options.td |  5 ++
 clang/lib/Driver/Job.cpp  |  2 +-
 clang/lib/Driver/ToolChains/Darwin.cpp| 49 ++-
 clang/lib/Frontend/CompilerInvocation.cpp |  7 ++-
 clang/lib/Lex/InitHeaderSearch.cpp| 19 ++-
 .../Driver/darwin-framework-search-paths.c| 26 ++
 clang/test/Driver/darwin-subframeworks.c  | 18 ---
 .../test/Preprocessor/cuda-macos-includes.cu  | 13 ++---
 8 files changed, 79 insertions(+), 60 deletions(-)
 create mode 100644 clang/test/Driver/darwin-framework-search-paths.c
 delete mode 100644 clang/test/Driver/darwin-subframeworks.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0528104f055158..8fa811845dfbcc 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8298,6 +8298,11 @@ def internal_externc_isystem : Separate<["-"], 
"internal-externc-isystem">,
"implicit extern \"C\" semantics; these are assumed to not be "
"user-provided and are used to model system and standard headers' "
"paths.">;
+def internal_iframework : Separate<["-"], "internal-iframework">,
+  MetaVarName<"">,
+  HelpText<"Add directory to the internal system framework include search 
path; these "
+   "are assumed to not be user-provided and are used to model system "
+   "and standard frameworks' paths.">;
 
 } // let Visibility = [CC1Option]
 
diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp
index ae2f1cd1f56c99..07d2d371c5626b 100644
--- a/clang/lib/Driver/Job.cpp
+++ b/clang/lib/Driver/Job.cpp
@@ -73,7 +73,7 @@ static bool skipArgs(const char *Flag, bool HaveCrashVFS, int 
&SkipNum,
 .Cases("-internal-externc-isystem", "-iprefix", true)
 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
 .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
-.Cases("-iframework", "-include-pch", true)
+.Cases("-internal-iframework", "-iframework", "-include-pch", true)
 .Default(false);
   if (IsInclude)
 return !HaveCrashVFS;
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 56b6dd78673cb6..19fd4dc148da73 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -800,9 +800,15 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 }
   }
 
-  // Add non-standard, platform-specific search paths, e.g., for DriverKit:
-  //  -L/System/DriverKit/usr/lib
-  //  -F/System/DriverKit/System/Library/Framework
+  // Add framework include paths and library search paths.
+  // There are two flavors:
+  // 1. The "non-standard" paths, e.g. for DriverKit:
+  //  -L/System/DriverKit/usr/lib
+  //  -F/System/DriverKit/System/Library/Frameworks
+  // 2. The "standard" paths, e.g. for macOS and iOS:
+  //  -F/System/Library/Frameworks
+  //  -F/System/Library/SubFrameworks
+  //  -F/Library/Frameworks
   {
 bool NonStandardSearchPath = false;
 const auto &Triple = getToolChain().getTriple();
@@ -813,18 +819,23 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   (Version.getMajor() == 605 && Version.getMinor().value_or(0) < 1);
 }
 
-if (NonStandardSearchPath) {
-  if (auto *Sysroot = Args.getLastArg(options::OPT_isysroot)) {
-auto AddSearchPath = [&](StringRef Flag, StringRef SearchPath) {
-  SmallString<128> P(Sysroot->getValue());
-  AppendPlatformPrefix(P, Triple);
-   

[clang] [llvm] [HLSL] Explicitly set the SPIR-V version with spv-target-env (PR #121961)

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

https://github.com/s-perron created 
https://github.com/llvm/llvm-project/pull/121961

In DXC, setting the vulkan version automatically sets the target spir-v
version to the maximum spir-v version that the vulkan version must
support. So for Vulkan 1.2, we set the spir-v version to spirv 1.5
because every implementation of Vulkan 1.2 must support spirv 1.5, but
not spir-v 1.6.


>From 3651bfc84db36b90799bad4bf8344be99aa51879 Mon Sep 17 00:00:00 2001
From: Steven Perron 
Date: Mon, 6 Jan 2025 15:22:03 -0500
Subject: [PATCH] [HLSL] Explicitly set the SPIR-V version with spv-target-env

In DXC, setting the vulkan version automatically sets the target spir-v
version to the maximum spir-v version that the vulkan version must
support. So for Vulkan 1.2, we set the spir-v version to spirv 1.5
because every implementation of Vulkan 1.2 must support spirv 1.5, but
not spir-v 1.6.
---
 clang/lib/Driver/Driver.cpp  | 11 ---
 clang/test/Driver/dxc_spirv.hlsl |  4 ++--
 llvm/lib/TargetParser/Triple.cpp | 20 
 3 files changed, 30 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 36d6c93c43321f..a31fb3fc08a42f 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1468,9 +1468,14 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
 
 // Set specific Vulkan version if applicable.
 if (const Arg *A = Args.getLastArg(options::OPT_fspv_target_env_EQ)) {
-  const llvm::StringSet<> ValidValues = {"vulkan1.2", "vulkan1.3"};
-  if (ValidValues.contains(A->getValue())) {
-T.setOSName(A->getValue());
+  const llvm::StringMap ValidTargets = {
+  {"vulkan1.2", llvm::Triple::SPIRVSubArch_v15},
+  {"vulkan1.3", llvm::Triple::SPIRVSubArch_v16}};
+
+  auto TargetInfo = ValidTargets.find(A->getValue());
+  if (TargetInfo != ValidTargets.end()) {
+T.setOSName(TargetInfo->getKey());
+T.setArch(llvm::Triple::spirv, TargetInfo->getValue());
   } else {
 Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
diff --git a/clang/test/Driver/dxc_spirv.hlsl b/clang/test/Driver/dxc_spirv.hlsl
index c087ea4b0d709f..e6624e5f1b3f6f 100644
--- a/clang/test/Driver/dxc_spirv.hlsl
+++ b/clang/test/Driver/dxc_spirv.hlsl
@@ -6,8 +6,8 @@
 // CHECK: "-triple" "spirv-unknown-vulkan-compute"
 // CHECK-SAME: "-x" "hlsl"
 
-// CHECK-VULKAN12: "-triple" "spirv-unknown-vulkan1.2-compute"
+// CHECK-VULKAN12: "-triple" "spirv1.5-unknown-vulkan1.2-compute"
 
-// CHECK-VULKAN13: "-triple" "spirv-unknown-vulkan1.3-compute"
+// CHECK-VULKAN13: "-triple" "spirv1.6-unknown-vulkan1.3-compute"
 
 // CHECK-ERROR: error: invalid value 'vulkan1.0' in 
'-fspv-target-env=vulkan1.0'
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cpp
index 7e040688dc1a7b..4c1de09e91f21c 100644
--- a/llvm/lib/TargetParser/Triple.cpp
+++ b/llvm/lib/TargetParser/Triple.cpp
@@ -113,6 +113,26 @@ StringRef Triple::getArchName(ArchType Kind, SubArchType 
SubArch) {
 if (SubArch == AArch64SubArch_arm64e)
   return "arm64e";
 break;
+  case Triple::spirv:
+switch (SubArch) {
+case Triple::SPIRVSubArch_v10:
+  return "spirv1.0";
+case Triple::SPIRVSubArch_v11:
+  return "spirv1.1";
+case Triple::SPIRVSubArch_v12:
+  return "spirv1.2";
+case Triple::SPIRVSubArch_v13:
+  return "spirv1.3";
+case Triple::SPIRVSubArch_v14:
+  return "spirv1.4";
+case Triple::SPIRVSubArch_v15:
+  return "spirv1.5";
+case Triple::SPIRVSubArch_v16:
+  return "spirv1.6";
+default:
+  break;
+}
+break;
   case Triple::dxil:
 switch (SubArch) {
 case Triple::NoSubArch:

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


[clang] [llvm] [HLSL] Explicitly set the SPIR-V version with spv-target-env (PR #121961)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Steven Perron (s-perron)


Changes

In DXC, setting the vulkan version automatically sets the target spir-v
version to the maximum spir-v version that the vulkan version must
support. So for Vulkan 1.2, we set the spir-v version to spirv 1.5
because every implementation of Vulkan 1.2 must support spirv 1.5, but
not spir-v 1.6.


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


3 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+8-3) 
- (modified) clang/test/Driver/dxc_spirv.hlsl (+2-2) 
- (modified) llvm/lib/TargetParser/Triple.cpp (+20) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 36d6c93c43321f..a31fb3fc08a42f 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1468,9 +1468,14 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
 
 // Set specific Vulkan version if applicable.
 if (const Arg *A = Args.getLastArg(options::OPT_fspv_target_env_EQ)) {
-  const llvm::StringSet<> ValidValues = {"vulkan1.2", "vulkan1.3"};
-  if (ValidValues.contains(A->getValue())) {
-T.setOSName(A->getValue());
+  const llvm::StringMap ValidTargets = {
+  {"vulkan1.2", llvm::Triple::SPIRVSubArch_v15},
+  {"vulkan1.3", llvm::Triple::SPIRVSubArch_v16}};
+
+  auto TargetInfo = ValidTargets.find(A->getValue());
+  if (TargetInfo != ValidTargets.end()) {
+T.setOSName(TargetInfo->getKey());
+T.setArch(llvm::Triple::spirv, TargetInfo->getValue());
   } else {
 Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
diff --git a/clang/test/Driver/dxc_spirv.hlsl b/clang/test/Driver/dxc_spirv.hlsl
index c087ea4b0d709f..e6624e5f1b3f6f 100644
--- a/clang/test/Driver/dxc_spirv.hlsl
+++ b/clang/test/Driver/dxc_spirv.hlsl
@@ -6,8 +6,8 @@
 // CHECK: "-triple" "spirv-unknown-vulkan-compute"
 // CHECK-SAME: "-x" "hlsl"
 
-// CHECK-VULKAN12: "-triple" "spirv-unknown-vulkan1.2-compute"
+// CHECK-VULKAN12: "-triple" "spirv1.5-unknown-vulkan1.2-compute"
 
-// CHECK-VULKAN13: "-triple" "spirv-unknown-vulkan1.3-compute"
+// CHECK-VULKAN13: "-triple" "spirv1.6-unknown-vulkan1.3-compute"
 
 // CHECK-ERROR: error: invalid value 'vulkan1.0' in 
'-fspv-target-env=vulkan1.0'
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cpp
index 7e040688dc1a7b..4c1de09e91f21c 100644
--- a/llvm/lib/TargetParser/Triple.cpp
+++ b/llvm/lib/TargetParser/Triple.cpp
@@ -113,6 +113,26 @@ StringRef Triple::getArchName(ArchType Kind, SubArchType 
SubArch) {
 if (SubArch == AArch64SubArch_arm64e)
   return "arm64e";
 break;
+  case Triple::spirv:
+switch (SubArch) {
+case Triple::SPIRVSubArch_v10:
+  return "spirv1.0";
+case Triple::SPIRVSubArch_v11:
+  return "spirv1.1";
+case Triple::SPIRVSubArch_v12:
+  return "spirv1.2";
+case Triple::SPIRVSubArch_v13:
+  return "spirv1.3";
+case Triple::SPIRVSubArch_v14:
+  return "spirv1.4";
+case Triple::SPIRVSubArch_v15:
+  return "spirv1.5";
+case Triple::SPIRVSubArch_v16:
+  return "spirv1.6";
+default:
+  break;
+}
+break;
   case Triple::dxil:
 switch (SubArch) {
 case Triple::NoSubArch:

``




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


[clang] [llvm] [HLSL] Explicitly set the SPIR-V version with spv-target-env (PR #121961)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Steven Perron (s-perron)


Changes

In DXC, setting the vulkan version automatically sets the target spir-v
version to the maximum spir-v version that the vulkan version must
support. So for Vulkan 1.2, we set the spir-v version to spirv 1.5
because every implementation of Vulkan 1.2 must support spirv 1.5, but
not spir-v 1.6.


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


3 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+8-3) 
- (modified) clang/test/Driver/dxc_spirv.hlsl (+2-2) 
- (modified) llvm/lib/TargetParser/Triple.cpp (+20) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 36d6c93c43321f..a31fb3fc08a42f 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1468,9 +1468,14 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
 
 // Set specific Vulkan version if applicable.
 if (const Arg *A = Args.getLastArg(options::OPT_fspv_target_env_EQ)) {
-  const llvm::StringSet<> ValidValues = {"vulkan1.2", "vulkan1.3"};
-  if (ValidValues.contains(A->getValue())) {
-T.setOSName(A->getValue());
+  const llvm::StringMap ValidTargets = {
+  {"vulkan1.2", llvm::Triple::SPIRVSubArch_v15},
+  {"vulkan1.3", llvm::Triple::SPIRVSubArch_v16}};
+
+  auto TargetInfo = ValidTargets.find(A->getValue());
+  if (TargetInfo != ValidTargets.end()) {
+T.setOSName(TargetInfo->getKey());
+T.setArch(llvm::Triple::spirv, TargetInfo->getValue());
   } else {
 Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
diff --git a/clang/test/Driver/dxc_spirv.hlsl b/clang/test/Driver/dxc_spirv.hlsl
index c087ea4b0d709f..e6624e5f1b3f6f 100644
--- a/clang/test/Driver/dxc_spirv.hlsl
+++ b/clang/test/Driver/dxc_spirv.hlsl
@@ -6,8 +6,8 @@
 // CHECK: "-triple" "spirv-unknown-vulkan-compute"
 // CHECK-SAME: "-x" "hlsl"
 
-// CHECK-VULKAN12: "-triple" "spirv-unknown-vulkan1.2-compute"
+// CHECK-VULKAN12: "-triple" "spirv1.5-unknown-vulkan1.2-compute"
 
-// CHECK-VULKAN13: "-triple" "spirv-unknown-vulkan1.3-compute"
+// CHECK-VULKAN13: "-triple" "spirv1.6-unknown-vulkan1.3-compute"
 
 // CHECK-ERROR: error: invalid value 'vulkan1.0' in 
'-fspv-target-env=vulkan1.0'
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cpp
index 7e040688dc1a7b..4c1de09e91f21c 100644
--- a/llvm/lib/TargetParser/Triple.cpp
+++ b/llvm/lib/TargetParser/Triple.cpp
@@ -113,6 +113,26 @@ StringRef Triple::getArchName(ArchType Kind, SubArchType 
SubArch) {
 if (SubArch == AArch64SubArch_arm64e)
   return "arm64e";
 break;
+  case Triple::spirv:
+switch (SubArch) {
+case Triple::SPIRVSubArch_v10:
+  return "spirv1.0";
+case Triple::SPIRVSubArch_v11:
+  return "spirv1.1";
+case Triple::SPIRVSubArch_v12:
+  return "spirv1.2";
+case Triple::SPIRVSubArch_v13:
+  return "spirv1.3";
+case Triple::SPIRVSubArch_v14:
+  return "spirv1.4";
+case Triple::SPIRVSubArch_v15:
+  return "spirv1.5";
+case Triple::SPIRVSubArch_v16:
+  return "spirv1.6";
+default:
+  break;
+}
+break;
   case Triple::dxil:
 switch (SubArch) {
 case Triple::NoSubArch:

``




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


[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2025-01-07 Thread Louis Dionne via cfe-commits


@@ -8265,6 +8265,11 @@ def internal_externc_isystem : Separate<["-"], 
"internal-externc-isystem">,
"implicit extern \"C\" semantics; these are assumed to not be "
"user-provided and are used to model system and standard headers' "
"paths.">;
+def internal_iframework : Separate<["-"], "internal-iframework">,

ldionne wrote:

Is it really closer to internal-externc-isystem than internal-isystem though? 
My understanding is that all of these flags are simply taken (by CC1) in the 
order in which they appear in the command-line. Is that not what's happening?

https://github.com/llvm/llvm-project/pull/120149
___
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-07 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:

Ideally I think the all the information necessary for understanding an error 
should be contained within the `error` diagnostic itself and additional useful 
(but not strictly necessary) information can (but doesn't necessarily have to 
be) put into notes.

What is necessary is a little subjective but...

> ‘Access to bounds-checked field has incomplete type’

doesn't contains all the necessary information IMHO and is vague enough that I 
think it will cause more confusion than the current diagnos

[clang] Reapply "[Clang] Improve diagnostics for expansion length mismatch" (PR #121044)

2025-01-07 Thread Matheus Izvekov via cfe-commits

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

LGTM, though I would have preferred to keep the patches separate, it's less of 
a revert risk.

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


[clang] [llvm] [Clang][LLVM][AArch64]Add new feature SSVE-BitPerm (PR #121947)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (CarolineConcatto)


Changes

The 20204-12 ISA update release adds a new feature: FEAT_SSVE_BitPerm, which 
allows the sve-bitperm instructions to run in streaming mode.

It also removes the requirement of FEAT_SVE2 for FEAT_SVE_BitPerm. The 
sve2-bitperm feature is now an alias for sve-bitperm and sve2.

A new feature flag sve-bitperm is added to reflect the change that the 
instructions under FEAT_SVE_BitPerm are supported if:
 on non streaming mode with FEAT_SVE2 and FEAT_SVE_BitPerm or
 in streaming mode with FEAT_SME and FEAT_SSVE_BitPerm

---

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


31 Files Affected:

- (modified) clang/include/clang/Basic/arm_sve.td (+1-1) 
- (modified) clang/lib/Basic/Targets/AArch64.cpp (+4-6) 
- (modified) clang/lib/Basic/Targets/AArch64.h (+1-1) 
- (modified) clang/test/CodeGen/AArch64/fmv-dependencies.c (+1-1) 
- (modified) clang/test/CodeGen/AArch64/sve2-intrinsics/acle_sve2_bdep.c (+4-4) 
- (modified) clang/test/CodeGen/AArch64/sve2-intrinsics/acle_sve2_bext.c (+4-4) 
- (modified) clang/test/CodeGen/AArch64/sve2-intrinsics/acle_sve2_bgrp.c (+4-4) 
- (modified) clang/test/CodeGen/AArch64/targetattr.c (+1-1) 
- (modified) clang/test/Driver/aarch64-implied-sme-features.c (+4-1) 
- (modified) clang/test/Driver/aarch64-implied-sve-features.c (+11-3) 
- (modified) clang/test/Driver/print-supported-extensions-aarch64.c (+3-1) 
- (modified) clang/test/Preprocessor/aarch64-target-features.c (+6-1) 
- (modified) 
clang/test/Sema/aarch64-sve2-intrinsics/acle_sve2_aes_bitperm_sha3_sm4.cpp 
(+48-48) 
- (modified) llvm/lib/Target/AArch64/AArch64.td (+2-2) 
- (modified) llvm/lib/Target/AArch64/AArch64Features.td (+7-2) 
- (modified) llvm/lib/Target/AArch64/AArch64InstrInfo.td (+6-2) 
- (modified) llvm/lib/Target/AArch64/AArch64Processors.td (+18-18) 
- (modified) llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td (+1-1) 
- (modified) llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp (+3-1) 
- (modified) llvm/lib/TargetParser/AArch64TargetParser.cpp (+3) 
- (modified) llvm/test/MC/AArch64/SVE2/bdep-diagnostics.s (+1-1) 
- (modified) llvm/test/MC/AArch64/SVE2/bdep.s (+4-4) 
- (modified) llvm/test/MC/AArch64/SVE2/bext.s (+4-4) 
- (modified) llvm/test/MC/AArch64/SVE2/bgrp.s (+4-4) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-arch-negative.s (+9-3) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-arch.s (+5-1) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-arch_extension-negative.s 
(+1-1) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-arch_extension.s (+1-1) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-cpu-negative.s (+9-3) 
- (modified) llvm/test/MC/AArch64/SVE2/directive-cpu.s (+5-1) 
- (modified) llvm/unittests/TargetParser/TargetParserTest.cpp (+18-15) 


``diff
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 1c6bdb8cad2d19..47f1754aeb6299 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1988,7 +1988,7 @@ def SVSM4E: SInst<"svsm4e[_{d}]","ddd", "Ui", 
MergeNone, "aarch64_sve_sm
 def SVSM4EKEY : SInst<"svsm4ekey[_{d}]", "ddd", "Ui", MergeNone, 
"aarch64_sve_sm4ekey", [IsOverloadNone]>;
 }
 
-let SVETargetGuard = "sve2-bitperm", SMETargetGuard = InvalidMode in {
+let SVETargetGuard = "sve2,sve-bitperm", SMETargetGuard = InvalidMode in {
 def SVBDEP   : SInst<"svbdep[_{d}]",   "ddd", "UcUsUiUl", MergeNone, 
"aarch64_sve_bdep_x">;
 def SVBDEP_N : SInst<"svbdep[_n_{d}]", "dda", "UcUsUiUl", MergeNone, 
"aarch64_sve_bdep_x">;
 def SVBEXT   : SInst<"svbext[_{d}]",   "ddd", "UcUsUiUl", MergeNone, 
"aarch64_sve_bext_x">;
diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 53e102bbe44687..ae55b8d9ab308d 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -485,7 +485,7 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   if (HasSVE2 && HasSVEAES)
 Builder.defineMacro("__ARM_FEATURE_SVE2_AES", "1");
 
-  if (HasSVE2 && HasSVE2BitPerm)
+  if (HasSVE2 && HasSVEBitPerm)
 Builder.defineMacro("__ARM_FEATURE_SVE2_BITPERM", "1");
 
   if (HasSVE2 && HasSVE2SHA3)
@@ -769,7 +769,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
   .Case("sve-aes", HasSVEAES)
-  .Case("sve2-bitperm", FPU & SveMode && HasSVE2BitPerm)
+  .Case("sve-bitperm", FPU & HasSVEBitPerm)
   .Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
   .Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
   .Case("sve2p1", FPU & SveMode && HasSVE2p1)
@@ -881,12 +881,10 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
 }
 if (Feature == "+sve-b16b16")
   HasSVEB16B16 = true;
-if (Feature == "+sve2-bitp

[clang] [Clang] __has_builtin should return false for aux triple builtins (PR #121839)

2025-01-07 Thread Nick Sarnie via cfe-commits

sarnex wrote:

> It is not quite trying to fix a problem:). In hipstdpar mode there's no 
> host/device segregation, and it is possible to codegen IR for host only bits 
> (e.g., parts of the stdlib). We delay resolving whether a construct is or 
> isn't viable to the ME, and just place in these special stubs where the 
> otherwise unsupported construct (in this case a builtin) is used. Then, iff 
> it turns out that the code path that reaches the unsupported construct is 
> accessible, we error out - please see https://reviews.llvm.org/D155850 and 
> https://reviews.llvm.org/D155856 for historical context.
> 
> I don't quite think that this change interacts with that at all (I'll look 
> again), but it might interact in some subtle way with offload languages such 
> as e.g. HIP which jump through some hoops to keep the AST consistent, so I've 
> added @yxsamliu to this review.

Ah, thanks for the clarification for for adding reviewers!

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


[clang] [NFC][analyzer][docs] Crosslink MallocChecker's ownership attributes (PR #121939)

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

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

LGTM. Please check if the generated docs look as intended before merging.

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


[clang] [diagtool] Make the BuiltinDiagnosticsByID table sorted (PR #120321)

2025-01-07 Thread Karl-Johan Karlsson via cfe-commits

https://github.com/karka228 updated 
https://github.com/llvm/llvm-project/pull/120321

>From 1ad62a9a136a5ae80c880459472a88517afe75a4 Mon Sep 17 00:00:00 2001
From: Karl-Johan Karlsson 
Date: Tue, 17 Dec 2024 22:48:04 +0100
Subject: [PATCH 1/2] [diagtool] Make the BuiltinDiagnosticsByID table sorted

When building with -DLLVM_ENABLE_EXPENSIVE_CHECKS=ON with a recent
libstdc++ (e.g. from gcc 13.3.0) the testcase
clang/test/Misc/warning-flags-tree.c fail with the message:

+ diagtool tree --internal
.../include/c++/13.3.0/bits/stl_algo.h:2013:
In function:
_ForwardIterator std::lower_bound(_ForwardIterator, _ForwardIterator,
const _Tp &, _Compare) [_ForwardIterator = const
diagtool::DiagnosticRecord *, _Tp = diagtool::DiagnosticRecord, _Compare
= bool (*)(const diagtool::DiagnosticRecord &, const
diagtool::DiagnosticRecord &)]

Error: elements in iterator range [first, last) are not partitioned by the
predicate __comp and value __val.

Objects involved in the operation:
iterator "first" @ 0x7ffea8ef2fd8 {
}
iterator "last" @ 0x7ffea8ef2fd0 {
}

The reason for this error is that std::lower_bound is called on
BuiltinDiagnosticsByID without it being entirely sorted. Calling
std::lower_bound If the range is not sorted, the behavior of this
function is undefined. This is detected when building with expensive
checks.

To make BuiltinDiagnosticsByID sorted we need to slightly change the
order the inc-files are included.
---
 clang/tools/diagtool/DiagnosticNames.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/tools/diagtool/DiagnosticNames.cpp 
b/clang/tools/diagtool/DiagnosticNames.cpp
index eb90f082437b33..215087b9004959 100644
--- a/clang/tools/diagtool/DiagnosticNames.cpp
+++ b/clang/tools/diagtool/DiagnosticNames.cpp
@@ -23,15 +23,14 @@ llvm::ArrayRef 
diagtool::getBuiltinDiagnosticsByName() {
   return llvm::ArrayRef(BuiltinDiagnosticsByName);
 }
 
-
 // FIXME: Is it worth having two tables, especially when this one can get
 // out of sync easily?
+// clang-format off
 static const DiagnosticRecord BuiltinDiagnosticsByID[] = {
 #define DIAG(ENUM, CLASS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR,  
\
  SHOWINSYSHEADER, SHOWINSYSMACRO, DEFER, CATEGORY) 
\
   {#ENUM, diag::ENUM, STR_SIZE(#ENUM, uint8_t)},
 #include "clang/Basic/DiagnosticCommonKinds.inc"
-#include "clang/Basic/DiagnosticCrossTUKinds.inc"
 #include "clang/Basic/DiagnosticDriverKinds.inc"
 #include "clang/Basic/DiagnosticFrontendKinds.inc"
 #include "clang/Basic/DiagnosticSerializationKinds.inc"
@@ -39,12 +38,14 @@ static const DiagnosticRecord BuiltinDiagnosticsByID[] = {
 #include "clang/Basic/DiagnosticParseKinds.inc"
 #include "clang/Basic/DiagnosticASTKinds.inc"
 #include "clang/Basic/DiagnosticCommentKinds.inc"
+#include "clang/Basic/DiagnosticCrossTUKinds.inc"
 #include "clang/Basic/DiagnosticSemaKinds.inc"
 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
 #include "clang/Basic/DiagnosticRefactoringKinds.inc"
 #include "clang/Basic/DiagnosticInstallAPIKinds.inc"
 #undef DIAG
 };
+// clang-format on
 
 static bool orderByID(const DiagnosticRecord &Left,
   const DiagnosticRecord &Right) {

>From 4cedc90e9b26e5d48d53df463e8650d8a726e1d5 Mon Sep 17 00:00:00 2001
From: Karl-Johan Karlsson 
Date: Tue, 7 Jan 2025 15:59:16 +0100
Subject: [PATCH 2/2] [diagtool] Make the BuiltinDiagnosticsByID table sorted

Extracted the includes into a wrapper header file DiagnosticIDs.inc.
Added is_sorted assert.
---
 clang/include/clang/Basic/DiagnosticIDs.inc | 31 +
 clang/lib/Basic/DiagnosticIDs.cpp   | 48 ++---
 clang/tools/diagtool/DiagnosticNames.cpp| 23 --
 3 files changed, 42 insertions(+), 60 deletions(-)
 create mode 100644 clang/include/clang/Basic/DiagnosticIDs.inc

diff --git a/clang/include/clang/Basic/DiagnosticIDs.inc 
b/clang/include/clang/Basic/DiagnosticIDs.inc
new file mode 100644
index 00..69a7c03d39dff0
--- /dev/null
+++ b/clang/include/clang/Basic/DiagnosticIDs.inc
@@ -0,0 +1,31 @@
+//===--- DiagnosticIDs.inc --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// \file
+/// Defines the Diagnostic IDs in ID sorted order.
+///
+//===--===//
+
+// Turn off clang-format, as the order of the includes are important to make
+// sure the table is sorted.
+
+// clang-format off
+#include "clang/Basic/DiagnosticCommonKinds.inc"
+#include "clang/Basic/DiagnosticDriverKinds.inc"
+#include "clang/Basic/DiagnosticFrontendKinds.inc"
+#include "clang/Basic/DiagnosticSerializationKinds.inc"
+#include "cla

[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-07 Thread Erich Keane via cfe-commits

erichkeane wrote:

I think I'm reasonably OK with this, though @Sirraide has a 'requested 
changes', so he should do the final approval.

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] Evaluate constant initializers in C as well (PR #121950)

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

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

None

>From 87176299fcd501ec6f440e61e224b30854920e10 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 7 Jan 2025 16:18:56 +0100
Subject: [PATCH] [clang] Evaluate constant initializers in C as well

---
 clang/lib/Sema/SemaDecl.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..ff334e9d52b9dd 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -14481,7 +14481,8 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl 
*var) {
 // do this lazily, because the result might depend on things that change
 // later, such as which constexpr functions happen to be defined.
 SmallVector Notes;
-if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
+if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus11 &&
+!getLangOpts().C23) {
   // Prior to C++11, in contexts where a constant initializer is required,
   // the set of valid constant initializers is described by syntactic rules
   // in [expr.const]p2-6.

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


[clang] [clang] Evaluate constant initializers in C as well (PR #121950)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



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


1 Files Affected:

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


``diff
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..ff334e9d52b9dd 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -14481,7 +14481,8 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl 
*var) {
 // do this lazily, because the result might depend on things that change
 // later, such as which constexpr functions happen to be defined.
 SmallVector Notes;
-if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
+if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus11 &&
+!getLangOpts().C23) {
   // Prior to C++11, in contexts where a constant initializer is required,
   // the set of valid constant initializers is described by syntactic rules
   // in [expr.const]p2-6.

``




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


[clang-tools-extra] Add bugprone-sprintf-argument-overlap (PR #114244)

2025-01-07 Thread Gábor Horváth via cfe-commits


@@ -0,0 +1,86 @@
+// RUN: %check_clang_tidy %s bugprone-sprintf-argument-overlap %t
+
+using size_t = decltype(sizeof(int));
+
+extern "C" int sprintf(char *s, const char *format, ...);
+extern "C" int snprintf(char *s, size_t n, const char *format, ...);
+
+namespace std {
+  int snprintf(char *s, size_t n, const char *format, ...);
+}
+
+struct st_t {
+  char buf[10];
+  char buf2[10];
+};
+
+struct st2_t {
+  st_t inner;
+};
+
+struct st3_t {
+  st2_t inner;
+};
+
+void first_arg_overlaps() {
+  char buf[10];
+  sprintf(buf, "%s", buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  snprintf(buf, sizeof(buf), "%s", buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: the 4th argument in 'snprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  std::snprintf(buf, sizeof(buf), "%s", buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:41: warning: the 4th argument in 'snprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  sprintf(buf+1, "%s", (buf+1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  sprintf(buf+1, "%s", buf+2);
+  sprintf(buf+1, "%s", buf[1]);
+
+  char* c = &buf[0];
+  sprintf(c, "%s", c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  snprintf(c, sizeof(buf), "%s", c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: the 4th argument in 'snprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+
+  snprintf(c, sizeof(buf), "%s%s", c, c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: the 4th argument in 'snprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  // CHECK-MESSAGES: :[[@LINE-2]]:39: warning: the 5th argument in 'snprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+
+  char buf2[10];
+  sprintf(buf, "%s", buf2);
+  sprintf(buf, "%s", buf2, buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: the 4th argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+
+  st_t st1, st2;
+  sprintf(st1.buf, "%s", st1.buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  sprintf(st1.buf, "%s", st1.buf2);
+  sprintf(st1.buf, "%s", st2.buf);
+
+  st3_t st3;
+  sprintf(st3.inner.inner.buf, "%s", st3.inner.inner.buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:38: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  sprintf((st3.inner.inner.buf), "%s", st3.inner.inner.buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+
+  st_t* stp;
+  sprintf(stp->buf, "%s", stp->buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  sprintf((stp->buf), "%s", stp->buf);
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: the 3rd argument in 'sprintf' 
overlaps the 1st argument, which is undefined behavior 
[bugprone-sprintf-argument-overlap]
+  stp = &st1;
+  sprintf(stp->buf, "%s", st1.buf);

Xazax-hun wrote:

It would be nice to add comments for false negatives. 

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


[clang] [C++20] Destroying delete and deleted destructors (PR #118800)

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

AaronBallman wrote:

Ping @zygoloid 

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


[clang] [Clang] __has_builtin should return false for aux triple builtins (PR #121839)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nick Sarnie (sarnex)


Changes

Currently, `__has_builtin` will return true when passed a builtin that is only 
supported on the aux target. I found this when  `__has_builtin` was called with 
an X86 builtin but the current target was SPIR-V.

If we know for sure the builtin can't be supported on the current target, the 
function should return false.

We can't simply check if it's an aux builtin, see the test mentioned in the 
comment.

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


4 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.h (+5) 
- (modified) clang/lib/Basic/Builtins.cpp (+19) 
- (modified) clang/lib/Lex/PPMacroExpansion.cpp (+17-3) 
- (added) clang/test/Preprocessor/builtin_aux_info.cpp (+12) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.h 
b/clang/include/clang/Basic/Builtins.h
index 63559d977ce6b6..0939f95b0922c1 100644
--- a/clang/include/clang/Basic/Builtins.h
+++ b/clang/include/clang/Basic/Builtins.h
@@ -74,6 +74,7 @@ struct Info {
   const char *Features;
   HeaderDesc Header;
   LanguageID Langs;
+  bool operator==(const Info &Other) const;
 };
 
 /// Holds information about both target-independent and
@@ -268,6 +269,10 @@ class Context {
   /// for AuxTarget).
   unsigned getAuxBuiltinID(unsigned ID) const { return ID - TSRecords.size(); }
 
+  // Return true if the AuxBuiltin ID represents a target-specific builtin that
+  // is always unsupported on the default target.
+  bool isAuxBuiltinIDAlwaysUnsupportedOnDefaultTarget(unsigned ID) const;
+
   /// Returns true if this is a libc/libm function without the '__builtin_'
   /// prefix.
   static bool isBuiltinFunc(llvm::StringRef Name);
diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp
index 588183788de322..bd443b3b371e35 100644
--- a/clang/lib/Basic/Builtins.cpp
+++ b/clang/lib/Basic/Builtins.cpp
@@ -41,6 +41,14 @@ static constexpr Builtin::Info BuiltinInfo[] = {
 #include "clang/Basic/Builtins.inc"
 };
 
+bool Builtin::Info::operator==(const Builtin::Info &Other) const {
+  auto StrCompare = [](StringRef A, StringRef B) { return A == B; };
+  return Name == Other.Name && StrCompare(Type, Other.Type) &&
+ StrCompare(Attributes, Other.Attributes) &&
+ StrCompare(Features, Other.Features) && Header.ID == Other.Header.ID 
&&
+ Langs == Other.Langs;
+}
+
 const Builtin::Info &Builtin::Context::getRecord(unsigned ID) const {
   if (ID < Builtin::FirstTSBuiltin)
 return BuiltinInfo[ID];
@@ -183,6 +191,17 @@ unsigned Builtin::Context::getRequiredVectorWidth(unsigned 
ID) const {
   return Width;
 }
 
+bool Builtin::Context::isAuxBuiltinIDAlwaysUnsupportedOnDefaultTarget(
+unsigned ID) const {
+  assert(isAuxBuiltinID(ID) && "Expected aux target builtin ID");
+  const auto &Record = getRecord(ID);
+  for (const auto &MainTargetBuiltin : TSRecords)
+if (Record == MainTargetBuiltin)
+  return false;
+
+  return true;
+}
+
 bool Builtin::Context::isLike(unsigned ID, unsigned &FormatIdx,
   bool &HasVAListArg, const char *Fmt) const {
   assert(Fmt && "Not passed a format string");
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index 347c13da0ad215..13d9a0094a5827 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1804,8 +1804,9 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
diag::err_feature_check_malformed);
 if (!II)
   return false;
-else if (II->getBuiltinID() != 0) {
-  switch (II->getBuiltinID()) {
+auto BuiltinID = II->getBuiltinID();
+if (BuiltinID != 0) {
+  switch (BuiltinID) {
   case Builtin::BI__builtin_cpu_is:
 return getTargetInfo().supportsCpuIs();
   case Builtin::BI__builtin_cpu_init:
@@ -1818,8 +1819,21 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
 // usual allocation and deallocation functions. Required by libc++
 return 201802;
   default:
+// We may get here because of aux builtins which may not be
+// supported on the default target, for example if we have an X86
+// specific builtin and the current target is SPIR-V. Sometimes we
+// rely on __has_builtin returning true when passed a builtin that
+// is not supported on the default target due to LangOpts but is
+// supported on the aux target. See
+// test/Headers/__cpuidex_conflict.c for an example. If the builtin
+// is an aux builtin and it can never be supported on the default
+// target, __has_builtin should return false.
+if (getBuiltinInfo().isAuxBuiltinID(BuiltinID) &&
+
getBuiltinInfo().isAuxBuiltinIDAlwaysUnsupportedOnDefaultTarget(
+BuiltinID))
+ 

[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

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


@@ -3430,13 +3430,15 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
-  ASan.getAllocaSizeInBytes(*AI),
-  0,
-  AI->getAlign().value(),
-  AI,
-  0,
-  0};
+const char *Name = AI->getName().data();
+if (AI->hasMetadata(LLVMContext::MD_unaltered_name)) {
+  MDTuple *tuple =

fhahn wrote:

```suggestion
  MDTuple *Tuple =
```

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

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


@@ -53,3 +53,4 @@ LLVM_FIXED_MD_KIND(MD_DIAssignID, "DIAssignID", 38)
 LLVM_FIXED_MD_KIND(MD_coro_outside_frame, "coro.outside.frame", 39)
 LLVM_FIXED_MD_KIND(MD_mmra, "mmra", 40)
 LLVM_FIXED_MD_KIND(MD_noalias_addrspace, "noalias.addrspace", 41)
+LLVM_FIXED_MD_KIND(MD_unaltered_name, "unaltered.name", 42)

fhahn wrote:

Not sure if it is worth adding a new metadata kind to work around not using 
debug info?

If we need new metadata, it should be documented and also needs to be checked 
by the verifier, but perhaps it would be possible to use 
https://llvm.org/docs/LangRef.html#annotation-metadata instead?

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

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


@@ -3430,13 +3430,15 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
-  ASan.getAllocaSizeInBytes(*AI),
-  0,
-  AI->getAlign().value(),
-  AI,
-  0,
-  0};
+const char *Name = AI->getName().data();

fhahn wrote:

Is is possible to use StringRef here?

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


[clang] [Clang] __has_builtin should return false for aux triple builtins (PR #121839)

2025-01-07 Thread Nick Sarnie via cfe-commits

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

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


@@ -3430,13 +3430,15 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
-  ASan.getAllocaSizeInBytes(*AI),
-  0,
-  AI->getAlign().value(),
-  AI,
-  0,
-  0};
+const char *Name = AI->getName().data();
+if (AI->hasMetadata(LLVMContext::MD_unaltered_name)) {
+  MDTuple *tuple =
+  dyn_cast(AI->getMetadata(LLVMContext::MD_unaltered_name));
+  Name = dyn_cast(tuple->getOperand(0))->getString().data();

fhahn wrote:

Should those be casts? If the dyn_cast can return nullptr, you need to check 
the return value

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


[clang] [llvm] [LLVM][AArch64] Add new feature +sme-mop4 and +sme-tmop (PR #121935)

2025-01-07 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-aarch64

@llvm/pr-subscribers-clang-driver

Author: None (CarolineConcatto)


Changes

The 2024-12 ISA spec release[1] add these features:
 FEAT_SME_MOP4(sme-mop4) to enable SME Quarter-tile outer product instructions
and
 FEAT_SME_TMOP(sme-tmop) to enable SME Structured sparsity outer product 
instructions
to allow these instructions to be available outside Armv9.6/sme2p2

[1] https://developer.arm.com/Architectures/A-Profile%20Architecture#Downloads

---

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


41 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-aarch64.c (+2) 
- (modified) llvm/lib/Target/AArch64/AArch64.td (+2-1) 
- (modified) llvm/lib/Target/AArch64/AArch64Features.td (+6) 
- (modified) llvm/lib/Target/AArch64/AArch64InstrInfo.td (+8) 
- (modified) llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td (+32-21) 
- (modified) llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp (+2) 
- (modified) llvm/test/MC/AArch64/SME2p2/bfmop4as-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/bfmop4as-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/bftmopa.s (+8-6) 
- (modified) llvm/test/MC/AArch64/SME2p2/directive-arch.s (+8) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4a-fp8-fp16-widening.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4a-fp8-fp32-widening.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp16-fp32-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp16-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp32-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp64-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/ftmopa.s (+18-16) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/stmopa.s (+8-6) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4a-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4s-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sutmopa.s (+5-3) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4s-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4a-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4s-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/ustmopa.s (+5-3) 
- (modified) llvm/test/MC/AArch64/SME2p2/utmopa.s (+8-6) 
- (modified) llvm/unittests/TargetParser/TargetParserTest.cpp (+8-2) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-aarch64.c 
b/clang/test/Driver/print-supported-extensions-aarch64.c
index 09d499548aa565..77812189f12d0d 100644
--- a/clang/test/Driver/print-supported-extensions-aarch64.c
+++ b/clang/test/Driver/print-supported-extensions-aarch64.c
@@ -51,6 +51,8 @@
 // CHECK-NEXT: pcdphintFEAT_PCDPHINT   
   Enable Armv9.6-A Producer Consumer Data Placement hints
 // CHECK-NEXT: pmuv3   FEAT_PMUv3  
   Enable Armv8.0-A PMUv3 Performance Monitors extension
 // CHECK-NEXT: popsFEAT_PoPS   
   Enable Armv9.6-A Point Of Physical Storage (PoPS) DC instructions
+// CHECK-NEXT: sme-mop4FEAT_SME_MOP4   
   Enable SME Quarter-tile outer product instructions
+// CHECK-NEXT: sme-tmopFEAT_SME_TMOP   
   Enable SME Structured sparsity outer product instructions
 // CHECK-NEXT: predres FEAT_SPECRES
   Enable Armv8.5-A execution and data prediction invalidation 
instructions
 // CHECK-NEXT: rng FEAT_RNG
   Enable Random Number generation instructions
 // CHECK-NEXT: ras FEAT_RAS, FEAT_RASv1p1  
   Enable Armv8.0-A Reliability, Availability and Serviceability 
Extensions
diff --git a/llvm/lib/Target/AArch64/AAr

[clang] [llvm] [LLVM][AArch64] Add new feature +sme-mop4 and +sme-tmop (PR #121935)

2025-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (CarolineConcatto)


Changes

The 2024-12 ISA spec release[1] add these features:
 FEAT_SME_MOP4(sme-mop4) to enable SME Quarter-tile outer product instructions
and
 FEAT_SME_TMOP(sme-tmop) to enable SME Structured sparsity outer product 
instructions
to allow these instructions to be available outside Armv9.6/sme2p2

[1] https://developer.arm.com/Architectures/A-Profile%20Architecture#Downloads

---

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


41 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-aarch64.c (+2) 
- (modified) llvm/lib/Target/AArch64/AArch64.td (+2-1) 
- (modified) llvm/lib/Target/AArch64/AArch64Features.td (+6) 
- (modified) llvm/lib/Target/AArch64/AArch64InstrInfo.td (+8) 
- (modified) llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td (+32-21) 
- (modified) llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp (+2) 
- (modified) llvm/test/MC/AArch64/SME2p2/bfmop4as-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/bfmop4as-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/bftmopa.s (+8-6) 
- (modified) llvm/test/MC/AArch64/SME2p2/directive-arch.s (+8) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4a-fp8-fp16-widening.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4a-fp8-fp32-widening.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp16-fp32-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp16-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp32-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/fmop4as-fp64-non-widening.s (+26-24) 
- (modified) llvm/test/MC/AArch64/SME2p2/ftmopa.s (+18-16) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4a-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/smop4s-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/stmopa.s (+8-6) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4a-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4s-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sumop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/sutmopa.s (+5-3) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-16to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4a-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/umop4s-8to32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4a-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4a-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4s-32.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/usmop4s-64.s (+14-12) 
- (modified) llvm/test/MC/AArch64/SME2p2/ustmopa.s (+5-3) 
- (modified) llvm/test/MC/AArch64/SME2p2/utmopa.s (+8-6) 
- (modified) llvm/unittests/TargetParser/TargetParserTest.cpp (+8-2) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-aarch64.c 
b/clang/test/Driver/print-supported-extensions-aarch64.c
index 09d499548aa565..77812189f12d0d 100644
--- a/clang/test/Driver/print-supported-extensions-aarch64.c
+++ b/clang/test/Driver/print-supported-extensions-aarch64.c
@@ -51,6 +51,8 @@
 // CHECK-NEXT: pcdphintFEAT_PCDPHINT   
   Enable Armv9.6-A Producer Consumer Data Placement hints
 // CHECK-NEXT: pmuv3   FEAT_PMUv3  
   Enable Armv8.0-A PMUv3 Performance Monitors extension
 // CHECK-NEXT: popsFEAT_PoPS   
   Enable Armv9.6-A Point Of Physical Storage (PoPS) DC instructions
+// CHECK-NEXT: sme-mop4FEAT_SME_MOP4   
   Enable SME Quarter-tile outer product instructions
+// CHECK-NEXT: sme-tmopFEAT_SME_TMOP   
   Enable SME Structured sparsity outer product instructions
 // CHECK-NEXT: predres FEAT_SPECRES
   Enable Armv8.5-A execution and data prediction invalidation 
instructions
 // CHECK-NEXT: rng FEAT_RNG
   Enable Random Number generation instructions
 // CHECK-NEXT: ras FEAT_RAS, FEAT_RASv1p1  
   Enable Armv8.0-A Reliability, Availability and Serviceability 
Extensions
diff --git a/llvm/lib/Target/AArch64/AArch64.td 
b/llvm/lib/Target/AArch64/AArch64.t

[clang] [clang][dataflow] Use smart pointer caching in unchecked optional accessor (PR #120249)

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

https://github.com/jvoung updated 
https://github.com/llvm/llvm-project/pull/120249

>From c526263a7accc434dbf6e93c2995ceb2f95873b8 Mon Sep 17 00:00:00 2001
From: Jan Voung 
Date: Tue, 17 Dec 2024 15:38:19 +
Subject: [PATCH 1/7] [clang][dataflow] Use smart pointer caching in unchecked
 optional accessor

Part 2 (and final part) following 
https://github.com/llvm/llvm-project/pull/120102
Allows users to do things like:

```
if (o->x.has_value()) {
  ((*o).x).value();
}
```
where the `->` and `*` are operator overload calls.

A user could instead extract the nested optional into a local variable
once instead of doing two accessor calls back to back, but currently
they are unsure why the code is flagged.
---
 .../CachedConstAccessorsLattice.h |  41 
 .../SmartPointerAccessorCaching.h | 168 +++
 .../lib/Analysis/FlowSensitive/CMakeLists.txt |   1 +
 .../Models/UncheckedOptionalAccessModel.cpp   |  58 +-
 .../SmartPointerAccessorCaching.cpp   | 153 ++
 .../Analysis/FlowSensitive/CMakeLists.txt |   1 +
 .../CachedConstAccessorsLatticeTest.cpp   |  32 +++
 .../SmartPointerAccessorCachingTest.cpp   | 194 ++
 .../UncheckedOptionalAccessModelTest.cpp  |  50 +
 9 files changed, 692 insertions(+), 6 deletions(-)
 create mode 100644 
clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
 create mode 100644 
clang/lib/Analysis/FlowSensitive/SmartPointerAccessorCaching.cpp
 create mode 100644 
clang/unittests/Analysis/FlowSensitive/SmartPointerAccessorCachingTest.cpp

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..6b5dacf9f66d2d 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -13,7 +13,9 @@
 #ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CACHED_CONST_ACCESSORS_LATTICE_H
 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CACHED_CONST_ACCESSORS_LATTICE_H
 
+#include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
@@ -71,10 +73,28 @@ template  class CachedConstAccessorsLattice 
: public Base {
   /// Requirements:
   ///
   ///  - `CE` should return a location (GLValue or a record type).
+  ///
+  /// DEPRECATED: switch users to the below overload which takes Callee and 
Type
+  /// directly.
   StorageLocation *getOrCreateConstMethodReturnStorageLocation(
   const RecordStorageLocation &RecordLoc, const CallExpr *CE,
   Environment &Env, llvm::function_ref 
Initialize);
 
+  /// Creates or returns a previously created `StorageLocation` associated with
+  /// a const method call `obj.getFoo()` where `RecordLoc` is the
+  /// `RecordStorageLocation` of `obj`, `Callee` is the decl for `getFoo`,
+  /// and `Type` is the return type of `getFoo`.
+  ///
+  /// The callback `Initialize` runs on the storage location if newly created.
+  ///
+  /// Requirements:
+  ///
+  ///  - `Type` should return a location (GLValue or a record type).
+  StorageLocation &getOrCreateConstMethodReturnStorageLocation(
+  const RecordStorageLocation &RecordLoc, const FunctionDecl *Callee,
+  QualType Type, Environment &Env,
+  llvm::function_ref Initialize);
+
   void clearConstMethodReturnValues(const RecordStorageLocation &RecordLoc) {
 ConstMethodReturnValues.erase(&RecordLoc);
   }
@@ -212,6 +232,27 @@ 
CachedConstAccessorsLattice::getOrCreateConstMethodReturnStorageLocation(
   return &Loc;
 }
 
+template 
+StorageLocation &
+CachedConstAccessorsLattice::getOrCreateConstMethodReturnStorageLocation(
+const RecordStorageLocation &RecordLoc, const FunctionDecl *Callee,
+QualType Type, Environment &Env,
+llvm::function_ref Initialize) {
+  assert(Callee != nullptr);
+  assert(!Type.isNull());
+  assert(Type->isReferenceType() || Type->isRecordType());
+  auto &ObjMap = ConstMethodReturnStorageLocations[&RecordLoc];
+  auto it = ObjMap.find(Callee);
+  if (it != ObjMap.end())
+return *it->second;
+
+  StorageLocation &Loc = Env.createStorageLocation(Type.getNonReferenceType());
+  Initialize(Loc);
+
+  ObjMap.insert({Callee, &Loc});
+  return Loc;
+}
+
 } // namespace dataflow
 } // namespace clang
 
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h 
b/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
new file mode 100644
index 00..e89e82c893d8cb
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/SmartPointerAccessorCaching.h
@@ -0,0 +1,168 @@
+//===-- SmartPointerAccessorCaching.h ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, u

[clang] [llvm] [RISCV] Add riscv_atomic.h and Zawrs builtins (PR #96283)

2025-01-07 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp updated 
https://github.com/llvm/llvm-project/pull/96283

>From 4b597ebf69de59d62e5587a27cedf2b12e831763 Mon Sep 17 00:00:00 2001
From: Wang Pengcheng 
Date: Fri, 21 Jun 2024 16:09:13 +0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.6-beta.1
---
 clang/include/clang/Basic/BuiltinsRISCV.td|  8 
 clang/lib/CodeGen/CGBuiltin.cpp   |  8 
 clang/lib/Headers/CMakeLists.txt  |  1 +
 clang/lib/Headers/riscv_atomic.h  | 18 
 .../CodeGen/RISCV/atomics-intrinsics/zawrs.c  | 42 +++
 llvm/include/llvm/IR/IntrinsicsRISCV.td   | 10 +
 llvm/lib/Target/RISCV/RISCVInstrInfoZa.td |  5 ++-
 llvm/test/CodeGen/RISCV/zawrs-intrinsic.ll| 33 +++
 8 files changed, 124 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/Headers/riscv_atomic.h
 create mode 100644 clang/test/CodeGen/RISCV/atomics-intrinsics/zawrs.c
 create mode 100644 llvm/test/CodeGen/RISCV/zawrs-intrinsic.ll

diff --git a/clang/include/clang/Basic/BuiltinsRISCV.td 
b/clang/include/clang/Basic/BuiltinsRISCV.td
index 4cc89a8a9d8af2..429f1356aa5fda 100644
--- a/clang/include/clang/Basic/BuiltinsRISCV.td
+++ b/clang/include/clang/Basic/BuiltinsRISCV.td
@@ -146,3 +146,11 @@ let Features = "zihintntl", Attributes = 
[CustomTypeChecking] in {
 def ntl_load : RISCVBuiltin<"void(...)">;
 def ntl_store : RISCVBuiltin<"void(...)">;
 } // Features = "zihintntl", Attributes = [CustomTypeChecking]
+
+//===--===//
+// Zawrs extension.
+//===--===//
+let Features = "zawrs" in {
+def wrs_nto : RISCVBuiltin<"void()">;
+def wrs_sto : RISCVBuiltin<"void()">;
+} // Features = "zawrs"
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2516ed45082429..1e130cad6d00dc 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -21834,6 +21834,14 @@ Value *CodeGenFunction::EmitRISCVBuiltinExpr(unsigned 
BuiltinID,
 ID = Intrinsic::riscv_sm3p1;
 break;
 
+  // Zawrs
+  case RISCV::BI__builtin_riscv_wrs_nto:
+ID = Intrinsic::riscv_wrs_nto;
+break;
+  case RISCV::BI__builtin_riscv_wrs_sto:
+ID = Intrinsic::riscv_wrs_sto;
+break;
+
   // Zihintntl
   case RISCV::BI__builtin_riscv_ntl_load: {
 llvm::Type *ResTy = ConvertType(E->getType());
diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt
index 89fa0ecd45eb4c..f8f430e6921cb0 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -118,6 +118,7 @@ set(ppc_htm_files
   )
 
 set(riscv_files
+  riscv_atomic.h
   riscv_bitmanip.h
   riscv_crypto.h
   riscv_ntlh.h
diff --git a/clang/lib/Headers/riscv_atomic.h b/clang/lib/Headers/riscv_atomic.h
new file mode 100644
index 00..4c548bdfa8253e
--- /dev/null
+++ b/clang/lib/Headers/riscv_atomic.h
@@ -0,0 +1,18 @@
+/*=== riscv_atomic.h - RISC-V atomic intrinsics ===
+ *
+ * Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+ * See https://llvm.org/LICENSE.txt for license information.
+ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+ *
+ *===---===
+ */
+
+#ifndef __RISCV_ATOMIC_H
+#define __RISCV_ATOMIC_H
+
+#ifdef __riscv_zawrs
+#define __riscv_wrs_nto __builtin_riscv_wrs_nto
+#define __riscv_wrs_sto __builtin_riscv_wrs_sto
+#endif
+
+#endif
diff --git a/clang/test/CodeGen/RISCV/atomics-intrinsics/zawrs.c 
b/clang/test/CodeGen/RISCV/atomics-intrinsics/zawrs.c
new file mode 100644
index 00..e3d4899244ca48
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/atomics-intrinsics/zawrs.c
@@ -0,0 +1,42 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 2
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv32 -target-feature +zawrs -disable-O0-optnone \
+// RUN:   -emit-llvm %s -o - | opt -S -passes=mem2reg | \
+// RUN:   FileCheck --check-prefixes=CHECK-RV32 %s
+// RUN: %clang_cc1 -triple riscv64 -target-feature +zawrs -disable-O0-optnone \
+// RUN:   -emit-llvm %s -o - | opt -S -passes=mem2reg | \
+// RUN:   FileCheck --check-prefix=CHECK-RV64 %s
+
+#include 
+
+// CHECK-RV32-LABEL: define dso_local void @zawrs_nto
+// CHECK-RV32-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-RV32-NEXT:  entry:
+// CHECK-RV32-NEXT:call void @llvm.riscv.wrs.nto()
+// CHECK-RV32-NEXT:ret void
+//
+// CHECK-RV64-LABEL: define dso_local void @zawrs_nto
+// CHECK-RV64-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-RV64-NEXT:  entry:
+// CHECK-RV64-NEXT:call void @llvm.riscv.wrs.nto()
+// CHECK-RV64-NEXT:ret void
+//
+void zawrs_nt

[clang] [llvm] [RISCV] Add riscv_atomic.h and Zawrs builtins (PR #96283)

2025-01-07 Thread Pengcheng Wang via cfe-commits

wangpc-pp wrote:

Ping for comments. :-)

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


[clang] [compiler-rt] [llvm] [ASan] Add metadata to renamed instructions so ASan doesn't use the i… (PR #119387)

2025-01-07 Thread via cfe-commits

https://github.com/gbMattN updated 
https://github.com/llvm/llvm-project/pull/119387

>From 8781ff2355750ae61d140620b1f6862537de07e3 Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 10 Dec 2024 15:01:37 +
Subject: [PATCH 1/5] [ASan] Add metadata to renamed instructions so ASan
 doesn't use the incorrect name

---
 llvm/lib/IR/ValueSymbolTable.cpp | 8 
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 7 ++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/IR/ValueSymbolTable.cpp b/llvm/lib/IR/ValueSymbolTable.cpp
index a020acf22a96c5..81bb3f3c5a5e35 100644
--- a/llvm/lib/IR/ValueSymbolTable.cpp
+++ b/llvm/lib/IR/ValueSymbolTable.cpp
@@ -123,6 +123,14 @@ ValueName *ValueSymbolTable::createValueName(StringRef 
Name, Value *V) {
   }
 
   // Otherwise, there is a naming conflict.  Rename this value.
+  // If we are renaming an instruction, ASan needs to know for it to serialize
+  // properly
+  if (auto *I = dyn_cast(V)) {
+MDString *trueNameMetadata = MDString::get(V->getContext(), Name);
+llvm::MDTuple *tuple =
+llvm::MDTuple::get(V->getContext(), trueNameMetadata);
+I->setMetadata("OriginalName", tuple);
+  }
   SmallString<256> UniqueName(Name.begin(), Name.end());
   return makeUniqueName(V, UniqueName);
 }
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index cb84588318496c..c696cc38167cd4 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,7 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-ASanStackVariableDescription D = {AI->getName().data(),
+std::string Name = AI->getName().data();
+if (AI->hasMetadata("OriginalName")) {
+  MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
+  Name = dyn_cast(tuple->getOperand(0))->getString();
+}
+ASanStackVariableDescription D = {Name.c_str(),
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From 25efafa3d67afb6a9107fdd502f5f6e4f40c311c Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Wed, 11 Dec 2024 11:44:01 +
Subject: [PATCH 2/5] [bugfix] Fixed string pointer being used out of scope

---
 llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index c696cc38167cd4..2051fa94678175 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -3430,12 +3430,12 @@ void FunctionStackPoisoner::processStaticAllocas() {
   SmallVector SVD;
   SVD.reserve(AllocaVec.size());
   for (AllocaInst *AI : AllocaVec) {
-std::string Name = AI->getName().data();
+const char* Name = AI->getName().data();
 if (AI->hasMetadata("OriginalName")) {
   MDTuple *tuple = dyn_cast(AI->getMetadata("OriginalName"));
-  Name = dyn_cast(tuple->getOperand(0))->getString();
+  Name = dyn_cast(tuple->getOperand(0))->getString().data();
 }
-ASanStackVariableDescription D = {Name.c_str(),
+ASanStackVariableDescription D = {Name,
   ASan.getAllocaSizeInBytes(*AI),
   0,
   AI->getAlign().value(),

>From c15ec2fe9bbe4855272a519b7f6dccca57a294eb Mon Sep 17 00:00:00 2001
From: gbMattN 
Date: Tue, 17 Dec 2024 16:47:11 +
Subject: [PATCH 3/5] Now only emit metadata when using a ASan, and tag it with
 an enum rather than a string

---
 clang/lib/CodeGen/CGExpr.cpp|  8 
 llvm/include/llvm/IR/FixedMetadataKinds.def |  1 +
 llvm/lib/IR/ValueSymbolTable.cpp|  8 
 .../Instrumentation/AddressSanitizer.cpp| 17 +++--
 4 files changed, 16 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 5fccc9cbb37ec1..d8fdacf30e12e3 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -137,6 +137,14 @@ llvm::AllocaInst 
*CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
 Alloca =
 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  ArraySize, Name, AllocaInsertPt->getIterator());
+  if (Alloca->getName() != Name.str() &&
+  SanOpts.Mask & SanitizerKind::Address) {
+
+llvm::LLVMContext &ctx = Alloca->getContext();
+llvm::MDString *trueNameMetadata = llvm::MDString::get(ctx, Name.str());
+llvm::MDTuple *tuple = llvm::MDTuple::get(ctx, trueNameMetadata);
+  

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

2025-01-07 Thread Pranav Kant via cfe-commits

https://github.com/pranavk updated 
https://github.com/llvm/llvm-project/pull/121944

>From 2347ae937659988e54bc6b9f47b6edb0fdaa8c13 Mon Sep 17 00:00:00 2001
From: Pranav Kant 
Date: Tue, 7 Jan 2025 14:48:00 +
Subject: [PATCH] [X86] Return illegal vectors in memory

When vector size doesn't fit in native machine vector size, we should
return vector via a hidden reference.
---
 clang/include/clang/Basic/LangOptions.h |  2 ++
 clang/lib/CodeGen/Targets/X86.cpp   | 38 +++--
 clang/test/CodeGen/X86/x86-illegal-vector.c | 22 
 clang/test/CodeGen/X86/x86-vec-i128.c   | 38 +++--
 4 files changed, 79 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CodeGen/X86/x86-illegal-vector.c

diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 949c8f5d448bcf..7dd8251c9da5c2 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -245,6 +245,8 @@ class LangOptionsBase {
 ///   construction vtable because it hasn't added 'type' as a substitution.
 ///   - Skip mangling enclosing class templates of member-like friend
 ///   function templates.
+///   - Incorrectly return illegal vectors (size greater than native
+/// vector size) to be returned in illegal registers on x86_64.
 Ver19,
 
 /// Conform to the underlying platform's C and C++ ABIs as closely
diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 7f73bf2a65266e..a40dbf9160ba6e 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1298,8 +1298,12 @@ class X86_64ABIInfo : public ABIInfo {
unsigned &NeededSSE,
unsigned &MaxVectorWidth) const;
 
+  // Checks whether vector types for function arguments are illegal
   bool IsIllegalVectorType(QualType Ty) const;
 
+  // Checks whether vector types for returns are illegal
+  bool IsIllegalReturnVectorType(QualType Ty) const;
+
   /// The 0.98 ABI revision clarified a lot of ambiguities,
   /// unfortunately in ways that were not always consistent with
   /// certain previous compilers.  In particular, platforms which
@@ -1334,6 +1338,16 @@ class X86_64ABIInfo : public ABIInfo {
 return T.isOSLinux() || T.isOSNetBSD();
   }
 
+  bool returnIllegalVectorsInMem() const {
+// Clang <= 19.0 did not do this.
+if (getContext().getLangOpts().getClangABICompat() <=
+LangOptions::ClangABI::Ver19)
+  return false;
+
+const llvm::Triple &T = getTarget().getTriple();
+return T.isOSLinux() || T.isOSNetBSD();
+  }
+
   X86AVXABILevel AVXLevel;
   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
   // 64-bit hardware.
@@ -2156,9 +2170,12 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
 }
 
 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
+  const bool returnIllegalVectorsIndirectly =
+  (returnIllegalVectorsInMem() && IsIllegalReturnVectorType(Ty));
+
   // If this is a scalar LLVM value then assume LLVM will pass it in the right
   // place naturally.
-  if (!isAggregateTypeForABI(Ty)) {
+  if (!isAggregateTypeForABI(Ty) && !returnIllegalVectorsIndirectly) {
 // Treat an enum type as its underlying type.
 if (const EnumType *EnumTy = Ty->getAs())
   Ty = EnumTy->getDecl()->getIntegerType();
@@ -2173,12 +2190,23 @@ ABIArgInfo 
X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
   return getNaturalAlignIndirect(Ty);
 }
 
-bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
+static bool IsIllegalVector(QualType Ty, uint64_t Size,
+X86AVXABILevel AVXLevel) {
   if (const VectorType *VecTy = Ty->getAs()) {
-uint64_t Size = getContext().getTypeSize(VecTy);
 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
 if (Size <= 64 || Size > LargestVector)
   return true;
+  }
+
+  return false;
+}
+
+bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
+  if (IsIllegalVector(Ty, getContext().getTypeSize(Ty), AVXLevel))
+return true;
+
+  // Maintain backward compatibility
+  if (const VectorType *VecTy = Ty->getAs()) {
 QualType EltTy = VecTy->getElementType();
 if (passInt128VectorsInMem() &&
 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
@@ -2189,6 +2217,10 @@ bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) 
const {
   return false;
 }
 
+bool X86_64ABIInfo::IsIllegalReturnVectorType(QualType Ty) const {
+  return IsIllegalVector(Ty, getContext().getTypeSize(Ty), AVXLevel);
+}
+
 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
 unsigned freeIntRegs) const {
   // If this is a scalar LLVM value then assume LLVM will pass it in the right
diff --git a/clang/test/CodeGen/X86/x86-illegal-vector.c 
b/clang/tes

[clang] [llvm] [Clang][LLVM][AArch64]Add new feature SSVE-BitPerm (PR #121947)

2025-01-07 Thread via cfe-commits

https://github.com/CarolineConcatto created 
https://github.com/llvm/llvm-project/pull/121947

The 20204-12 ISA update release adds a new feature: FEAT_SSVE_BitPerm, which 
allows the sve-bitperm instructions to run in streaming mode.

It also removes the requirement of FEAT_SVE2 for FEAT_SVE_BitPerm. The 
sve2-bitperm feature is now an alias for sve-bitperm and sve2.

A new feature flag sve-bitperm is added to reflect the change that the 
instructions under FEAT_SVE_BitPerm are supported if:
 on non streaming mode with FEAT_SVE2 and FEAT_SVE_BitPerm or
 in streaming mode with FEAT_SME and FEAT_SSVE_BitPerm

>From fca9d22fbfe55f1b9da5b205c1726d95eb94f176 Mon Sep 17 00:00:00 2001
From: Caroline Concatto 
Date: Fri, 3 Jan 2025 13:52:55 +
Subject: [PATCH] [Clang][LLVM][AArch64]Add new feature SSVE-BitPerm

The 20204-12 ISA update release adds a new feature:
FEAT_SSVE_BitPerm, which allows the sve-bitperm instructions to run
in streaming mode.

It also removes the requirement of FEAT_SVE2 for FEAT_SVE_BitPerm.
The sve2-bitperm feature is now an alias for sve-bitperm and sve2.

A new feature flag sve-bitperm is added to reflect the change that the 
instructions under
FEAT_SVE_BitPerm are supported if:
 on non streaming mode with FEAT_SVE2 and FEAT_SVE_BitPerm or
 in streaming mode with FEAT_SME and FEAT_SSVE_BitPerm
---
 clang/include/clang/Basic/arm_sve.td  |  2 +-
 clang/lib/Basic/Targets/AArch64.cpp   | 10 +-
 clang/lib/Basic/Targets/AArch64.h |  2 +-
 clang/test/CodeGen/AArch64/fmv-dependencies.c |  2 +-
 .../AArch64/sve2-intrinsics/acle_sve2_bdep.c  |  8 +-
 .../AArch64/sve2-intrinsics/acle_sve2_bext.c  |  8 +-
 .../AArch64/sve2-intrinsics/acle_sve2_bgrp.c  |  8 +-
 clang/test/CodeGen/AArch64/targetattr.c   |  2 +-
 .../Driver/aarch64-implied-sme-features.c |  5 +-
 .../Driver/aarch64-implied-sve-features.c | 14 ++-
 .../print-supported-extensions-aarch64.c  |  4 +-
 .../Preprocessor/aarch64-target-features.c|  7 +-
 .../acle_sve2_aes_bitperm_sha3_sm4.cpp| 96 +--
 llvm/lib/Target/AArch64/AArch64.td|  4 +-
 llvm/lib/Target/AArch64/AArch64Features.td|  9 +-
 llvm/lib/Target/AArch64/AArch64InstrInfo.td   |  8 +-
 llvm/lib/Target/AArch64/AArch64Processors.td  | 36 +++
 .../lib/Target/AArch64/AArch64SVEInstrInfo.td |  2 +-
 .../AArch64/AsmParser/AArch64AsmParser.cpp|  4 +-
 llvm/lib/TargetParser/AArch64TargetParser.cpp |  3 +
 llvm/test/MC/AArch64/SVE2/bdep-diagnostics.s  |  2 +-
 llvm/test/MC/AArch64/SVE2/bdep.s  |  8 +-
 llvm/test/MC/AArch64/SVE2/bext.s  |  8 +-
 llvm/test/MC/AArch64/SVE2/bgrp.s  |  8 +-
 .../MC/AArch64/SVE2/directive-arch-negative.s | 12 ++-
 llvm/test/MC/AArch64/SVE2/directive-arch.s|  6 +-
 .../SVE2/directive-arch_extension-negative.s  |  2 +-
 .../AArch64/SVE2/directive-arch_extension.s   |  2 +-
 .../MC/AArch64/SVE2/directive-cpu-negative.s  | 12 ++-
 llvm/test/MC/AArch64/SVE2/directive-cpu.s |  6 +-
 .../TargetParser/TargetParserTest.cpp | 33 ---
 31 files changed, 193 insertions(+), 140 deletions(-)

diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 1c6bdb8cad2d19..47f1754aeb6299 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1988,7 +1988,7 @@ def SVSM4E: SInst<"svsm4e[_{d}]","ddd", "Ui", 
MergeNone, "aarch64_sve_sm
 def SVSM4EKEY : SInst<"svsm4ekey[_{d}]", "ddd", "Ui", MergeNone, 
"aarch64_sve_sm4ekey", [IsOverloadNone]>;
 }
 
-let SVETargetGuard = "sve2-bitperm", SMETargetGuard = InvalidMode in {
+let SVETargetGuard = "sve2,sve-bitperm", SMETargetGuard = InvalidMode in {
 def SVBDEP   : SInst<"svbdep[_{d}]",   "ddd", "UcUsUiUl", MergeNone, 
"aarch64_sve_bdep_x">;
 def SVBDEP_N : SInst<"svbdep[_n_{d}]", "dda", "UcUsUiUl", MergeNone, 
"aarch64_sve_bdep_x">;
 def SVBEXT   : SInst<"svbext[_{d}]",   "ddd", "UcUsUiUl", MergeNone, 
"aarch64_sve_bext_x">;
diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 53e102bbe44687..ae55b8d9ab308d 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -485,7 +485,7 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   if (HasSVE2 && HasSVEAES)
 Builder.defineMacro("__ARM_FEATURE_SVE2_AES", "1");
 
-  if (HasSVE2 && HasSVE2BitPerm)
+  if (HasSVE2 && HasSVEBitPerm)
 Builder.defineMacro("__ARM_FEATURE_SVE2_BITPERM", "1");
 
   if (HasSVE2 && HasSVE2SHA3)
@@ -769,7 +769,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
   .Case("sve-aes", HasSVEAES)
-  .Case("sve2-bitperm", FPU & SveMode && HasSVE2BitPerm)
+  .Case("sve-bitperm", FPU & HasSVEBitPerm)
   .Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
   .Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
   

  1   2   3   4   5   >