[clang] [clang][bytecode] Handle __builtin_memcmp (PR #119544)

2024-12-12 Thread Timm Baeder via cfe-commits

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


[clang] [AST] Migrate away from PointerUnion::{is, get} (NFC) (PR #119673)

2024-12-12 Thread Nikita Popov via cfe-commits

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


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


[clang] [AST] Migrate away from PointerUnion::{is, get} (NFC) (PR #119673)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes

Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.


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


8 Files Affected:

- (modified) clang/include/clang/AST/APValue.h (+2-4) 
- (modified) clang/include/clang/AST/Decl.h (+5-6) 
- (modified) clang/include/clang/AST/DeclContextInternals.h (+5-5) 
- (modified) clang/include/clang/AST/DeclTemplate.h (+8-9) 
- (modified) clang/include/clang/AST/ExprConcepts.h (+4-4) 
- (modified) clang/include/clang/AST/ExternalASTSource.h (+3-5) 
- (modified) clang/include/clang/AST/Redeclarable.h (+1-1) 
- (modified) clang/include/clang/AST/Type.h (+3-3) 


``diff
diff --git a/clang/include/clang/AST/APValue.h 
b/clang/include/clang/AST/APValue.h
index 7869ee386689d7..4401f3a8ff482c 100644
--- a/clang/include/clang/AST/APValue.h
+++ b/clang/include/clang/AST/APValue.h
@@ -157,11 +157,9 @@ class APValue {
 
 void Profile(llvm::FoldingSetNodeID &ID) const;
 
-template 
-bool is() const { return Ptr.is(); }
+template  bool is() const { return isa(Ptr); }
 
-template 
-T get() const { return Ptr.get(); }
+template  T get() const { return cast(Ptr); }
 
 template 
 T dyn_cast() const { return Ptr.dyn_cast(); }
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 88d93a79d00f8f..67ee0bb412692a 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3457,18 +3457,17 @@ class TypedefNameDecl : public TypeDecl, public 
Redeclarable {
   using redeclarable_base::isFirstDecl;
 
   bool isModed() const {
-return MaybeModedTInfo.getPointer().is();
+return isa(MaybeModedTInfo.getPointer());
   }
 
   TypeSourceInfo *getTypeSourceInfo() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->first
- : MaybeModedTInfo.getPointer().get();
+return isModed() ? cast(MaybeModedTInfo.getPointer())->first
+ : cast(MaybeModedTInfo.getPointer());
   }
 
   QualType getUnderlyingType() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->second
- : MaybeModedTInfo.getPointer()
-   .get()
+return isModed() ? cast(MaybeModedTInfo.getPointer())->second
+ : cast(MaybeModedTInfo.getPointer())
->getType();
   }
 
diff --git a/clang/include/clang/AST/DeclContextInternals.h 
b/clang/include/clang/AST/DeclContextInternals.h
index e169c485921929..b17b7627ac90c5 100644
--- a/clang/include/clang/AST/DeclContextInternals.h
+++ b/clang/include/clang/AST/DeclContextInternals.h
@@ -70,7 +70,7 @@ class StoredDeclsList {
 // want to keep (if any) will be of the form DeclListNode(D, );
 // replace it with just D.
 if (NewLast) {
-  DeclListNode *Node = NewLast->get();
+  DeclListNode *Node = cast(*NewLast);
   *NewLast = Node->D;
   C.DeallocateDeclListNode(Node);
 }
@@ -84,11 +84,11 @@ class StoredDeclsList {
 if (!Data.getPointer())
   // All declarations are erased.
   return nullptr;
-else if (NewHead.is())
+else if (isa(NewHead))
   // The list only contains a declaration, the header itself.
   return (DeclListNode::Decls *)&Data;
 else {
-  assert(NewLast && NewLast->is() && "Not the tail?");
+  assert(NewLast && isa(*NewLast) && "Not the tail?");
   return NewLast;
 }
   }
@@ -207,7 +207,7 @@ class StoredDeclsList {
 }
 
 // Append the Decls.
-DeclListNode *Node = C.AllocateDeclListNode(Tail->get());
+DeclListNode *Node = C.AllocateDeclListNode(cast(*Tail));
 Node->Rest = DeclsAsList;
 *Tail = Node;
   }
@@ -293,7 +293,7 @@ class StoredDeclsList {
 llvm::errs() << '[' << Node->D << "] -> ";
 D = Node->Rest;
   } else {
-llvm::errs() << '[' << D.get() << "]\n";
+llvm::errs() << '[' << cast(D) << "]\n";
 return;
   }
 }
diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 44ccf8932a1830..d3a466a8617bb1 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -319,8 +319,7 @@ class DefaultArgStorage {
 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast())
   Parm = Prev;
-assert(!Parm->getDefaultArgStorage()
-.ValueOrInherited.template is() &&
+assert(!isa(Parm->getDefaultArgStorage().ValueOrInhe

[clang] [AST] Migrate away from PointerUnion::{is, get} (NFC) (PR #119673)

2024-12-12 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/119673

Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.


>From af717b3d499585967571738d2213bfe16c0dd552 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Thu, 12 Dec 2024 00:02:06 -0800
Subject: [PATCH] [AST] Migrate away from PointerUnion::{is,get} (NFC)

Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.
---
 clang/include/clang/AST/APValue.h  |  6 ++
 clang/include/clang/AST/Decl.h | 11 +--
 clang/include/clang/AST/DeclContextInternals.h | 10 +-
 clang/include/clang/AST/DeclTemplate.h | 17 -
 clang/include/clang/AST/ExprConcepts.h |  8 
 clang/include/clang/AST/ExternalASTSource.h|  8 +++-
 clang/include/clang/AST/Redeclarable.h |  2 +-
 clang/include/clang/AST/Type.h |  6 +++---
 8 files changed, 31 insertions(+), 37 deletions(-)

diff --git a/clang/include/clang/AST/APValue.h 
b/clang/include/clang/AST/APValue.h
index 7869ee386689d7..4401f3a8ff482c 100644
--- a/clang/include/clang/AST/APValue.h
+++ b/clang/include/clang/AST/APValue.h
@@ -157,11 +157,9 @@ class APValue {
 
 void Profile(llvm::FoldingSetNodeID &ID) const;
 
-template 
-bool is() const { return Ptr.is(); }
+template  bool is() const { return isa(Ptr); }
 
-template 
-T get() const { return Ptr.get(); }
+template  T get() const { return cast(Ptr); }
 
 template 
 T dyn_cast() const { return Ptr.dyn_cast(); }
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 88d93a79d00f8f..67ee0bb412692a 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3457,18 +3457,17 @@ class TypedefNameDecl : public TypeDecl, public 
Redeclarable {
   using redeclarable_base::isFirstDecl;
 
   bool isModed() const {
-return MaybeModedTInfo.getPointer().is();
+return isa(MaybeModedTInfo.getPointer());
   }
 
   TypeSourceInfo *getTypeSourceInfo() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->first
- : MaybeModedTInfo.getPointer().get();
+return isModed() ? cast(MaybeModedTInfo.getPointer())->first
+ : cast(MaybeModedTInfo.getPointer());
   }
 
   QualType getUnderlyingType() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->second
- : MaybeModedTInfo.getPointer()
-   .get()
+return isModed() ? cast(MaybeModedTInfo.getPointer())->second
+ : cast(MaybeModedTInfo.getPointer())
->getType();
   }
 
diff --git a/clang/include/clang/AST/DeclContextInternals.h 
b/clang/include/clang/AST/DeclContextInternals.h
index e169c485921929..b17b7627ac90c5 100644
--- a/clang/include/clang/AST/DeclContextInternals.h
+++ b/clang/include/clang/AST/DeclContextInternals.h
@@ -70,7 +70,7 @@ class StoredDeclsList {
 // want to keep (if any) will be of the form DeclListNode(D, );
 // replace it with just D.
 if (NewLast) {
-  DeclListNode *Node = NewLast->get();
+  DeclListNode *Node = cast(*NewLast);
   *NewLast = Node->D;
   C.DeallocateDeclListNode(Node);
 }
@@ -84,11 +84,11 @@ class StoredDeclsList {
 if (!Data.getPointer())
   // All declarations are erased.
   return nullptr;
-else if (NewHead.is())
+else if (isa(NewHead))
   // The list only contains a declaration, the header itself.
   return (DeclListNode::Decls *)&Data;
 else {
-  assert(NewLast && NewLast->is() && "Not the tail?");
+  assert(NewLast && isa(*NewLast) && "Not the tail?");
   return NewLast;
 }
   }
@@ -207,7 +207,7 @@ class StoredDeclsList {
 }
 
 // Append the Decls.
-DeclListNode *Node = C.AllocateDeclListNode(Tail->get());
+DeclListNode *Node = C.AllocateDeclListNode(cast(*Tail));
 Node->Rest = DeclsAsList;
 *Tail = Node;
   }
@@ -293,7 +293,7 @@ class StoredDeclsList {
 llvm::errs() << '[' << Node->D << "] -> ";
 D = Node->Rest;
   } else {
-llvm::errs() << '[' << D.get() << "]\n";
+llvm::errs() << '[' << cast(D) << "]\n";
 return;
   }
 }
diff --git a/clan

[clang] [RISCV] Merging RISCVToolChain and BareMetal toolchains (PR #118809)

2024-12-12 Thread Kito Cheng via cfe-commits

kito-cheng wrote:

I would suggest to break this PR into several small pieces, the clang/test 
folder should not having too much change during the merging, especially I feel 
not conformable changing the non-RISC-V file within this PR, I expect those 
change should happened in a separated patch.

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


[clang] [clang-tools-extra] FunctionDecl::getFunctionTypeLoc: ignore function type attributes (PR #118420)

2024-12-12 Thread Robert Dazi via cfe-commits

v01dXYZ wrote:

I've got to squash and reword the commits. Also, I'll add a line to the release 
stating now FunctionDecl getFunctionTypeLoc/getReturrnLoc now supports 
AnnotatedTypes.

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


[clang] [Clang] Deleting an incomplete enum type is not an error (PR #118455)

2024-12-12 Thread A. Jiang via cfe-commits


@@ -540,6 +540,14 @@ namespace PR10504 {
   void f(A *x) { delete x; } // expected-warning {{delete called on 
'PR10504::A' that is abstract but has non-virtual destructor}}
 }
 
+#if __cplusplus >= 201103L
+enum GH99278_1 { // expected-note {{definition of 'GH99278_1' is not complete 
until the closing '}'}}
+zero = decltype(delete static_cast(nullptr), 0){}

frederick-vs-ja wrote:

If one attempts to evaluate such a weird delete-expression, there would be 
initially UB because it's impossible to `new` an object of an incomplete enum 
type. However, the UB would be definitely transformed into constant evaluation 
failure, becaue such an enum type only incomplete in the enum body, where every 
evaluation must be within the constant evaluation of some enumerator.

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


[clang] [Clang] Deleting an incomplete enum type is not an error (PR #118455)

2024-12-12 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja edited 
https://github.com/llvm/llvm-project/pull/118455
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV] Merging RISCVToolChain and BareMetal toolchains (PR #118809)

2024-12-12 Thread Petr Hosek via cfe-commits

petrhosek wrote:

> > I think this change could be made a lot smaller by doing a clean up first, 
> > bringing the BareMetal driver closer to other drivers, before attempting to 
> > merge the RISCVToolChain driver into it.
> 
> Could you describe in a bit more detail which bits you think need to be 
> cleaned up? Or are you planning to push additional changes yourself in the 
> near future? This is a little vague. (We don't want this to be blocked 
> indefinitely.)

Two areas I've specifically been looking into are 
`BareMetal::Linker::ConstructJob` and 
`BareMetal::AddClangCXXStdlibIncludeArgs`. I have local changes for both but 
they need more testing.

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


[clang] [AST] Migrate away from PointerUnion::{is, get} (NFC) (PR #119673)

2024-12-12 Thread Kazu Hirata via cfe-commits

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


[clang] 2a825cd - [AST] Migrate away from PointerUnion::{is,get} (NFC) (#119673)

2024-12-12 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-12-12T01:15:39-08:00
New Revision: 2a825cd2f93b5f83029c36d6c8229f65b6ef2ec7

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

LOG: [AST] Migrate away from PointerUnion::{is,get} (NFC) (#119673)

Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.

Added: 


Modified: 
clang/include/clang/AST/APValue.h
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclContextInternals.h
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/AST/ExprConcepts.h
clang/include/clang/AST/ExternalASTSource.h
clang/include/clang/AST/Redeclarable.h
clang/include/clang/AST/Type.h

Removed: 




diff  --git a/clang/include/clang/AST/APValue.h 
b/clang/include/clang/AST/APValue.h
index 7869ee386689d7..4401f3a8ff482c 100644
--- a/clang/include/clang/AST/APValue.h
+++ b/clang/include/clang/AST/APValue.h
@@ -157,11 +157,9 @@ class APValue {
 
 void Profile(llvm::FoldingSetNodeID &ID) const;
 
-template 
-bool is() const { return Ptr.is(); }
+template  bool is() const { return isa(Ptr); }
 
-template 
-T get() const { return Ptr.get(); }
+template  T get() const { return cast(Ptr); }
 
 template 
 T dyn_cast() const { return Ptr.dyn_cast(); }

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 88d93a79d00f8f..67ee0bb412692a 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3457,18 +3457,17 @@ class TypedefNameDecl : public TypeDecl, public 
Redeclarable {
   using redeclarable_base::isFirstDecl;
 
   bool isModed() const {
-return MaybeModedTInfo.getPointer().is();
+return isa(MaybeModedTInfo.getPointer());
   }
 
   TypeSourceInfo *getTypeSourceInfo() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->first
- : MaybeModedTInfo.getPointer().get();
+return isModed() ? cast(MaybeModedTInfo.getPointer())->first
+ : cast(MaybeModedTInfo.getPointer());
   }
 
   QualType getUnderlyingType() const {
-return isModed() ? MaybeModedTInfo.getPointer().get()->second
- : MaybeModedTInfo.getPointer()
-   .get()
+return isModed() ? cast(MaybeModedTInfo.getPointer())->second
+ : cast(MaybeModedTInfo.getPointer())
->getType();
   }
 

diff  --git a/clang/include/clang/AST/DeclContextInternals.h 
b/clang/include/clang/AST/DeclContextInternals.h
index e169c485921929..b17b7627ac90c5 100644
--- a/clang/include/clang/AST/DeclContextInternals.h
+++ b/clang/include/clang/AST/DeclContextInternals.h
@@ -70,7 +70,7 @@ class StoredDeclsList {
 // want to keep (if any) will be of the form DeclListNode(D, );
 // replace it with just D.
 if (NewLast) {
-  DeclListNode *Node = NewLast->get();
+  DeclListNode *Node = cast(*NewLast);
   *NewLast = Node->D;
   C.DeallocateDeclListNode(Node);
 }
@@ -84,11 +84,11 @@ class StoredDeclsList {
 if (!Data.getPointer())
   // All declarations are erased.
   return nullptr;
-else if (NewHead.is())
+else if (isa(NewHead))
   // The list only contains a declaration, the header itself.
   return (DeclListNode::Decls *)&Data;
 else {
-  assert(NewLast && NewLast->is() && "Not the tail?");
+  assert(NewLast && isa(*NewLast) && "Not the tail?");
   return NewLast;
 }
   }
@@ -207,7 +207,7 @@ class StoredDeclsList {
 }
 
 // Append the Decls.
-DeclListNode *Node = C.AllocateDeclListNode(Tail->get());
+DeclListNode *Node = C.AllocateDeclListNode(cast(*Tail));
 Node->Rest = DeclsAsList;
 *Tail = Node;
   }
@@ -293,7 +293,7 @@ class StoredDeclsList {
 llvm::errs() << '[' << Node->D << "] -> ";
 D = Node->Rest;
   } else {
-llvm::errs() << '[' << D.get() << "]\n";
+llvm::errs() << '[' << cast(D) << "]\n";
 return;
   }
 }

diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 44ccf8932a1830..d3a466a8617bb1 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -319,8 +319,7 @@ class DefaultArgStorage {
 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast())
   Parm = Prev;
- 

[clang] [-Wunsafe-buffer-usage] Suppress warning for multi-dimensional constant arrays (PR #118249)

2024-12-12 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-amdgpu-runtime` running on `omp-vega20-0` while building 
`clang` at step 7 "Add check check-offload".

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


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

```
Step 7 (Add check check-offload) failure: test (failure)
 TEST 'libomptarget :: amdgcn-amd-amdhsa :: 
sanitizer/kernel_crash_async.c' FAILED 
Exit Code: 1

Command Output (stdout):
--
# RUN: at line 2
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp-I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib 
 -fopenmp-targets=amdgcn-amd-amdhsa -O3 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 -o 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib 
-fopenmp-targets=amdgcn-amd-amdhsa -O3 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 -o 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# note: command had no output on stdout or stderr
# RUN: at line 3
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash 
env -u LLVM_DISABLE_SYMBOLIZATION OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 2>&1 | 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=TRACE
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash 
env -u LLVM_DISABLE_SYMBOLIZATION OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
# note: command had no output on stdout or stderr
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=TRACE
# note: command had no output on stdout or stderr
# RUN: at line 4
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 2>&1 | 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=CHECK
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/not --crash 
/home/ompworker/bbot/o

[clang] cfad8f1 - [clang][bytecode] Fix a build failure on aarch64

2024-12-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-12-12T09:08:30+01:00
New Revision: cfad8f14f846860b5c2e413c41c9b2b5642e

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

LOG: [clang][bytecode] Fix a build failure on aarch64

This broke e.g.
https://lab.llvm.org/buildbot/#/builders/190/builds/11216

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 68b6929423e344..a343280b5ce50f 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1950,7 +1950,8 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
 
   size_t MinBufferSize = std::min(BufferA.byteSize().getQuantity(),
   BufferB.byteSize().getQuantity());
-  size_t CmpSize = std::min(MinBufferSize, Size.getZExtValue());
+  size_t CmpSize =
+  std::min(MinBufferSize, static_cast(Size.getZExtValue()));
   int Result = std::memcmp(BufferA.Data.get(), BufferB.Data.get(), CmpSize);
   if (Result == 0)
 pushInteger(S, 0, Call->getType());



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


[clang] [-Wunsafe-buffer-usage] Suppress warning for multi-dimensional constant arrays (PR #118249)

2024-12-12 Thread Malavika Samak via cfe-commits

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


[clang] [Darwin][Driver][clang] Prioritise command line args over `DEFAULT_SYSROOT` (PR #115993)

2024-12-12 Thread Carlo Cabrera via cfe-commits

carlocab wrote:

Tested locally; seems to be working as intended.

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


[clang] [Darwin][Driver][clang] Prioritise command line args over `DEFAULT_SYSROOT` (PR #115993)

2024-12-12 Thread Carlo Cabrera via cfe-commits

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


[clang] 737d78a - [Darwin][Driver][clang] Prioritise command line args over `DEFAULT_SYSROOT` (#115993)

2024-12-12 Thread via cfe-commits

Author: Carlo Cabrera
Date: 2024-12-12T16:15:20+08:00
New Revision: 737d78a9785ea3e928de2b36a4e3e7decd8c9491

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

LOG: [Darwin][Driver][clang] Prioritise command line args over 
`DEFAULT_SYSROOT` (#115993)

If a toolchain is configured with `DEFAULT_SYSROOT`, then this could
result in an unintended value for `-syslibroot` being passed to the
linker if the user manually sets `-isysroot` or `SDKROOT`.

Let's fix this by prioritising command line flags when determining
`-syslibroot` before checking `getSysRoot`.

Downstream bug report:
https://github.com/Homebrew/homebrew-core/issues/197277

Co-authored-by: Bo Anderson 

Co-authored-by: Bo Anderson 

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/sysroot.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 87380869f6fdab..cdb6d21a0148b6 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -430,13 +430,17 @@ void darwin::Linker::AddLinkArgs(Compilation &C, const 
ArgList &Args,
 
   // Give --sysroot= preference, over the Apple specific behavior to also use
   // --isysroot as the syslibroot.
-  StringRef sysroot = C.getSysRoot();
-  if (sysroot != "") {
+  // We check `OPT__sysroot_EQ` directly instead of `getSysRoot` to make sure 
we
+  // prioritise command line arguments over configuration of `DEFAULT_SYSROOT`.
+  if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
 CmdArgs.push_back("-syslibroot");
-CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
+CmdArgs.push_back(A->getValue());
   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
 CmdArgs.push_back("-syslibroot");
 CmdArgs.push_back(A->getValue());
+  } else if (StringRef sysroot = C.getSysRoot(); sysroot != "") {
+CmdArgs.push_back("-syslibroot");
+CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
   }
 
   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);

diff  --git a/clang/test/Driver/sysroot.c b/clang/test/Driver/sysroot.c
index 85da2499090af1..3080f76e031686 100644
--- a/clang/test/Driver/sysroot.c
+++ b/clang/test/Driver/sysroot.c
@@ -4,10 +4,9 @@
 // CHECK-SYSROOTEQ: "-cc1"{{.*}} "-isysroot" "{{[^"]*}}/FOO"
 
 // Apple Darwin uses -isysroot as the syslib root, too.
-// We pass --sysroot="" to defeat any -DDEFAULT_SYSROOT parameter.
 // RUN: touch %t2.o
 // RUN: %clang -target i386-apple-darwin10 \
-// RUN:   -isysroot /FOO --sysroot="" -### %t2.o 2> %t2
+// RUN:   -isysroot /FOO -### %t2.o 2> %t2
 // RUN: FileCheck --check-prefix=CHECK-APPLE-ISYSROOT < %t2 %s
 // CHECK-APPLE-ISYSROOT: "-arch" "i386"{{.*}} "-syslibroot" "{{[^"]*}}/FOO"
 



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


[clang] [clang][Driver][Darwin] Optionally use xcselect to find macOS SDK (PR #119670)

2024-12-12 Thread Carlo Cabrera via cfe-commits

https://github.com/carlocab created 
https://github.com/llvm/llvm-project/pull/119670

This is a scaled down version of https://reviews.llvm.org/D136315.

The intent is largely the same as before[^1], but I've scaled down the scope to 
try to avoid the issues that the previous patch caused:
- the changes are now opt-in based on enabling `CLANG_USE_XCSELECT`
- this only works when targeting macOS on a macOS host (this is the only case 
supported by `libxcselect`[^2])

We also introduce an environment variable `CLANG_NO_XCSELECT` that disables 
this behaviour if Clang is configured with `CLANG_USE_XCSELECT=ON`. This is 
needed to avoid breaking tests.

Another reason to leave this as opt-in for now is that there are some bugs in 
libxcselect that need fixing before it is safe to use by default for all users. 
This has been reported to Apple as FB16081077.

[^1]: See also https://reviews.llvm.org/D109460 and #45225.
[^2]: https://developer.apple.com/documentation/xcselect?language=objc

>From 9db768ec1be84d6bf647b85f052776720822f64f Mon Sep 17 00:00:00 2001
From: Carlo Cabrera 
Date: Tue, 10 Dec 2024 01:45:22 +0800
Subject: [PATCH] [clang][Driver][Darwin] Optionally use xcselect to find macOS
 SDK

This is a scaled down version of https://reviews.llvm.org/D136315.

The intent is largely the same as before[^1], but I've scaled down the scope
to try to avoid the issues that the previous patch caused:
- the changes are now opt-in based on enabling `CLANG_USE_XCSELECT`
- this only works when targeting macOS on a macOS host (this is the only
  case supported by `libxcselect`[^2])

We also introduce an environment variable `CLANG_NO_XCSELECT` that
disables this behaviour if Clang is configured with
`CLANG_USE_XCSELECT=ON`. This is needed to avoid breaking tests.

Another reason to leave this as opt-in for now is that there are some
bugs in libxcselect that need fixing before it is safe to use by default
for all users. This has been reported to Apple as FB16081077.

[^1]: See also https://reviews.llvm.org/D109460 and #45225.
[^2]: https://developer.apple.com/documentation/xcselect?language=objc
---
 clang/CMakeLists.txt  | 33 +++
 clang/include/clang/Config/config.h.cmake |  6 +
 clang/lib/Driver/CMakeLists.txt   |  4 +++
 clang/lib/Driver/ToolChains/Darwin.cpp| 31 ++---
 clang/test/lit.cfg.py |  4 +++
 5 files changed, 69 insertions(+), 9 deletions(-)

diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 27e8095534a65c..3c7096a27c509b 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -214,6 +214,39 @@ if(GCC_INSTALL_PREFIX AND NOT 
USE_DEPRECATED_GCC_INSTALL_PREFIX)
 "See https://github.com/llvm/llvm-project/pull/77537 for detail.")
 endif()
 
+if(APPLE)
+  check_include_file(xcselect.h CLANG_HAVE_XCSELECT_H)
+  if(CLANG_HAVE_XCSELECT_H)
+include(CheckSymbolExists)
+list(APPEND CMAKE_REQUIRED_LIBRARIES xcselect)
+check_symbol_exists(xcselect_host_sdk_path xcselect.h 
CLANG_HAVE_XCSELECT_HOST_SDK_PATH)
+list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES xcselect)
+  endif()
+endif()
+
+cmake_dependent_option(CLANG_USE_XCSELECT "Use libxcselect to find the macOS 
SDK." OFF
+  "APPLE;CLANG_HAVE_XCSELECT_HOST_SDK_PATH" OFF)
+
+if(DEFAULT_SYSROOT AND CLANG_USE_XCSELECT)
+  message(FATAL_ERROR "Setting DEFAULT_SYSROOT is incompatible with 
CLANG_USE_XCSELECT.")
+endif()
+
+if(CLANG_USE_XCSELECT)
+  set(XCSELECT_VALID_POLICIES LATEST MATCHING_ONLY MATCHING_PREFERRED)
+  set(CLANG_XCSELECT_HOST_SDK_POLICY "LATEST" CACHE STRING
+"Policy to use for xcselect. One of: ${XCSELECT_VALID_POLICIES}")
+  set_property(CACHE CLANG_XCSELECT_HOST_SDK_POLICY PROPERTY STRINGS 
${XCSELECT_VALID_POLICIES})
+  string(TOUPPER ${CLANG_XCSELECT_HOST_SDK_POLICY} 
CLANG_XCSELECT_HOST_SDK_POLICY)
+  list(JOIN XCSELECT_VALID_POLICIES "|" XCSELECT_POLICY_REGEX)
+  if(NOT CLANG_XCSELECT_HOST_SDK_POLICY MATCHES 
"^XCSELECT_HOST_SDK_POLICY_(${XCSELECT_POLICY_REGEX})$")
+if(NOT CLANG_XCSELECT_HOST_SDK_POLICY IN_LIST XCSELECT_VALID_POLICIES)
+  message(FATAL_ERROR
+"CLANG_XCSELECT_HOST_SDK_POLICY (${CLANG_XCSELECT_HOST_SDK_POLICY}) 
must be one of: ${XCSELECT_VALID_POLICIES}")
+endif()
+set(CLANG_XCSELECT_HOST_SDK_POLICY 
"XCSELECT_HOST_SDK_POLICY_${CLANG_XCSELECT_HOST_SDK_POLICY}")
+  endif()
+endif()
+
 set(ENABLE_LINKER_BUILD_ID OFF CACHE BOOL "pass --build-id to ld")
 
 set(ENABLE_X86_RELAX_RELOCATIONS ON CACHE BOOL
diff --git a/clang/include/clang/Config/config.h.cmake 
b/clang/include/clang/Config/config.h.cmake
index 27ed69e21562bf..9ae0c6a4b9e11d 100644
--- a/clang/include/clang/Config/config.h.cmake
+++ b/clang/include/clang/Config/config.h.cmake
@@ -86,4 +86,10 @@
 /* Whether CIR is built into Clang */
 #cmakedefine01 CLANG_ENABLE_CIR
 
+/* Whether to use xcselect to find the macOS SDK */
+#cmakedefine CLANG_USE_XCSELECT
+
+/* Policy to use for xcselect */
+#cmakedefine CLANG_XCSELECT_HOST_

[clang] [clang][Driver][Darwin] Optionally use xcselect to find macOS SDK (PR #119670)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Carlo Cabrera (carlocab)


Changes

This is a scaled down version of https://reviews.llvm.org/D136315.

The intent is largely the same as before[^1], but I've scaled down the scope to 
try to avoid the issues that the previous patch caused:
- the changes are now opt-in based on enabling `CLANG_USE_XCSELECT`
- this only works when targeting macOS on a macOS host (this is the only case 
supported by `libxcselect`[^2])

We also introduce an environment variable `CLANG_NO_XCSELECT` that disables 
this behaviour if Clang is configured with `CLANG_USE_XCSELECT=ON`. This is 
needed to avoid breaking tests.

Another reason to leave this as opt-in for now is that there are some bugs in 
libxcselect that need fixing before it is safe to use by default for all users. 
This has been reported to Apple as FB16081077.

[^1]: See also https://reviews.llvm.org/D109460 and #45225.
[^2]: https://developer.apple.com/documentation/xcselect?language=objc

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


5 Files Affected:

- (modified) clang/CMakeLists.txt (+33) 
- (modified) clang/include/clang/Config/config.h.cmake (+6) 
- (modified) clang/lib/Driver/CMakeLists.txt (+4) 
- (modified) clang/lib/Driver/ToolChains/Darwin.cpp (+22-9) 
- (modified) clang/test/lit.cfg.py (+4) 


``diff
diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 27e8095534a65c..3c7096a27c509b 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -214,6 +214,39 @@ if(GCC_INSTALL_PREFIX AND NOT 
USE_DEPRECATED_GCC_INSTALL_PREFIX)
 "See https://github.com/llvm/llvm-project/pull/77537 for detail.")
 endif()
 
+if(APPLE)
+  check_include_file(xcselect.h CLANG_HAVE_XCSELECT_H)
+  if(CLANG_HAVE_XCSELECT_H)
+include(CheckSymbolExists)
+list(APPEND CMAKE_REQUIRED_LIBRARIES xcselect)
+check_symbol_exists(xcselect_host_sdk_path xcselect.h 
CLANG_HAVE_XCSELECT_HOST_SDK_PATH)
+list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES xcselect)
+  endif()
+endif()
+
+cmake_dependent_option(CLANG_USE_XCSELECT "Use libxcselect to find the macOS 
SDK." OFF
+  "APPLE;CLANG_HAVE_XCSELECT_HOST_SDK_PATH" OFF)
+
+if(DEFAULT_SYSROOT AND CLANG_USE_XCSELECT)
+  message(FATAL_ERROR "Setting DEFAULT_SYSROOT is incompatible with 
CLANG_USE_XCSELECT.")
+endif()
+
+if(CLANG_USE_XCSELECT)
+  set(XCSELECT_VALID_POLICIES LATEST MATCHING_ONLY MATCHING_PREFERRED)
+  set(CLANG_XCSELECT_HOST_SDK_POLICY "LATEST" CACHE STRING
+"Policy to use for xcselect. One of: ${XCSELECT_VALID_POLICIES}")
+  set_property(CACHE CLANG_XCSELECT_HOST_SDK_POLICY PROPERTY STRINGS 
${XCSELECT_VALID_POLICIES})
+  string(TOUPPER ${CLANG_XCSELECT_HOST_SDK_POLICY} 
CLANG_XCSELECT_HOST_SDK_POLICY)
+  list(JOIN XCSELECT_VALID_POLICIES "|" XCSELECT_POLICY_REGEX)
+  if(NOT CLANG_XCSELECT_HOST_SDK_POLICY MATCHES 
"^XCSELECT_HOST_SDK_POLICY_(${XCSELECT_POLICY_REGEX})$")
+if(NOT CLANG_XCSELECT_HOST_SDK_POLICY IN_LIST XCSELECT_VALID_POLICIES)
+  message(FATAL_ERROR
+"CLANG_XCSELECT_HOST_SDK_POLICY (${CLANG_XCSELECT_HOST_SDK_POLICY}) 
must be one of: ${XCSELECT_VALID_POLICIES}")
+endif()
+set(CLANG_XCSELECT_HOST_SDK_POLICY 
"XCSELECT_HOST_SDK_POLICY_${CLANG_XCSELECT_HOST_SDK_POLICY}")
+  endif()
+endif()
+
 set(ENABLE_LINKER_BUILD_ID OFF CACHE BOOL "pass --build-id to ld")
 
 set(ENABLE_X86_RELAX_RELOCATIONS ON CACHE BOOL
diff --git a/clang/include/clang/Config/config.h.cmake 
b/clang/include/clang/Config/config.h.cmake
index 27ed69e21562bf..9ae0c6a4b9e11d 100644
--- a/clang/include/clang/Config/config.h.cmake
+++ b/clang/include/clang/Config/config.h.cmake
@@ -86,4 +86,10 @@
 /* Whether CIR is built into Clang */
 #cmakedefine01 CLANG_ENABLE_CIR
 
+/* Whether to use xcselect to find the macOS SDK */
+#cmakedefine CLANG_USE_XCSELECT
+
+/* Policy to use for xcselect */
+#cmakedefine CLANG_XCSELECT_HOST_SDK_POLICY ${CLANG_XCSELECT_HOST_SDK_POLICY}
+
 #endif
diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 4fd10bf671512f..299de2ef30470c 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -14,6 +14,10 @@ if(WIN32)
   set(system_libs version)
 endif()
 
+if(CLANG_USE_XCSELECT)
+  set(system_libs xcselect)
+endif()
+
 add_clang_library(clangDriver
   Action.cpp
   Compilation.cpp
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 87380869f6fdab..8d3e0130a5a432 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -29,6 +29,10 @@
 #include "llvm/TargetParser/Triple.h"
 #include  // ::getenv
 
+#ifdef CLANG_USE_XCSELECT
+#include  // ::xcselect_host_sdk_path
+#endif
+
 using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang::driver::toolchains;
@@ -2257,17 +2261,26 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) 
const {
 // Warn if the path does not exist.
 if (!getVFS().exists

[clang] [clang][Driver][Darwin] Optionally use xcselect to find macOS SDK (PR #119670)

2024-12-12 Thread Carlo Cabrera via cfe-commits

carlocab wrote:

> We also introduce an environment variable `CLANG_NO_XCSELECT` that disables 
> this behaviour if Clang is configured with `CLANG_USE_XCSELECT=ON`. This is 
> needed to avoid breaking tests.

It might also be nicer to set this only for the tests that break instead of 
globally.

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


[clang] [WebKit checkers] Recognize ensureFoo functions (PR #119681)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes

In WebKit, we often write Foo::ensureBar function which lazily initializes 
m_bar and returns a raw pointer or a raw reference to m_bar. Such a return 
value is safe to use for the duration of a member function call in Foo so long 
as m_bar is const so that it never gets unset or updated with a new value once 
it's initialized.

This PR adds support for recognizing these types of functions and treating its 
return value as a safe origin of a function argument (including "this") or a 
local variable.

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


9 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp (+42) 
- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h (+10) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp (+4-1) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp (+4) 
- (modified) 
clang/test/Analysis/Checkers/WebKit/call-args-checked-const-member.cpp (+29) 
- (modified) 
clang/test/Analysis/Checkers/WebKit/call-args-counted-const-member.cpp (+29) 
- (modified) 
clang/test/Analysis/Checkers/WebKit/local-vars-checked-const-member.cpp (+33) 
- (modified) 
clang/test/Analysis/Checkers/WebKit/local-vars-counted-const-member.cpp (+33) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+32-29) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index b3cd594a0f3529..4086b267b6dad8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/AST/StmtVisitor.h"
 #include 
 
 namespace clang {
@@ -158,6 +159,9 @@ bool isConstOwnerPtrMemberExpr(const clang::Expr *E) {
 E = ThisArg;
   }
 }
+  } else if (auto *OCE = dyn_cast(E)) {
+if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
+  E = OCE->getArg(0);
   }
   auto *ME = dyn_cast(E);
   if (!ME)
@@ -169,4 +173,42 @@ bool isConstOwnerPtrMemberExpr(const clang::Expr *E) {
   return isOwnerPtrType(T) && T.isConstQualified();
 }
 
+class EnsureFunctionVisitor
+: public ConstStmtVisitor {
+public:
+  bool VisitStmt(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && !Visit(Child))
+return false;
+}
+return true;
+  }
+
+  bool VisitReturnStmt(const ReturnStmt *RS) {
+if (auto *RV = RS->getRetValue()) {
+  RV = RV->IgnoreParenCasts();
+  if (isa(RV))
+return true;
+  return isConstOwnerPtrMemberExpr(RV);
+}
+return false;
+  }
+};
+
+bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
+  auto *MCE = dyn_cast(E);
+  if (!MCE)
+return false;
+  auto *Callee = MCE->getDirectCallee();
+  if (!Callee)
+return false;
+  auto* Body = Callee->getBody();
+  if (!Body)
+return false;
+  auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
+  if (IsNew)
+CacheIt->second = EnsureFunctionVisitor().Visit(Body);
+  return CacheIt->second;
+}
+
 } // namespace clang
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index ddbef0fba04489..a4d46235dc9c47 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -67,6 +67,16 @@ bool isASafeCallArg(const clang::Expr *E);
 /// \returns true if E is a MemberExpr accessing a const smart pointer type.
 bool isConstOwnerPtrMemberExpr(const clang::Expr *E);
 
+/// \returns true if E is a CXXMemberCallExpr which returns a const smart 
pointer
+/// type.
+class EnsureFunctionAnalysis {
+  using CacheTy = llvm::DenseMap;
+  mutable CacheTy Cache{};
+
+public:
+  bool isACallToEnsureFn(const Expr *E) const;
+};
+
 /// \returns name of AST node or empty string.
 template  std::string safeGetName(const T *ASTNode) {
   const auto *const ND = llvm::dyn_cast_or_null(ASTNode);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
index ef2d42ccada65c..56fa72c100ec8c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
@@ -33,6 +33,7 @@ class RawPtrRefCallArgsChecker
   mutable BugReporter *BR;
 
   TrivialFunctionAnalysis TFA;
+  EnsureFunctionAnalysis EFA;
 
 public:
   RawPtrRefCallArgsChecker(const char *description)
@@ -140,7 +141,7 @@ class RawPtrRefCallArgsChecker
 
   bool isPtrOriginSafe(const Expr *Arg) const {
 return tryToFindPtrOrigin(Arg, /*StopAtFirstRefCountedObj=*/true,
-   

[clang] [WebKit checkers] Recognize ensureFoo functions (PR #119681)

2024-12-12 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/119681

In WebKit, we often write Foo::ensureBar function which lazily initializes 
m_bar and returns a raw pointer or a raw reference to m_bar. Such a return 
value is safe to use for the duration of a member function call in Foo so long 
as m_bar is const so that it never gets unset or updated with a new value once 
it's initialized.

This PR adds support for recognizing these types of functions and treating its 
return value as a safe origin of a function argument (including "this") or a 
local variable.

>From 0982f5ca3f9d1ea713b1e34b6e6b9d08ff65e6f1 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Thu, 12 Dec 2024 01:31:42 -0800
Subject: [PATCH] [WebKit checkers] Recognize ensureFoo functions

In WebKit, we often write Foo::ensureBar function which lazily initializes 
m_bar and returns
a raw pointer or a raw reference to m_bar. Such a return value is safe to use 
for the
duration of a member function call in Foo so long as m_bar is const so that it 
never gets
unset or updated with a new value once it's initialized.

This PR adds support for recognizing these types of functions and treating its 
return value
as a safe origin of a function argument (including "this") or a local variable.
---
 .../Checkers/WebKit/ASTUtils.cpp  | 42 +
 .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 10 +++
 .../WebKit/RawPtrRefCallArgsChecker.cpp   |  5 +-
 .../WebKit/RawPtrRefLocalVarsChecker.cpp  |  4 ++
 .../WebKit/call-args-checked-const-member.cpp | 29 +
 .../WebKit/call-args-counted-const-member.cpp | 29 +
 .../local-vars-checked-const-member.cpp   | 33 ++
 .../local-vars-counted-const-member.cpp   | 33 ++
 .../Analysis/Checkers/WebKit/mock-types.h | 61 ++-
 9 files changed, 216 insertions(+), 30 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index b3cd594a0f3529..4086b267b6dad8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/AST/StmtVisitor.h"
 #include 
 
 namespace clang {
@@ -158,6 +159,9 @@ bool isConstOwnerPtrMemberExpr(const clang::Expr *E) {
 E = ThisArg;
   }
 }
+  } else if (auto *OCE = dyn_cast(E)) {
+if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
+  E = OCE->getArg(0);
   }
   auto *ME = dyn_cast(E);
   if (!ME)
@@ -169,4 +173,42 @@ bool isConstOwnerPtrMemberExpr(const clang::Expr *E) {
   return isOwnerPtrType(T) && T.isConstQualified();
 }
 
+class EnsureFunctionVisitor
+: public ConstStmtVisitor {
+public:
+  bool VisitStmt(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && !Visit(Child))
+return false;
+}
+return true;
+  }
+
+  bool VisitReturnStmt(const ReturnStmt *RS) {
+if (auto *RV = RS->getRetValue()) {
+  RV = RV->IgnoreParenCasts();
+  if (isa(RV))
+return true;
+  return isConstOwnerPtrMemberExpr(RV);
+}
+return false;
+  }
+};
+
+bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
+  auto *MCE = dyn_cast(E);
+  if (!MCE)
+return false;
+  auto *Callee = MCE->getDirectCallee();
+  if (!Callee)
+return false;
+  auto* Body = Callee->getBody();
+  if (!Body)
+return false;
+  auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
+  if (IsNew)
+CacheIt->second = EnsureFunctionVisitor().Visit(Body);
+  return CacheIt->second;
+}
+
 } // namespace clang
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index ddbef0fba04489..a4d46235dc9c47 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -67,6 +67,16 @@ bool isASafeCallArg(const clang::Expr *E);
 /// \returns true if E is a MemberExpr accessing a const smart pointer type.
 bool isConstOwnerPtrMemberExpr(const clang::Expr *E);
 
+/// \returns true if E is a CXXMemberCallExpr which returns a const smart 
pointer
+/// type.
+class EnsureFunctionAnalysis {
+  using CacheTy = llvm::DenseMap;
+  mutable CacheTy Cache{};
+
+public:
+  bool isACallToEnsureFn(const Expr *E) const;
+};
+
 /// \returns name of AST node or empty string.
 template  std::string safeGetName(const T *ASTNode) {
   const auto *const ND = llvm::dyn_cast_or_null(ASTNode);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
index ef2d42ccada65c..56fa72c100ec8c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRe

[clang] 98470c0 - [clang][bytecode] Handle __builtin_bcmp (#119678)

2024-12-12 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-12-12T10:57:39+01:00
New Revision: 98470c0b2e0eef52e6900bf2d524a390edac9d58

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

LOG: [clang][bytecode] Handle __builtin_bcmp (#119678)

... the same as `__builtin_memcmp`. Also fix a bug we still had when we
couldn't find a difference in the two inputs after `Size` bytes.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/test/AST/ByteCode/builtin-functions.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index a343280b5ce50f..21baedf832eeac 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1917,7 +1917,7 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   const APSInt &Size =
   peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(2)));
 
-  if (ID == Builtin::BImemcmp)
+  if (ID == Builtin::BImemcmp || ID == Builtin::BIbcmp)
 diagnoseNonConstexprBuiltin(S, OpPC, ID);
 
   if (Size.isZero()) {
@@ -1952,15 +1952,34 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   BufferB.byteSize().getQuantity());
   size_t CmpSize =
   std::min(MinBufferSize, static_cast(Size.getZExtValue()));
-  int Result = std::memcmp(BufferA.Data.get(), BufferB.Data.get(), CmpSize);
-  if (Result == 0)
+
+  for (size_t I = 0; I != CmpSize; ++I) {
+std::byte A = BufferA.Data[I];
+std::byte B = BufferB.Data[I];
+
+if (A < B) {
+  pushInteger(S, -1, Call->getType());
+  return true;
+} else if (A > B) {
+  pushInteger(S, 1, Call->getType());
+  return true;
+}
+  }
+
+  // We compared CmpSize bytes above. If the limiting factor was the Size
+  // passed, we're done and the result is equality (0).
+  if (Size.getZExtValue() <= CmpSize) {
 pushInteger(S, 0, Call->getType());
-  else if (Result < 0)
-pushInteger(S, -1, Call->getType());
-  else
-pushInteger(S, 1, Call->getType());
+return true;
+  }
 
-  return true;
+  // However, if we read all the available bytes but were instructed to read
+  // even more, diagnose this as a "read of dereferenced one-past-the-end
+  // pointer". This is what would happen if we called CheckRead() on every 
array
+  // element.
+  S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
+  << AK_Read << S.Current->getRange(OpPC);
+  return false;
 }
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
@@ -2438,6 +2457,8 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
 
   case Builtin::BI__builtin_memcmp:
   case Builtin::BImemcmp:
+  case Builtin::BI__builtin_bcmp:
+  case Builtin::BIbcmp:
 if (!interp__builtin_memcmp(S, OpPC, Frame, F, Call))
   return false;
 break;

diff  --git a/clang/test/AST/ByteCode/builtin-functions.cpp 
b/clang/test/AST/ByteCode/builtin-functions.cpp
index 83caa1d03df3a3..4ee24646286fa8 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -1255,4 +1255,19 @@ namespace Memcmp {
   // both-note 
{{not supported}}
   static_assert(__builtin_memcmp("", &incomplete, 1u) == 42); // both-error 
{{not an integral constant}} \
   // both-note 
{{not supported}}
+
+  static_assert(__builtin_memcmp(u8"abab\0banana", u8"abab\0banana", 100) == 
0); // both-error {{not an integral constant}} \
+   
  // both-note {{dereferenced one-past-the-end}}
+
+  static_assert(__builtin_bcmp("abaa", "abba", 3) != 0);
+  static_assert(__builtin_bcmp("abaa", "abba", 2) == 0);
+  static_assert(__builtin_bcmp("a\203", "a", 2) != 0);
+  static_assert(__builtin_bcmp("a\203", "a\003", 2) != 0);
+  static_assert(__builtin_bcmp(0, 0, 0) == 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0banana", 100) == 0); // 
both-error {{not an integral constant}}\
+   // 
both-note {{dereferenced one-past-the-end}}
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 100) != 0); // 
FIXME: Should we reject this?
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 7) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 6) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 5) == 0);
 }



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


[clang] [clang][bytecode] Handle __builtin_bcmp (PR #119678)

2024-12-12 Thread Timm Baeder via cfe-commits

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


[clang] [clang] Enable the -Wdangling-capture diagnostic by default. (PR #119685)

2024-12-12 Thread Haojian Wu via cfe-commits

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

We have tested this diagnostics internally, and we don't find see any issues.

>From be7678e1798ad61af05ac3f83d7149125be9ed7a Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 12 Dec 2024 10:57:06 +0100
Subject: [PATCH] [clang] Enable the -Wdangling-capture diagnostic by default.

---
 clang/docs/ReleaseNotes.rst  | 9 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 4 ++--
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6802c0c50b8f0c..7cb18225cb38c2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -664,6 +664,15 @@ Improvements to Clang's diagnostics
   bool operator==(const C&) = default;
 };
 
+- Clang now emits `-Wdangling-capture` diangostic when a STL container 
captures a dangling reference.
+
+  .. code-block:: c++
+
+void test() {
+  std::vector views;
+  views.push_back(std::string("123")); // warning
+}
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0a245e2077f68f..811265151fa0da 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10237,10 +10237,10 @@ def warn_dangling_pointer_assignment : Warning<
InGroup;
 def warn_dangling_reference_captured : Warning<
"object whose reference is captured by '%0' will be destroyed at the end of 
"
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 def warn_dangling_reference_captured_by_unknown : Warning<
"object whose reference is captured will be destroyed at the end of "
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.

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


[clang] [clang][bytecode] Handle __builtin_bcmp (PR #119678)

2024-12-12 Thread Timm Baeder via cfe-commits

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

... the same as `__builtin_memcmp`. Also fix a bug we still had when we 
couldn't find a difference in the two inputs after `Size` bytes.

>From 3a480676781925badff8b88c3833f083fdc3dcbd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 12 Dec 2024 10:17:45 +0100
Subject: [PATCH] [clang][bytecode] Handle __builtin_bcmp

... the same as `__builtin_memcmp`. Also fix a bug we still had when we
couldn't find a difference in the two inputs after `Size` bytes.
---
 clang/lib/AST/ByteCode/InterpBuiltin.cpp  | 37 +++
 clang/test/AST/ByteCode/builtin-functions.cpp | 15 
 2 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index a343280b5ce50f..21baedf832eeac 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1917,7 +1917,7 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   const APSInt &Size =
   peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(2)));
 
-  if (ID == Builtin::BImemcmp)
+  if (ID == Builtin::BImemcmp || ID == Builtin::BIbcmp)
 diagnoseNonConstexprBuiltin(S, OpPC, ID);
 
   if (Size.isZero()) {
@@ -1952,15 +1952,34 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   BufferB.byteSize().getQuantity());
   size_t CmpSize =
   std::min(MinBufferSize, static_cast(Size.getZExtValue()));
-  int Result = std::memcmp(BufferA.Data.get(), BufferB.Data.get(), CmpSize);
-  if (Result == 0)
+
+  for (size_t I = 0; I != CmpSize; ++I) {
+std::byte A = BufferA.Data[I];
+std::byte B = BufferB.Data[I];
+
+if (A < B) {
+  pushInteger(S, -1, Call->getType());
+  return true;
+} else if (A > B) {
+  pushInteger(S, 1, Call->getType());
+  return true;
+}
+  }
+
+  // We compared CmpSize bytes above. If the limiting factor was the Size
+  // passed, we're done and the result is equality (0).
+  if (Size.getZExtValue() <= CmpSize) {
 pushInteger(S, 0, Call->getType());
-  else if (Result < 0)
-pushInteger(S, -1, Call->getType());
-  else
-pushInteger(S, 1, Call->getType());
+return true;
+  }
 
-  return true;
+  // However, if we read all the available bytes but were instructed to read
+  // even more, diagnose this as a "read of dereferenced one-past-the-end
+  // pointer". This is what would happen if we called CheckRead() on every 
array
+  // element.
+  S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
+  << AK_Read << S.Current->getRange(OpPC);
+  return false;
 }
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
@@ -2438,6 +2457,8 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
 
   case Builtin::BI__builtin_memcmp:
   case Builtin::BImemcmp:
+  case Builtin::BI__builtin_bcmp:
+  case Builtin::BIbcmp:
 if (!interp__builtin_memcmp(S, OpPC, Frame, F, Call))
   return false;
 break;
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp 
b/clang/test/AST/ByteCode/builtin-functions.cpp
index 83caa1d03df3a3..4ee24646286fa8 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -1255,4 +1255,19 @@ namespace Memcmp {
   // both-note 
{{not supported}}
   static_assert(__builtin_memcmp("", &incomplete, 1u) == 42); // both-error 
{{not an integral constant}} \
   // both-note 
{{not supported}}
+
+  static_assert(__builtin_memcmp(u8"abab\0banana", u8"abab\0banana", 100) == 
0); // both-error {{not an integral constant}} \
+   
  // both-note {{dereferenced one-past-the-end}}
+
+  static_assert(__builtin_bcmp("abaa", "abba", 3) != 0);
+  static_assert(__builtin_bcmp("abaa", "abba", 2) == 0);
+  static_assert(__builtin_bcmp("a\203", "a", 2) != 0);
+  static_assert(__builtin_bcmp("a\203", "a\003", 2) != 0);
+  static_assert(__builtin_bcmp(0, 0, 0) == 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0banana", 100) == 0); // 
both-error {{not an integral constant}}\
+   // 
both-note {{dereferenced one-past-the-end}}
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 100) != 0); // 
FIXME: Should we reject this?
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 7) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 6) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 5) == 0);
 }

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

[clang] [clang-tools-extra] [llvm] [MTE] Apply alignment / size in AsmPrinter rather than IR (PR #111918)

2024-12-12 Thread Florian Mayer via cfe-commits


@@ -808,6 +808,10 @@ void Verifier::visitGlobalValue(const GlobalValue &GV) {
   "visibility must be dso_local!",
   &GV);
 
+  if (GV.isTagged()) {

fmayer wrote:

The codegen has "is section == precisely honor alignment"

```
Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const {
[...]
  // If a section is specified, always precisely honor explicit alignment,
  // so we don't insert padding into a section we don't control.
  if (GVAlignment && GV->hasSection())
return *GVAlignment;
```

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


[clang] [WebKit checkers] Recognize ensureFoo functions (PR #119681)

2024-12-12 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff dd8d85dba6e8f74a55fb5053107797e21894a0c6 
0982f5ca3f9d1ea713b1e34b6e6b9d08ff65e6f1 --extensions h,cpp -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp 
clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp 
clang/test/Analysis/Checkers/WebKit/call-args-checked-const-member.cpp 
clang/test/Analysis/Checkers/WebKit/call-args-counted-const-member.cpp 
clang/test/Analysis/Checkers/WebKit/local-vars-checked-const-member.cpp 
clang/test/Analysis/Checkers/WebKit/local-vars-counted-const-member.cpp 
clang/test/Analysis/Checkers/WebKit/mock-types.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 4086b267b6..da6d4598cb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -202,7 +202,7 @@ bool EnsureFunctionAnalysis::isACallToEnsureFn(const 
clang::Expr *E) const {
   auto *Callee = MCE->getDirectCallee();
   if (!Callee)
 return false;
-  auto* Body = Callee->getBody();
+  auto *Body = Callee->getBody();
   if (!Body)
 return false;
   auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index a4d46235dc..b508043d0f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -67,8 +67,8 @@ bool isASafeCallArg(const clang::Expr *E);
 /// \returns true if E is a MemberExpr accessing a const smart pointer type.
 bool isConstOwnerPtrMemberExpr(const clang::Expr *E);
 
-/// \returns true if E is a CXXMemberCallExpr which returns a const smart 
pointer
-/// type.
+/// \returns true if E is a CXXMemberCallExpr which returns a const smart
+/// pointer type.
 class EnsureFunctionAnalysis {
   using CacheTy = llvm::DenseMap;
   mutable CacheTy Cache{};

``




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


[clang] [clang] Enable the -Wdangling-capture diagnostic by default. (PR #119685)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

We have tested this diagnostics internally, and we don't find see any issues.

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


2 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+9) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6802c0c50b8f0c..7cb18225cb38c2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -664,6 +664,15 @@ Improvements to Clang's diagnostics
   bool operator==(const C&) = default;
 };
 
+- Clang now emits `-Wdangling-capture` diangostic when a STL container 
captures a dangling reference.
+
+  .. code-block:: c++
+
+void test() {
+  std::vector views;
+  views.push_back(std::string("123")); // warning
+}
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0a245e2077f68f..811265151fa0da 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10237,10 +10237,10 @@ def warn_dangling_pointer_assignment : Warning<
InGroup;
 def warn_dangling_reference_captured : Warning<
"object whose reference is captured by '%0' will be destroyed at the end of 
"
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 def warn_dangling_reference_captured_by_unknown : Warning<
"object whose reference is captured will be destroyed at the end of "
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.

``




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


[clang] [C++20][Modules] Load function body from the module that gives canonical decl (PR #111992)

2024-12-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

We'll try the latest version and report back.

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


[clang] [clang] Enable the -Wdangling-capture diagnostic by default. (PR #119685)

2024-12-12 Thread Gábor Horváth via cfe-commits

https://github.com/Xazax-hun approved this pull request.

LGTM! 

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits

https://github.com/gerekon updated 
https://github.com/llvm/llvm-project/pull/118008

>From bf0488585f41d3342c5c6d289d4621e3f50195cc Mon Sep 17 00:00:00 2001
From: Andrei Safronov 
Date: Thu, 1 Jun 2023 00:42:37 +0300
Subject: [PATCH 1/2] [Clang][Xtensa] Add Xtensa target.

---
 clang/include/clang/Basic/TargetInfo.h |   5 +-
 clang/lib/AST/ASTContext.cpp   |  47 
 clang/lib/Basic/CMakeLists.txt |   1 +
 clang/lib/Basic/Targets.cpp|   4 +
 clang/lib/Basic/Targets/Xtensa.cpp |  62 +
 clang/lib/Basic/Targets/Xtensa.h   | 141 +++
 clang/lib/Driver/ToolChains/CommonArgs.cpp |   5 +
 clang/test/Preprocessor/init.c | 272 +
 clang/test/Preprocessor/stdint.c   | 107 
 9 files changed, 643 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/Basic/Targets/Xtensa.cpp
 create mode 100644 clang/lib/Basic/Targets/Xtensa.h

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 9cd23d123f2bac..97444ef28a66d8 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -358,7 +358,10 @@ class TargetInfo : public TransferrableTargetInfo,
 //void *__saved_reg_area_end_pointer;
 //void *__overflow_area_pointer;
 //} va_list;
-HexagonBuiltinVaList
+HexagonBuiltinVaList,
+
+// Tensilica Xtensa
+XtensaABIBuiltinVaList
   };
 
 protected:
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 80e8c5b9df58e7..0f2df53d07e086 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -9727,6 +9727,51 @@ static TypedefDecl *CreateHexagonBuiltinVaListDecl(const 
ASTContext *Context) {
   return Context->buildImplicitTypedef(VaListTagArrayType, 
"__builtin_va_list");
 }
 
+static TypedefDecl *
+CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
+  // typedef struct __va_list_tag {
+  RecordDecl *VaListTagDecl;
+
+  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
+  VaListTagDecl->startDefinition();
+
+  const size_t NumFields = 3;
+  QualType FieldTypes[NumFields];
+  const char *FieldNames[NumFields];
+
+  // int* __va_stk;
+  FieldTypes[0] = Context->getPointerType(Context->IntTy);
+  FieldNames[0] = "__va_stk";
+
+  // int* __va_reg;
+  FieldTypes[1] = Context->getPointerType(Context->IntTy);
+  FieldNames[1] = "__va_reg";
+
+  // int __va_ndx;
+  FieldTypes[2] = Context->IntTy;
+  FieldNames[2] = "__va_ndx";
+
+  // Create fields
+  for (unsigned i = 0; i < NumFields; ++i) {
+FieldDecl *Field = FieldDecl::Create(
+*Context, VaListTagDecl, SourceLocation(), SourceLocation(),
+&Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
+/*BitWidth=*/nullptr,
+/*Mutable=*/false, ICIS_NoInit);
+Field->setAccess(AS_public);
+VaListTagDecl->addDecl(Field);
+  }
+  VaListTagDecl->completeDefinition();
+  Context->VaListTagDecl = VaListTagDecl;
+  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
+
+  // } __va_list_tag;
+  TypedefDecl *VaListTagTypedefDecl =
+  Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
+
+  return VaListTagTypedefDecl;
+}
+
 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  TargetInfo::BuiltinVaListKind Kind) {
   switch (Kind) {
@@ -9748,6 +9793,8 @@ static TypedefDecl *CreateVaListDecl(const ASTContext 
*Context,
 return CreateSystemZBuiltinVaListDecl(Context);
   case TargetInfo::HexagonBuiltinVaList:
 return CreateHexagonBuiltinVaListDecl(Context);
+  case TargetInfo::XtensaABIBuiltinVaList:
+return CreateXtensaABIBuiltinVaListDecl(Context);
   }
 
   llvm_unreachable("Unhandled __builtin_va_list type kind");
diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index e11e1ac4a6fa63..331dfbb3f4b67e 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -120,6 +120,7 @@ add_clang_library(clangBasic
   Targets/WebAssembly.cpp
   Targets/X86.cpp
   Targets/XCore.cpp
+  Targets/Xtensa.cpp
   TokenKinds.cpp
   TypeTraits.cpp
   Version.cpp
diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 0021d33c45d7c9..3ef99acdc2e323 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -40,6 +40,7 @@
 #include "Targets/WebAssembly.h"
 #include "Targets/X86.h"
 #include "Targets/XCore.h"
+#include "Targets/Xtensa.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticFrontend.h"
 #include "llvm/ADT/StringExtras.h"
@@ -737,6 +738,9 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple &Triple,
 default:
 return std::make_unique(Triple, Opts);
 }
+
+  case llvm::Triple::xtensa:
+return std::make_unique(Triple, Opts);
   }
 }
 } // namespace targets
diff --git a/clang/lib/Basic/Targets/Xtensa.cpp 
b/clang/lib/Basic/Targets/Xt

[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -358,7 +358,10 @@ class TargetInfo : public TransferrableTargetInfo,
 //void *__saved_reg_area_end_pointer;
 //void *__overflow_area_pointer;
 //} va_list;
-HexagonBuiltinVaList
+HexagonBuiltinVaList,
+
+// Tensilica Xtensa
+XtensaABIBuiltinVaList

gerekon wrote:

fixed

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -9727,6 +9727,51 @@ static TypedefDecl *CreateHexagonBuiltinVaListDecl(const 
ASTContext *Context) {
   return Context->buildImplicitTypedef(VaListTagArrayType, 
"__builtin_va_list");
 }
 
+static TypedefDecl *
+CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
+  // typedef struct __va_list_tag {
+  RecordDecl *VaListTagDecl;
+
+  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
+  VaListTagDecl->startDefinition();
+
+  const size_t NumFields = 3;
+  QualType FieldTypes[NumFields];

gerekon wrote:

fixed

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -9727,6 +9727,51 @@ static TypedefDecl *CreateHexagonBuiltinVaListDecl(const 
ASTContext *Context) {
   return Context->buildImplicitTypedef(VaListTagArrayType, 
"__builtin_va_list");
 }
 
+static TypedefDecl *
+CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
+  // typedef struct __va_list_tag {
+  RecordDecl *VaListTagDecl;

gerekon wrote:

fixed

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -0,0 +1,62 @@
+//===--- Xtensa.cpp - Implement Xtensa target feature support 
-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements Xtensa TargetInfo objects.
+//
+//===--===//
+
+#include "Xtensa.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/MacroBuilder.h"
+#include "clang/Basic/TargetBuiltins.h"
+
+using namespace clang;
+using namespace clang::targets;
+
+void XtensaTargetInfo::getTargetDefines(const LangOptions &Opts,
+MacroBuilder &Builder) const {
+  Builder.defineMacro("__xtensa__");
+  Builder.defineMacro("__XTENSA__");
+  if (BigEndian)

gerekon wrote:

fixed

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -9727,6 +9727,51 @@ static TypedefDecl *CreateHexagonBuiltinVaListDecl(const 
ASTContext *Context) {
   return Context->buildImplicitTypedef(VaListTagArrayType, 
"__builtin_va_list");
 }
 
+static TypedefDecl *
+CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
+  // typedef struct __va_list_tag {
+  RecordDecl *VaListTagDecl;
+
+  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
+  VaListTagDecl->startDefinition();
+
+  const size_t NumFields = 3;

gerekon wrote:

fixed

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


[clang] [Clang][Xtensa] Add Xtensa target. (PR #118008)

2024-12-12 Thread Alexey Gerenkov via cfe-commits


@@ -0,0 +1,141 @@
+//===--- Xtensa.h - Declare Xtensa target feature support ---*- C++ 
-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file declares Xtensa TargetInfo objects.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_BASIC_TARGETS_XTENSA_H
+#define LLVM_CLANG_LIB_BASIC_TARGETS_XTENSA_H
+
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/TargetParser/Triple.h"
+
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/MacroBuilder.h"
+#include "clang/Basic/TargetBuiltins.h"
+
+namespace clang {
+namespace targets {
+
+class LLVM_LIBRARY_VISIBILITY XtensaTargetInfo : public TargetInfo {
+  static const Builtin::Info BuiltinInfo[];
+
+protected:
+  std::string CPU;
+  bool HasFP = false;

gerekon wrote:

fixed

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


[libclc] [libclc] Optimize ceil/fabs/floor/rint/trunc (PR #119596)

2024-12-12 Thread Matt Arsenault via cfe-commits

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

LGTM. I'm not sure how this all ends up expanding, I was expecting to see the 
elementwise builtins used.

It would be great if we had update_cc_test_checks style testing for the 
resulting implementation 

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


[clang] [clang] Fix sub-integer __builtin_elementwise_(add|sub)_sat (PR #119423)

2024-12-12 Thread Fraser Cormack via cfe-commits

frasercrmck wrote:

> Even with this fix, the behavior with mixed types still seems really 
> confusing, especially if you mix signed/unsigned inputs. Can we address that 
> somehow?

I totally agree.

The (elementwise) builtins won't let you mix `ext_vector_type`s of different 
signs or element sizes, so maybe we should extend logic that to all scalars 
too? Ban mixed signs? Ban mixed sizes entirely? This would be a larger change 
that would probably need documenting - an RFC? Worth noting perhaps that maybe 
the current vector behaviour depends on the type of vectors you use (OpenCL, 
AltiVec, GCC, NEON, SVE) - I haven't checked that.

I note also that the documentation says that `For scalar types, consider the 
operation applied to a vector with a single element.`. This is misleading, as 
the usual implicit conversions don't behave the same way for scalars as they do 
for vectors.

CC @arsenm - might be of interest to you.

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


[clang] [Clang] Add fake use emission to Clang with -fextend-lifetimes (PR #110102)

2024-12-12 Thread Stephen Tozer via cfe-commits


@@ -1664,6 +1710,17 @@ CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  
emission.getOriginalAllocatedAddress(),
  emission.getSizeForLifetimeMarkers());
 
+  // Analogous to lifetime markers, we use a 'cleanup' to emit fake.use
+  // calls for local variables. We are exempting volatile variables and
+  // non-scalars larger than 4 times the size of an unsigned int (32 bytes).
+  // Larger non-scalars are often allocated in memory and may create 
unnecessary
+  // overhead.
+  if (CGM.getCodeGenOpts().ExtendLifetimes) {
+if (extendLifetime(getContext(), CurCodeDecl, D, CXXABIThisDecl))
+  EHStack.pushCleanup(NormalFakeUse,
+   emission.getAllocatedAddress());

SLTozer wrote:

Looks like the difference is about allocas in a non-default address space - 
essentially we'll get either:
```
  %i = alloca i32, align 4, addrspace(5)
  %i.ascast = addrspacecast ptr addrspace(5) %i to ptr
  store i32 %someval, ptr %i.ascast, align 4
; getAllocatedAddress
  %fake.use = load i32, ptr %i.ascast, align 4
  call void (...) @llvm.fake.use(i32 %fake.use)
; getOriginalAllocatedAddress
  %fake.use = load i32, ptr addrspace(5) %i, align 4
  call void (...) @llvm.fake.use(i32 %fake.use)
```
In practice, both of them result in extended variable lifetimes (the fake use 
will continue to track `%someval` in both cases), so I _think_ this is 
unimportant. On the one hand, the pointer that we use to store and load is 
`%i.ascast`, so it seems consistent for the fake use to use that; on the other 
hand, if a `#dbg_declare` is created, it will refer to `ptr addrspace(5) %i`, 
so that could be more appropriate for the fake use. In summary: I don't know, 
and I don't think it matters.

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


[clang] [clang][ASTVisitor] Visit `HoldingVar` from `BindingDecl`. (PR #117858)

2024-12-12 Thread Clement Courbet via cfe-commits

https://github.com/legrosbuffle updated 
https://github.com/llvm/llvm-project/pull/117858

>From f388f19e26bdd7e45e874e4574e7d9196c2eaf0b Mon Sep 17 00:00:00 2001
From: Clement Courbet 
Date: Mon, 25 Nov 2024 15:52:18 +
Subject: [PATCH 1/3] [clang][ASTVisitor] Visit `HoldingVar` from
 `BindingDecl`.

Tuple-like types introduce `VarDecl`s in the AST for their "holding
vars", but AST visitors do not visit those. As a result the `VarDecl`
for the holding var is orphaned when trying to retreive its parents.

Fix a `FlowSensitive` test that assumes that only a `BindingDecl`
is introduced with the given name (the matcher now can also reach
the `VarDecl` for the holding var).
---
 clang/include/clang/AST/RecursiveASTVisitor.h |  5 +-
 .../unittests/AST/ASTContextParentMapTest.cpp | 49 +++
 .../Analysis/FlowSensitive/TransferTest.cpp   | 17 +--
 3 files changed, 66 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 2b35997bd539ac..3ff60555c7873c 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2143,8 +2143,11 @@ DEF_TRAVERSE_DECL(DecompositionDecl, {
 })
 
 DEF_TRAVERSE_DECL(BindingDecl, {
-  if (getDerived().shouldVisitImplicitCode())
+  if (getDerived().shouldVisitImplicitCode()) {
 TRY_TO(TraverseStmt(D->getBinding()));
+if (const auto HoldingVar = D->getHoldingVar())
+  TRY_TO(TraverseDecl(HoldingVar));
+  }
 })
 
 DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
diff --git a/clang/unittests/AST/ASTContextParentMapTest.cpp 
b/clang/unittests/AST/ASTContextParentMapTest.cpp
index 515dfb99e1126d..9af0a46817a25f 100644
--- a/clang/unittests/AST/ASTContextParentMapTest.cpp
+++ b/clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -148,5 +148,54 @@ TEST(GetParents, FriendTypeLoc) {
   ElementsAre(DynTypedNode::create(FrA)));
 }
 
+TEST(GetParents, UserDefinedTupleLikeTypes) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(Verifier.match(
+  R"(
+namespace std {
+
+using size_t = __typeof(sizeof(int));
+
+template 
+struct tuple_size;
+
+template 
+struct tuple_size : tuple_size{};
+
+template 
+requires requires { tuple_size::value; }
+struct tuple_size : tuple_size{};
+
+
+template
+struct tuple_element;
+
+
+}  // namespace std
+
+struct Decomposable {};
+
+template<> struct std::tuple_size {
+  static constexpr size_t value = 2;
+};
+
+template struct std::tuple_element {
+  using type = int;
+};
+
+template struct std::tuple_element {
+  using type = const int;
+};
+
+template
+const int& get(const Decomposable& d);
+
+void F(const Decomposable& d) {
+const auto& [x, y] = d;
+}
+)",
+  varDecl(hasName("x"), hasAncestor(decompositionDecl())), Lang_CXX20));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 39e7001393e5e9..e10e4611ab8c60 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -143,6 +143,15 @@ const Formula &getFormula(const ValueDecl &D, const 
Environment &Env) {
   return cast(Env.getValue(D))->formula();
 }
 
+const BindingDecl *findBindingDecl(const char *Name, ASTContext &ASTCtx) {
+  using ast_matchers::bindingDecl;
+  using ast_matchers::hasName;
+  auto TargetNodes =
+  ast_matchers::match(bindingDecl(hasName(Name)).bind("v"), ASTCtx);
+  assert(TargetNodes.size() == 1 && "Name must be unique");
+  return ast_matchers::selectFirst("v", TargetNodes);
+}
+
 TEST(TransferTest, CNotSupported) {
   TestInputs Inputs("void target() {}");
   Inputs.Language = TestLanguage::Lang_C89;
@@ -5515,10 +5524,10 @@ TEST(TransferTest, 
StructuredBindingAssignFromTupleLikeType) {
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
 
-const ValueDecl *BoundFooDecl = findValueDecl(ASTCtx, "BoundFoo");
+const ValueDecl *BoundFooDecl = findBindingDecl("BoundFoo", ASTCtx);
 ASSERT_THAT(BoundFooDecl, NotNull());
 
-const ValueDecl *BoundBarDecl = findValueDecl(ASTCtx, "BoundBar");
+const ValueDecl *BoundBarDecl = findBindingDecl("BoundBar", ASTCtx);
 ASSERT_THAT(BoundBarDecl, NotNull());
 
 const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
@@ -5596,10 +5605,10 @@ TEST(TransferTest, 
StructuredBindingAssignRefFromTupleLikeType) {
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
 
-const ValueDecl *BoundFooDecl = findValueDecl(ASTCtx, "BoundFoo");
+const ValueDecl *BoundFooDecl = findBindingDecl("BoundFoo", ASTCtx);
 ASSERT_THAT(BoundFooDecl, NotNull());
 
-const

[clang] [Clang] Add fake use emission to Clang with -fextend-lifetimes (PR #110102)

2024-12-12 Thread Stephen Tozer via cfe-commits

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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Shilei Tian via cfe-commits


@@ -0,0 +1,11 @@
+// REQUIRES: asserts
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 
-disable-llvm-passes -fopenmp-targets=amdgcn-amd-amdhsa -x c++ -emit-llvm-bc %s 
-o %t-x86-host.bc
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple 
x86_64-unknown-linux-gnu -target-cpu gfx906 -fopenmp -nogpulib 
-fopenmp-is-target-device -fopenmp-host-ir-file-path %t-x86-host.bc -x c++ %s
+
+// Don't crash with assertions build.
+int MyGlobVar;
+#pragma omp threadprivate(MyGlobVar)

shiltian wrote:

This should not crash for sure, but I wonder is this a valid use of OpenMP? I 
don't know what I should expect from this semantics.

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


[clang] [Clang] Add fake use emission to Clang with -fextend-lifetimes (PR #110102)

2024-12-12 Thread Stephen Tozer via cfe-commits

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


[clang] [clang-cl] Don't add implicit NoBuiltinAttr to deleted or defaulted functions (#116256) (PR #119719)

2024-12-12 Thread via cfe-commits

cor3ntin wrote:

Can you edit the description to explain the reason for that change? Thanks

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


[clang] 6edd867 - [SystemZ][z/OS] Replace assert with updated return statement to check if a file size will grow due to conversion

2024-12-12 Thread Abhina Sreeskantharajan via cfe-commits

Author: Abhina Sreeskantharajan
Date: 2024-12-12T11:56:08-05:00
New Revision: 6edd867e43cb5eb3bb84561c0490e5ebb9d06d90

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

LOG: [SystemZ][z/OS] Replace assert with updated return statement to check if a 
file size will grow due to conversion

Added: 


Modified: 
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 849c18f171f6e1..44e982d3ee67fb 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -592,8 +592,7 @@ bool needConversion(StringRef Filename) {
 #ifdef __MVS__
   llvm::ErrorOr NeedConversion =
   llvm::needzOSConversion(Filename.str().c_str());
-  assert(NeedConversion && "Filename was not found");
-  return *NeedConversion;
+  return NeedConversion && *NeedConversion;
 #else
   return false;
 #endif



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


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

2024-12-12 Thread via cfe-commits

SunilKuravinakop wrote:

I ran `./install/bin/clang-tidy -p=build clang/lib/Sema/SemaOpenMP.cpp 
-checks=llvm-*` and did not find any changes being suggested for the code 
changes which I have done. Is there any other tool other than clang-tidy which 
I can run before uploading? I have been using git-clang-format for quite 
sometime now. 

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


[clang] [llvm] [OpenMP]Initial parsing/sema support for target_device selector set (PR #118471)

2024-12-12 Thread via cfe-commits


@@ -15629,6 +15629,34 @@ ExprResult 
SemaOpenMP::VerifyPositiveIntegerConstantInClause(
   return ICE;
 }
 
+void SemaOpenMP::ActOnOpenMPDeviceNum(Expr *DeviceNumExpr) {
+  llvm::APSInt Result;
+  Expr::EvalResult EvalResult;
+  // Strip implicit casts from the expression
+  DeviceNumExpr = DeviceNumExpr->IgnoreImpCasts();

Ritanya-B-Bharadwaj wrote:

I was unsure whether `EvaluateAsInt` could fetch the value from the expression 
containing implicit casts as the control kept ending up in the else case.

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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,11 @@
+// REQUIRES: asserts

arsenm wrote:

This does not require asserts 

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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,11 @@
+// REQUIRES: asserts
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 
-disable-llvm-passes -fopenmp-targets=amdgcn-amd-amdhsa -x c++ -emit-llvm-bc %s 
-o %t-x86-host.bc
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple 
x86_64-unknown-linux-gnu -target-cpu gfx906 -fopenmp -nogpulib 
-fopenmp-is-target-device -fopenmp-host-ir-file-path %t-x86-host.bc -x c++ %s
+
+// Don't crash with assertions build.

arsenm wrote:

Needs output checks 

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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Matt Arsenault via cfe-commits


@@ -3302,6 +3302,9 @@ void ItaniumCXXABI::EmitThreadLocalInitFuncs(
   CharUnits Align = CGM.getContext().getDeclAlign(VD);
   Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
 }
+if (Val->getType() != Wrapper->getReturnType()) {
+  Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
+}

arsenm wrote:

Don't think you need the condition, CreateAddrSpaceCast should be a no-op if 
the types match 

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


[clang] [lldb] [Serialization] Support loading template specializations lazily (PR #119333)

2024-12-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

@ChuanqiXu9 the added test fails under ASAN that reports memory leaks:

```
$ cmake -G Ninja -DLLVM_USE_SANITIZER=Address -DCMAKE_CXX_COMPILER=clang 
-DCMAKE_C_COMPILER=clang ../
$ ninja SerializationTests
$ ./tools/clang/unittests/Serialization/SerializationTests
```

produces
```
==4100640==ERROR: LeakSanitizer: detected memory leaks

Indirect leak of 32776 byte(s) in 1 object(s) allocated from:
#0 0x559f90ba330c in calloc 
(/usr/local/google/home/ibiryukov/code/llvm-project/build-asan/tools/clang/unittests/Serialization/SerializationTests+0x174d30c)
 (BuildId: 4baf7bfc387b0be3)
#1 0x559f910585eb in safe_calloc 
/usr/local/google/home/ibiryukov/code/llvm-project/llvm/include/llvm/Support/MemAlloc.h:40:18
#2 0x559f910585eb in AllocateBuckets 
/usr/local/google/home/ibiryukov/code/llvm-project/llvm/lib/Support/FoldingSet.cpp:173:40
#3 0x559f910585eb in llvm::FoldingSetBase::FoldingSetBase(unsigned int) 
/usr/local/google/home/ibiryukov/code/llvm-project/llvm/lib/Support/FoldingSet.cpp:187:13
#4 0x559f90f34503 in FoldingSetImpl 
/usr/local/google/home/ibiryukov/code/llvm-project/llvm/include/llvm/ADT/FoldingSet.h:454:9
#5 0x559f90f34503 in ContextualFoldingSet 
/usr/local/google/home/ibiryukov/code/llvm-project/llvm/include/llvm/ADT/FoldingSet.h:636:9
#6 0x559f90f34503 in clang::ASTContext::ASTContext(clang::LangOptions&, 
clang::SourceManager&, clang::IdentifierTable&, clang::SelectorTable&, 
clang::Builtin::Context&, clang::TranslationUnitKind) 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/lib/AST/ASTContext.cpp:920:7
#7 0x559f92667204 in clang::CompilerInstance::createASTContext() 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/lib/Frontend/CompilerInstance.cpp:553:23
#8 0x559f928ad79a in 
clang::FrontendAction::BeginSourceFile(clang::CompilerInstance&, 
clang::FrontendInputFile const&) 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/lib/Frontend/FrontendAction.cpp:948:10
#9 0x559f9266fb7d in 
clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/lib/Frontend/CompilerInstance.cpp:1061:13
#10 0x559f90c13901 in (anonymous 
namespace)::LoadSpecLazilyTest::GenerateModuleInterface[abi:cxx11](llvm::StringRef,
 llvm::StringRef) 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/unittests/Serialization/LoadSpecLazilyTest.cpp:86:5
#11 0x559f90c18b8b in (anonymous 
namespace)::LoadSpecLazilyTest_ChainedTest2_Test::TestBody() 
/usr/local/google/home/ibiryukov/code/llvm-project/clang/unittests/Serialization/LoadSpecLazilyTest.cpp:227:3
#12 0x559f90e46395 in HandleExceptionsInMethodIfSupported 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc
#13 0x559f90e46395 in testing::Test::Run() 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc:2687:5
#14 0x559f90e48ae2 in testing::TestInfo::Run() 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc:2836:11
#15 0x559f90e4ad74 in testing::TestSuite::Run() 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc:3015:30
#16 0x559f90e82ee8 in testing::internal::UnitTestImpl::RunAllTests() 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc:5920:44
#17 0x559f90e811c7 in 
HandleExceptionsInMethodIfSupported 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc
#18 0x559f90e811c7 in testing::UnitTest::Run() 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/src/gtest.cc:5484:10
#19 0x559f90e08bfa in RUN_ALL_TESTS 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/googletest/include/gtest/gtest.h:2317:73
#20 0x559f90e08bfa in main 
/usr/local/google/home/ibiryukov/code/llvm-project/third-party/unittest/UnitTestMain/TestMain.cpp:55:10
#21 0x7f0546213c89 in __libc_start_call_main 
csu/../sysdeps/nptl/libc_start_call_main.h:58:16
...
SUMMARY: AddressSanitizer: 488922 byte(s) leaked in 529 allocation(s).
```

Maybe revert the change or is there a simple fix forward?

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


[clang] [clang][bytecode] Handle __builtin_bcmp (PR #119678)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

... the same as `__builtin_memcmp`. Also fix a bug we still had when we 
couldn't find a difference in the two inputs after `Size` bytes.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+29-8) 
- (modified) clang/test/AST/ByteCode/builtin-functions.cpp (+15) 


``diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index a343280b5ce50f..21baedf832eeac 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1917,7 +1917,7 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   const APSInt &Size =
   peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(2)));
 
-  if (ID == Builtin::BImemcmp)
+  if (ID == Builtin::BImemcmp || ID == Builtin::BIbcmp)
 diagnoseNonConstexprBuiltin(S, OpPC, ID);
 
   if (Size.isZero()) {
@@ -1952,15 +1952,34 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
   BufferB.byteSize().getQuantity());
   size_t CmpSize =
   std::min(MinBufferSize, static_cast(Size.getZExtValue()));
-  int Result = std::memcmp(BufferA.Data.get(), BufferB.Data.get(), CmpSize);
-  if (Result == 0)
+
+  for (size_t I = 0; I != CmpSize; ++I) {
+std::byte A = BufferA.Data[I];
+std::byte B = BufferB.Data[I];
+
+if (A < B) {
+  pushInteger(S, -1, Call->getType());
+  return true;
+} else if (A > B) {
+  pushInteger(S, 1, Call->getType());
+  return true;
+}
+  }
+
+  // We compared CmpSize bytes above. If the limiting factor was the Size
+  // passed, we're done and the result is equality (0).
+  if (Size.getZExtValue() <= CmpSize) {
 pushInteger(S, 0, Call->getType());
-  else if (Result < 0)
-pushInteger(S, -1, Call->getType());
-  else
-pushInteger(S, 1, Call->getType());
+return true;
+  }
 
-  return true;
+  // However, if we read all the available bytes but were instructed to read
+  // even more, diagnose this as a "read of dereferenced one-past-the-end
+  // pointer". This is what would happen if we called CheckRead() on every 
array
+  // element.
+  S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
+  << AK_Read << S.Current->getRange(OpPC);
+  return false;
 }
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
@@ -2438,6 +2457,8 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
 
   case Builtin::BI__builtin_memcmp:
   case Builtin::BImemcmp:
+  case Builtin::BI__builtin_bcmp:
+  case Builtin::BIbcmp:
 if (!interp__builtin_memcmp(S, OpPC, Frame, F, Call))
   return false;
 break;
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp 
b/clang/test/AST/ByteCode/builtin-functions.cpp
index 83caa1d03df3a3..4ee24646286fa8 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -1255,4 +1255,19 @@ namespace Memcmp {
   // both-note 
{{not supported}}
   static_assert(__builtin_memcmp("", &incomplete, 1u) == 42); // both-error 
{{not an integral constant}} \
   // both-note 
{{not supported}}
+
+  static_assert(__builtin_memcmp(u8"abab\0banana", u8"abab\0banana", 100) == 
0); // both-error {{not an integral constant}} \
+   
  // both-note {{dereferenced one-past-the-end}}
+
+  static_assert(__builtin_bcmp("abaa", "abba", 3) != 0);
+  static_assert(__builtin_bcmp("abaa", "abba", 2) == 0);
+  static_assert(__builtin_bcmp("a\203", "a", 2) != 0);
+  static_assert(__builtin_bcmp("a\203", "a\003", 2) != 0);
+  static_assert(__builtin_bcmp(0, 0, 0) == 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0banana", 100) == 0); // 
both-error {{not an integral constant}}\
+   // 
both-note {{dereferenced one-past-the-end}}
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 100) != 0); // 
FIXME: Should we reject this?
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 7) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 6) != 0);
+  static_assert(__builtin_bcmp("abab\0banana", "abab\0canada", 5) == 0);
 }

``




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


[clang] [clang][LoongArch] Add FreeBSD targets (PR #119191)

2024-12-12 Thread WÁNG Xuěruì via cfe-commits

xen0n wrote:

> > Also a `[Clang]` tag could be prepended to the PR title to make it clearer 
> > what part gets changed.
> 
> Not only clang, all of FreeBSD on LoongArch

It's not about *what can get built after the change*, but *what part of LLVM 
project this change applies to*, which is Clang. Look at the diff -- all 
touched files reside in `clang/` directory, that's it.

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


[clang] [lldb] [Serialization] Support loading template specializations lazily (PR #119333)

2024-12-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

Ah, it's `DisableFree` again. I'll send a fix.

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


[clang] [lldb] [Serialization] Support loading template specializations lazily (PR #119333)

2024-12-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

Fixed by 7f4312015291a32d811a0f37e24b4d9736c524f7.

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


[clang] 7f43120 - [Serialization] Free memory in LoadSpecLazilyTest

2024-12-12 Thread Ilya Biryukov via cfe-commits

Author: Ilya Biryukov
Date: 2024-12-12T11:19:11+01:00
New Revision: 7f4312015291a32d811a0f37e24b4d9736c524f7

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

LOG: [Serialization] Free memory in LoadSpecLazilyTest

Default Clang invocations set DisableFree = true, which causes ASAN to
complain. Override it in tests that are not supposed to leak.

Added: 


Modified: 
clang/unittests/Serialization/LoadSpecLazilyTest.cpp

Removed: 




diff  --git a/clang/unittests/Serialization/LoadSpecLazilyTest.cpp 
b/clang/unittests/Serialization/LoadSpecLazilyTest.cpp
index 0e452652a940d5..7cc074c51fcd03 100644
--- a/clang/unittests/Serialization/LoadSpecLazilyTest.cpp
+++ b/clang/unittests/Serialization/LoadSpecLazilyTest.cpp
@@ -82,6 +82,8 @@ class LoadSpecLazilyTest : public ::testing::Test {
 Instance.setDiagnostics(Diags.get());
 Instance.setInvocation(Invocation);
 Instance.getFrontendOpts().OutputFile = CacheBMIPath;
+// Avoid memory leaks.
+Instance.getFrontendOpts().DisableFree = false;
 GenerateModuleInterfaceAction Action;
 EXPECT_TRUE(Instance.ExecuteAction(Action));
 EXPECT_FALSE(Diags->hasErrorOccurred());



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


[clang] [clang] Enable the -Wdangling-capture diagnostic by default. (PR #119685)

2024-12-12 Thread via cfe-commits

cor3ntin wrote:

Did you benchmark the impact on compile times?

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


[clang] [flang] [flang][Driver] Don't require -fno-integrated-as when using -save-temps (PR #119624)

2024-12-12 Thread Sergio Afonso via cfe-commits

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

Thank you, I think this is a good first step. Eventually, I think we'll still 
have to introduce proper support for `-fc1as`, because `-fno-integrated-as` 
(this patch making it the default for Flang) results in target offload programs 
failing to link.

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


[clang] [llvm] [RISC-V] Add support for MIPS P8700 CPU (PR #117865)

2024-12-12 Thread Guy Blank via cfe-commits


@@ -0,0 +1,371 @@
+//===- RISCVLoadStoreOptimizer.cpp 
===//
+//
+// 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
+//
+//===--===//
+//
+// Bundle loads and stores that operate on consecutive memory locations to take
+// the advantage of hardware load/store bonding.
+//
+//===--===//
+
+#include "RISCV.h"
+#include "RISCVTargetMachine.h"
+#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Target/TargetOptions.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "riscv-load-store-opt"
+#define RISCV_LOAD_STORE_OPT_NAME "RISCV Load / Store Optimizer"
+namespace {
+
+struct RISCVLoadStoreOpt : public MachineFunctionPass {
+  static char ID;
+  bool runOnMachineFunction(MachineFunction &Fn) override;
+
+  RISCVLoadStoreOpt() : MachineFunctionPass(ID) {}
+
+  MachineFunctionProperties getRequiredProperties() const override {
+return MachineFunctionProperties().set(
+MachineFunctionProperties::Property::NoVRegs);
+  }
+
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+AU.addRequired();
+MachineFunctionPass::getAnalysisUsage(AU);
+  }
+
+  StringRef getPassName() const override { return RISCV_LOAD_STORE_OPT_NAME; }
+
+  // Find and pair load/store instructions.
+  bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
+
+  // Convert load/store pairs to single instructions.
+  bool tryConvertToLdStPair(MachineBasicBlock::iterator First,
+MachineBasicBlock::iterator Second);
+
+  // Scan the instructions looking for a load/store that can be combined
+  // with the current instruction into a load/store pair.
+  // Return the matching instruction if one is found, else MBB->end().
+  MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
+   bool &MergeForward);
+
+  MachineBasicBlock::iterator
+  mergePairedInsns(MachineBasicBlock::iterator I,
+   MachineBasicBlock::iterator Paired, bool MergeForward);
+
+private:
+  AliasAnalysis *AA;
+  MachineRegisterInfo *MRI;
+  const RISCVInstrInfo *TII;
+  const RISCVRegisterInfo *TRI;
+  LiveRegUnits ModifiedRegUnits, UsedRegUnits;
+  bool UseLoadStorePair = false;
+};
+} // end anonymous namespace
+
+char RISCVLoadStoreOpt::ID = 0;
+INITIALIZE_PASS(RISCVLoadStoreOpt, DEBUG_TYPE, RISCV_LOAD_STORE_OPT_NAME, 
false,
+false)
+
+bool RISCVLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
+  if (skipFunction(Fn.getFunction()))
+return false;
+  const RISCVSubtarget &Subtarget = Fn.getSubtarget();
+
+  if (!Subtarget.useLoadStorePairs())
+return false;
+
+  bool MadeChange = false;
+  TII = Subtarget.getInstrInfo();
+  TRI = Subtarget.getRegisterInfo();
+  MRI = &Fn.getRegInfo();
+  AA = &getAnalysis().getAAResults();
+  ModifiedRegUnits.init(*TRI);
+  UsedRegUnits.init(*TRI);
+  UseLoadStorePair = Subtarget.useLoadStorePairs();
+
+  for (MachineBasicBlock &MBB : Fn) {
+LLVM_DEBUG(dbgs() << "MBB: " << MBB.getName() << "\n");
+
+for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
+ MBBI != E;) {
+  if (TII->isPairableLdStInstOpc(MBBI->getOpcode()) &&
+  tryToPairLdStInst(MBBI))
+MadeChange = true;
+  else
+++MBBI;
+}
+  }
+  return MadeChange;
+}
+
+// Find loads and stores that can be merged into a single load or store pair
+// instruction.
+bool RISCVLoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
+  MachineInstr &MI = *MBBI;
+  MachineBasicBlock::iterator E = MI.getParent()->end();
+
+  if (!TII->isLdStSafeToPair(MI, TRI))
+return false;
+
+  // Look ahead for a pairable instruction.
+  bool MergeForward;
+  MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, MergeForward);
+  if (Paired != E) {
+MBBI = mergePairedInsns(MBBI, Paired, MergeForward);
+return true;
+  }
+  return false;
+}
+
+bool RISCVLoadStoreOpt::tryConvertToLdStPair(
+MachineBasicBlock::iterator First, MachineBasicBlock::iterator Second) {
+  if (!UseLoadStorePair)
+return false;
+
+  unsigned PairOpc;
+  switch (First->getOpcode()) {
+  default:
+return false;
+  case RISCV::SW:
+PairOpc = RISCV::SWP;
+break;
+  case RISCV::LW:
+PairOpc = RISCV::LWP;
+break;
+  case RISCV::SD:
+PairOpc = RISCV::SDP;
+break;
+  case RISCV::LD:
+PairOpc = RISCV::LDP;
+break;
+  }
+
+  MachineFunction *MF = First->getMF();
+  const MachineMemOperand *MMO = *First->memoperands_begin();
+  Align MMOAlign = MMO->getAlign();
+  if (const PseudoSourceValue *Sour

[clang] [clang][Driver] Fix triple config loading for clang-cl (PR #111397)

2024-12-12 Thread via cfe-commits

https://github.com/zmodem commented:

I didn't even realize people are using config files with clang-cl (since IIRC 
it doesn't support the config file command-line options).

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


[clang] [clang][Driver] Fix triple config loading for clang-cl (PR #111397)

2024-12-12 Thread via cfe-commits


@@ -1336,17 +1359,7 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
 
   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
   // and getToolChain is const.
-  if (IsCLMode()) {
-// clang-cl targets MSVC-style Win32.
-llvm::Triple T(TargetTriple);
-T.setOS(llvm::Triple::Win32);
-T.setVendor(llvm::Triple::PC);
-T.setEnvironment(llvm::Triple::MSVC);
-T.setObjectFormat(llvm::Triple::COFF);
-if (Args.hasArg(options::OPT__SLASH_arm64EC))
-  T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
-TargetTriple = T.str();
-  } else if (IsDXCMode()) {
+  if (IsDXCMode()) {

zmodem wrote:

Doesn't this mode have the same issue?

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


[clang] [clang][Driver] Fix triple config loading for clang-cl (PR #111397)

2024-12-12 Thread via cfe-commits


@@ -1286,6 +1299,16 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   appendOneArg(Args, Opt, nullptr);
 }
 }
+
+// The config file may have changed the architecture so apply it.
+if (HasConfigFile && Args.hasArg(options::OPT__SLASH_arm64EC)) {
+  llvm::Triple T(TargetTriple);
+  if (T.getArch() != llvm::Triple::aarch64 ||
+  T.getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) {
+T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
+TargetTriple = T.str();

zmodem wrote:

The PR description only mentions moving the default triple calculation earlier, 
but not this part.

The config file can presumably change many things, so why does the target 
triple need special handling? Also what about flags that affect x86 vs. x86_64 
(-m32 and -m64), do we need to handle those too?

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


[clang] [clang][Driver] Fix triple config loading for clang-cl (PR #111397)

2024-12-12 Thread via cfe-commits

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


[libclc] [libclc] Optimize ceil/fabs/floor/rint/trunc (PR #119596)

2024-12-12 Thread Fraser Cormack via cfe-commits

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

>From 68df2622a3ca1b98a0cbf1fc9e6200e12fecbb2e Mon Sep 17 00:00:00 2001
From: Fraser Cormack 
Date: Wed, 11 Dec 2024 17:28:38 +
Subject: [PATCH 1/2] [libclc] Optimize ceil/fabs/floor/rint/trunc

These functions all map to the corresponding LLVM intrinsics, but the
vector intrinsics weren't being generated. The intrinsic mapping from
CLC vector function to vector intrinsic was working correctly, but the
mapping from OpenCL builtin to CLC function was suboptimally recursively
splitting vectors in halves.

For example, with this change, `ceil(float16)` calls `llvm.ceil.v16f32`
directly.

The CLC versions of each of these builtins are also now enabled for
SPIR-V targets. The LLVM -> SPIR-V translator maps the intrinsics to the
appropriate OpExtInst. As such, there is no diff to the SPIR-V binaries
before/after this change.

The clspv targets show a difference, but it's not expected to be a
problem:

>   %call = tail call spir_func double @llvm.fabs.f64(double noundef %x) #9
<   %call = tail call spir_func double @_Z4fabsd(double noundef %x) #9

The AMDGPU targets make use of the same _CLC_DEFINE_UNARY_BUILTIN macro
to override sqrt, so those functions also appear more optimal with this
change, calling the vector `llvm.sqrt.vXf32` intrinsics directly.
---
 libclc/clc/include/clc/clcmacro.h   | 16 +++-
 libclc/clc/include/clc/math/clc_ceil.h  |  7 ---
 libclc/clc/include/clc/math/clc_fabs.h  |  7 ---
 libclc/clc/include/clc/math/clc_floor.h |  7 ---
 libclc/clc/include/clc/math/clc_rint.h  |  7 ---
 libclc/clc/include/clc/math/clc_trunc.h |  7 ---
 6 files changed, 15 insertions(+), 36 deletions(-)

diff --git a/libclc/clc/include/clc/clcmacro.h 
b/libclc/clc/include/clc/clcmacro.h
index 244239284ecabc..c6583749eca661 100644
--- a/libclc/clc/include/clc/clcmacro.h
+++ b/libclc/clc/include/clc/clcmacro.h
@@ -191,7 +191,21 @@
 
 #define _CLC_DEFINE_UNARY_BUILTIN(RET_TYPE, FUNCTION, BUILTIN, ARG1_TYPE)  
\
   _CLC_DEF _CLC_OVERLOAD RET_TYPE FUNCTION(ARG1_TYPE x) { return BUILTIN(x); } 
\
-  _CLC_UNARY_VECTORIZE(_CLC_OVERLOAD _CLC_DEF, RET_TYPE, FUNCTION, ARG1_TYPE)
+  _CLC_DEF _CLC_OVERLOAD RET_TYPE##2 FUNCTION(ARG1_TYPE##2 x) {
\
+return BUILTIN(x); 
\
+  }
\
+  _CLC_DEF _CLC_OVERLOAD RET_TYPE##3 FUNCTION(ARG1_TYPE##3 x) {
\
+return BUILTIN(x); 
\
+  }
\
+  _CLC_DEF _CLC_OVERLOAD RET_TYPE##4 FUNCTION(ARG1_TYPE##4 x) {
\
+return BUILTIN(x); 
\
+  }
\
+  _CLC_DEF _CLC_OVERLOAD RET_TYPE##8 FUNCTION(ARG1_TYPE##8 x) {
\
+return BUILTIN(x); 
\
+  }
\
+  _CLC_DEF _CLC_OVERLOAD RET_TYPE##16 FUNCTION(ARG1_TYPE##16 x) {  
\
+return BUILTIN(x); 
\
+  }
 
 #ifdef cl_khr_fp16
 
diff --git a/libclc/clc/include/clc/math/clc_ceil.h 
b/libclc/clc/include/clc/math/clc_ceil.h
index 66590687c34220..905aef37e11c66 100644
--- a/libclc/clc/include/clc/math/clc_ceil.h
+++ b/libclc/clc/include/clc/math/clc_ceil.h
@@ -1,11 +1,6 @@
 #ifndef __CLC_MATH_CLC_CEIL_H__
 #define __CLC_MATH_CLC_CEIL_H__
 
-#if defined(CLC_CLSPV) || defined(CLC_SPIRV)
-// clspv and spir-v targets provide their own OpenCL-compatible ceil
-#define __clc_ceil ceil
-#else
-
 // Map the function to an LLVM intrinsic
 #define __CLC_FUNCTION __clc_ceil
 #define __CLC_INTRINSIC "llvm.ceil"
@@ -14,6 +9,4 @@
 #undef __CLC_INTRINSIC
 #undef __CLC_FUNCTION
 
-#endif
-
 #endif // __CLC_MATH_CLC_CEIL_H__
diff --git a/libclc/clc/include/clc/math/clc_fabs.h 
b/libclc/clc/include/clc/math/clc_fabs.h
index 93367b57313713..525577ab98a389 100644
--- a/libclc/clc/include/clc/math/clc_fabs.h
+++ b/libclc/clc/include/clc/math/clc_fabs.h
@@ -1,11 +1,6 @@
 #ifndef __CLC_MATH_CLC_FABS_H__
 #define __CLC_MATH_CLC_FABS_H__
 
-#if defined(CLC_CLSPV) || defined(CLC_SPIRV)
-// clspv and spir-v targets provide their own OpenCL-compatible fabs
-#define __clc_fabs fabs
-#else
-
 // Map the function to an LLVM intrinsic
 #define __CLC_FUNCTION __clc_fabs
 #define __CLC_INTRINSIC "llvm.fabs"
@@ -14,6 +9,4 @@
 #undef __CLC_INTRINSIC
 #undef __CLC_FUNCTION
 
-#endif
-
 #endif // __CLC_MATH_CLC_FABS_H__
diff --git a/libclc/clc/include/clc/math/clc_floor.h 
b/libclc/clc/include/clc/math/clc_floor.h
index 9919872ec633c6..e2d9dbadb434db 100644
--- a/libclc/clc/include/clc/math/clc_floor.h
+++ b/libc

[clang-tools-extra] [clang-tidy][NFC][doc] clean out-dated clang-static-analyzer checks (PR #119580)

2024-12-12 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/119580

>From df8b95c76ef3b5be61b5cea6476eba80bcd16792 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 12 Dec 2024 00:20:01 +0800
Subject: [PATCH 1/3] [clang-tidy][NFC][doc] clean out-dated
 clang-static-analyzer checks

---
 .../clang-analyzer/cplusplus.PureVirtualCall.rst|  9 -
 .../clang-analyzer/cplusplus.SelfAssignment.rst | 13 +
 clang-tools-extra/docs/clang-tidy/checks/list.rst   | 13 +++--
 3 files changed, 16 insertions(+), 19 deletions(-)
 delete mode 100644 
clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.PureVirtualCall.rst
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.SelfAssignment.rst

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.PureVirtualCall.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.PureVirtualCall.rst
deleted file mode 100644
index 9fab628b80d443..00
--- 
a/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.PureVirtualCall.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-.. title:: clang-tidy - clang-analyzer-cplusplus.PureVirtualCall
-
-clang-analyzer-cplusplus.PureVirtualCall
-
-
-Check pure virtual function calls during construction/destruction.
-
-The clang-analyzer-cplusplus.PureVirtualCall check is an alias of
-Clang Static Analyzer cplusplus.PureVirtualCall.
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.SelfAssignment.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.SelfAssignment.rst
new file mode 100644
index 00..8e0deb4820d105
--- /dev/null
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/clang-analyzer/cplusplus.SelfAssignment.rst
@@ -0,0 +1,13 @@
+.. title:: clang-tidy - clang-analyzer-cplusplus.SelfAssignment
+.. meta::
+   :http-equiv=refresh: 
5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-selfassignment
+
+clang-analyzer-cplusplus.SelfAssignment
+==
+
+Checks C++ copy and move assignment operators for self assignment.
+
+The `clang-analyzer-cplusplus.SelfAssignment` check is an alias, please see
+`Clang Static Analyzer Available Checkers
+`_
+for more information.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index d731b13fc0df44..d9e9cb67ef7a0b 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -458,7 +458,7 @@ Check aliases
:doc:`clang-analyzer-cplusplus.NewDelete 
`, `Clang Static Analyzer 
cplusplus.NewDelete 
`_,
:doc:`clang-analyzer-cplusplus.NewDeleteLeaks 
`, `Clang Static Analyzer 
cplusplus.NewDeleteLeaks 
`_,
:doc:`clang-analyzer-cplusplus.PlacementNew 
`, `Clang Static Analyzer 
cplusplus.PlacementNew 
`_,
-   :doc:`clang-analyzer-cplusplus.PureVirtualCall 
`, Clang Static Analyzer 
cplusplus.PureVirtualCall,
+   :doc:`clang-analyzer-cplusplus.SelfAssignment 
`, `Clang Static Analyzer 
cplusplus.SelfAssignment 
`_,
:doc:`clang-analyzer-cplusplus.StringChecker 
`, `Clang Static Analyzer 
cplusplus.StringChecker 
`_,
:doc:`clang-analyzer-deadcode.DeadStores 
`, `Clang Static Analyzer 
deadcode.DeadStores 
`_,
:doc:`clang-analyzer-fuchsia.HandleChecker 
`, `Clang Static Analyzer 
fuchsia.HandleChecker 
`_,
@@ -471,7 +471,6 @@ Check aliases
:doc:`clang-analyzer-optin.cplusplus.UninitializedObject 
`, `Clang Static Analyzer 
optin.cplusplus.UninitializedObject 
`_,
:doc:`clang-analyzer-optin.cplusplus.VirtualCall 
`, `Clang Static Analyzer 
optin.cplusplus.VirtualCall 
`_,
:doc:`clang-analyzer-optin.mpi.MPI-Checker 
`, `Clang Static Analyzer 
optin.mpi.MPI-Checker 
`_,
-   :doc:`clang-analyzer-optin.osx.OSObjectCStyleCast 
`, Clang Static Analyzer 
optin.osx.OSObjectCStyleCast,

:doc:`clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
 
`,
 `Clang Static Analyzer 
optin.osx.cocoa.localizability.EmptyLocalization

[clang] [Clang] Add "extend lifetime" flags and release note (PR #110000)

2024-12-12 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer updated 
https://github.com/llvm/llvm-project/pull/11

>From 6a873f5c487a936344f6cd226b7d525b406f34b2 Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Wed, 25 Sep 2024 15:08:39 +0100
Subject: [PATCH 1/6] [Clang] Add "extend lifetime" flags and release note

Following the commit that added the fake use intrinsic to LLVM, this patch
adds a pair of flags for the clang frontend that emit fake use intrinsics,
for the purpose of extending the lifetime of variables (either all source
variables, or just the `this` pointer). This patch does not implement the
fake use intrinsic emission of the flags themselves, it simply adds the flags,
the corresponding release note, and the attachment of the `has_fake_uses`
attribute to affected functions; the remaining functionality appears in the
next patch.
---
 clang/docs/ReleaseNotes.rst   | 10 ++
 clang/include/clang/Basic/CodeGenOptions.def  |  6 ++
 clang/include/clang/Driver/Options.td |  9 +
 clang/lib/CodeGen/CGCall.cpp  |  4 
 clang/lib/Driver/ToolChains/Clang.cpp |  5 +
 clang/lib/Frontend/CompilerInvocation.cpp |  5 +
 clang/test/CodeGen/extend-lifetimes-hasfakeuses.c | 12 
 7 files changed, 51 insertions(+)
 create mode 100644 clang/test/CodeGen/extend-lifetimes-hasfakeuses.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 601a233b81904f..f88fcef9bdade7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -412,6 +412,16 @@ New Compiler Flags
   only for thread-local variables, and none (which corresponds to the
   existing ``-fno-c++-static-destructors`` flag) skips all static
   destructors registration.
+- The ``-fextend-lifetimes`` and ``-fextend-this-ptr`` flags have been added to
+  allow for improved debugging of optimized code. Using ``-fextend-lifetimes``
+  will cause Clang to generate code that tries to preserve the lifetimes of
+  source variables, meaning that variables will typically be visible in a
+  debugger more often. The ``-fextend-this-ptr`` flag has the same behaviour,
+  but applies only to the ``this`` variable in C++ class member functions. Note
+  that this flag modifies the optimizations that Clang performs, which will
+  result in reduced performance in generated code; however, this feature will
+  not extend the lifetime of some variables in cases where doing so would have
+  too severe an impact on generated code performance.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 4cf22c4ee08ce0..2f155f7df49a3a 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -393,6 +393,12 @@ CODEGENOPT(EnableTLSDESC, 1, 0)
 /// Bit size of immediate TLS offsets (0 == use the default).
 VALUE_CODEGENOPT(TLSSize, 8, 0)
 
+/// Whether to extend the live range of the `this` pointer.
+CODEGENOPT(ExtendThisPtr, 1, 0)
+
+/// Whether to extend the live ranges of all local variables.
+CODEGENOPT(ExtendLifetimes, 1, 0)
+
 /// The default stack protector guard offset to use.
 VALUE_CODEGENOPT(StackProtectorGuardOffset, 32, INT_MAX)
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9c356c9d2ea4ef..b2e22c9cb6bd95 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4298,6 +4298,15 @@ def stack_usage_file : Separate<["-"], 
"stack-usage-file">,
   Visibility<[CC1Option]>,
   HelpText<"Filename (or -) to write stack usage output to">,
   MarshallingInfoString>;
+def fextend_this_ptr : Flag <["-"], "fextend-this-ptr">, Group,
+  MarshallingInfoFlag>,
+  HelpText<"Extend the lifetime of the 'this' pointer to improve visibility "
+   "in optimized debugging">, Visibility<[ClangOption, CC1Option]>;
+def fextend_lifetimes : Flag <["-"], "fextend-lifetimes">, Group,
+  MarshallingInfoFlag>,
+  HelpText<"Extend the lifetimes of local variables and parameters to improve "
+   "visibility in optimized debugging">,
+   Visibility<[ClangOption, CC1Option]>;
 
 defm unique_basic_block_section_names : 
BoolFOption<"unique-basic-block-section-names",
   CodeGenOpts<"UniqueBasicBlockSectionNames">, DefaultFalse,
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 20455dbb820914..41195953c9a221 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2567,6 +2567,10 @@ void CodeGenModule::ConstructAttributeList(StringRef 
Name,
 if (shouldDisableTailCalls())
   FuncAttrs.addAttribute("disable-tail-calls", "true");
 
+// Mark the function as having fake uses when -fextend-lifetimes is on.
+if (CodeGenOpts.ExtendLifetimes || CodeGenOpts.ExtendThisPtr)
+  FuncAttrs.addAttribute(llvm::Attribute::HasFakeUses);
+
 // CP

[clang] [clang][Driver] Support simplified triple versions for config files (PR #111387)

2024-12-12 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-libc-amdgpu-runtime` running on `omp-vega20-1` while building 
`clang` at step 7 "Add check check-offload".

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


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

```
Step 7 (Add check check-offload) failure: test (failure)
 TEST 'libomptarget :: amdgcn-amd-amdhsa :: 
sanitizer/kernel_crash_async.c' FAILED 
Exit Code: 1

Command Output (stdout):
--
# RUN: at line 2
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test 
-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib
  -fopenmp-targets=amdgcn-amd-amdhsa -O3 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 -o 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 -Xoffload-linker -lc -Xoffload-linker -lm 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp -I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test 
-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib
 -fopenmp-targets=amdgcn-amd-amdhsa -O3 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 -o 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 -Xoffload-linker -lc -Xoffload-linker -lm 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# RUN: at line 3
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/not 
--crash env -u LLVM_DISABLE_SYMBOLIZATION 
OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 2>&1 | 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/FileCheck
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=TRACE
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/not 
--crash env -u LLVM_DISABLE_SYMBOLIZATION 
OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES=1 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/FileCheck
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=TRACE
# RUN: at line 4
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/not 
--crash 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/sanitizer/Output/kernel_crash_async.c.tmp
 2>&1 | 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/FileCheck
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/sanitizer/kernel_crash_async.c
 --check-prefixes=C

[clang] [Clang] Enable -fextend-lifetimes at -Og (PR #118026)

2024-12-12 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer updated 
https://github.com/llvm/llvm-project/pull/118026

>From efd7f58e421b0afdc886688128f72170e0c4a970 Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Wed, 25 Sep 2024 15:08:39 +0100
Subject: [PATCH 1/2] [Clang] Add "extend lifetime" flags and release note

Following the commit that added the fake use intrinsic to LLVM, this patch
adds a pair of flags for the clang frontend that emit fake use intrinsics,
for the purpose of extending the lifetime of variables (either all source
variables, or just the `this` pointer). This patch does not implement the
fake use intrinsic emission of the flags themselves, it simply adds the flags,
the corresponding release note, and the attachment of the `has_fake_uses`
attribute to affected functions; the remaining functionality appears in the
next patch.
---
 clang/docs/ReleaseNotes.rst  | 14 ++
 clang/include/clang/Basic/CodeGenOptions.def |  3 +++
 clang/include/clang/Basic/CodeGenOptions.h   |  6 ++
 clang/include/clang/Driver/Options.td| 20 
 clang/lib/Driver/ToolChains/Clang.cpp|  2 ++
 clang/test/Driver/extend-variable-liveness.c | 15 +++
 6 files changed, 60 insertions(+)
 create mode 100644 clang/test/Driver/extend-variable-liveness.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 601a233b81904f..19a40d4666c727 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -412,6 +412,20 @@ New Compiler Flags
   only for thread-local variables, and none (which corresponds to the
   existing ``-fno-c++-static-destructors`` flag) skips all static
   destructors registration.
+- The ``-fextend-variable-liveness`` flag has been added to allow for improved
+  debugging of optimized code. Using ``-fextend-variable-liveness`` will cause
+  Clang to generate code that tries to preserve the liveness of source 
variables
+  through optimizations, meaning that variables will typically be visible in a
+  debugger more often. The flag has two levels: ``-fextend-variable-liveness``,
+  or ``-fextend-variable-liveness=all``, extendes the liveness of all user
+  variables and the ``this`` pointer. Alternatively ``-fextend-this-ptr``, or
+  ``-fextend-variable-liveness=this``, has the same behaviour but applies only
+  to the ``this`` variable in C++ class member functions, meaning its effect is
+  a strict subset of ``-fextend-variable-liveness``. Note that this flag
+  modifies the results of optimizations that Clang performs, which will result
+  in reduced performance in generated code; however, this feature will not
+  extend the liveness of some variables in cases where doing so would likely
+  have a severe impact on generated code performance.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 4cf22c4ee08ce0..8d181c96bc9641 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -393,6 +393,9 @@ CODEGENOPT(EnableTLSDESC, 1, 0)
 /// Bit size of immediate TLS offsets (0 == use the default).
 VALUE_CODEGENOPT(TLSSize, 8, 0)
 
+/// The types of variables that we will extend the live ranges of.
+ENUM_CODEGENOPT(ExtendVariableLiveness, ExtendVariableLivenessKind, 2, 
ExtendVariableLivenessKind::None)
+
 /// The default stack protector guard offset to use.
 VALUE_CODEGENOPT(StackProtectorGuardOffset, 32, INT_MAX)
 
diff --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index 2dcf98b465661e..f55d9513443e8c 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -95,6 +95,12 @@ class CodeGenOptions : public CodeGenOptionsBase {
 Embed_Marker// Embed a marker as a placeholder for bitcode.
   };
 
+  enum class ExtendVariableLivenessKind {
+None,
+This,
+All,
+  };
+
   enum InlineAsmDialectKind {
 IAD_ATT,
 IAD_Intel,
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9c356c9d2ea4ef..bd9e5407d3843b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4298,6 +4298,26 @@ def stack_usage_file : Separate<["-"], 
"stack-usage-file">,
   Visibility<[CC1Option]>,
   HelpText<"Filename (or -) to write stack usage output to">,
   MarshallingInfoString>;
+def fextend_variable_liveness_EQ : Joined<["-"], "fextend-variable-liveness=">,
+  Group, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Extend the liveness of user variables through optimizations to "
+   "prevent stale or optimized-out variable values when debugging. Can 
"
+   "be applied to all user variables, or just to the C++ 'this' ptr. "
+   "May choose not to extend the liveness of some variables, such as "
+   "non-scalars larger than 4 unsigned ints, or 

[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Sergei Barannikov via cfe-commits

s-barannikov wrote:

> Updating the wrapper function's return type as below also fixes the error:

I mean, why do we have to watch for type mismatches and fix them instead of 
creating the correct type in the first place?
There is `getPointerType(RetQT)` just above, shouldn't it be something like 
`getPointerType(RetQT, )`?
Or RetQT should have had the correct address space, but for some reason it was 
lost?



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


[clang] [Clang] Enable -fextend-lifetimes at -Og (PR #118026)

2024-12-12 Thread Stephen Tozer via cfe-commits


@@ -1834,6 +1834,14 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions 
&Opts, ArgList &Args,
 Opts.setInlining(CodeGenOptions::NormalInlining);
   }
 
+  // If we have specified -Og and have not explicitly set 
-fno-extend-lifetimes,
+  // then default to -fextend-lifetimes.
+  if (Arg *A = Args.getLastArg(options::OPT_O_Group);
+  A && A->containsValue("g")) {

SLTozer wrote:

I've moved this behaviour to the driver now. Also regarding the first request 
to use `A->getValue() == "g"` - if just `-O` is passed then `A->getValue()` 
will crash, as there are no values. An alternative would be to change the check 
to `A->getNumValues() && A->getValue() == "g"`, but I think `containsValue` is 
more concise.

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


[clang] f229ea2 - [clang] Enable the -Wdangling-capture diagnostic by default. (#119685)

2024-12-12 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-12-12T16:38:17+01:00
New Revision: f229ea2ffe9bb8380a4285bd379736aaadaf55ac

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

LOG: [clang] Enable the -Wdangling-capture diagnostic by default. (#119685)

We have tested this diagnostics internally, and we don't find see any
issues.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ae57b84f9247c4..26fa986810a4b8 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -666,6 +666,15 @@ Improvements to Clang's diagnostics
   bool operator==(const C&) = default;
 };
 
+- Clang now emits `-Wdangling-capture` diangostic when a STL container 
captures a dangling reference.
+
+  .. code-block:: c++
+
+void test() {
+  std::vector views;
+  views.push_back(std::string("123")); // warning
+}
+
 Improvements to Clang's time-trace
 --
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0a245e2077f68f..811265151fa0da 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10237,10 +10237,10 @@ def warn_dangling_pointer_assignment : Warning<
InGroup;
 def warn_dangling_reference_captured : Warning<
"object whose reference is captured by '%0' will be destroyed at the end of 
"
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 def warn_dangling_reference_captured_by_unknown : Warning<
"object whose reference is captured will be destroyed at the end of "
-   "the full-expression">, InGroup, DefaultIgnore;
+   "the full-expression">, InGroup;
 
 // For non-floating point, expressions of the form x == x or x != x
 // should result in a warning, since these always evaluate to a constant.



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


[clang] [llvm] [OpenMP]Initial parsing/sema support for target_device selector set (PR #118471)

2024-12-12 Thread via cfe-commits

https://github.com/Ritanya-B-Bharadwaj updated 
https://github.com/llvm/llvm-project/pull/118471

>From cb3bfb497c6f65bc185dc4fe7b8d9c5dbd92c4f0 Mon Sep 17 00:00:00 2001
From: Ritanya B Bharadwaj 
Date: Tue, 3 Dec 2024 03:58:40 -0600
Subject: [PATCH] Initial parsing/sema support for target_device selector set

---
 clang/include/clang/Sema/SemaOpenMP.h |   3 +
 clang/lib/AST/OpenMPClause.cpp|   5 +-
 clang/lib/Parse/ParseOpenMP.cpp   |  27 ++-
 clang/lib/Sema/SemaOpenMP.cpp |  29 +++
 .../OpenMP/begin_declare_variant_messages.c   |  22 +-
 clang/test/OpenMP/declare_variant_ast_print.c |   4 +
 .../OpenMP/declare_variant_bind_to_decl.cpp   |   2 +-
 clang/test/OpenMP/declare_variant_messages.c  |  57 +++---
 .../test/OpenMP/declare_variant_messages.cpp  |  28 +--
 clang/test/OpenMP/metadirective_messages.cpp  |   2 +-
 .../nvptx_declare_variant_name_mangling.cpp   |   8 +-
 .../include/llvm/Frontend/OpenMP/OMPContext.h |   9 +-
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |  36 
 llvm/lib/Frontend/OpenMP/OMPContext.cpp   | 192 +-
 llvm/unittests/Frontend/OpenMPContextTest.cpp |  26 ++-
 15 files changed, 320 insertions(+), 130 deletions(-)

diff --git a/clang/include/clang/Sema/SemaOpenMP.h 
b/clang/include/clang/Sema/SemaOpenMP.h
index 3d1cc4fab1c10f..4b9c930db26b5d 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -849,6 +849,9 @@ class SemaOpenMP : public SemaBase {
   ArrayRef AppendArgs, SourceLocation AdjustArgsLoc,
   SourceLocation AppendArgsLoc, SourceRange SR);
 
+  /// Handle device_num selector.
+  void ActOnOpenMPDeviceNum(Expr *DeviceNumExpr);
+
   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  SourceLocation StartLoc,
  SourceLocation LParenLoc,
diff --git a/clang/lib/AST/OpenMPClause.cpp b/clang/lib/AST/OpenMPClause.cpp
index 4246ba95d827f1..870c4224c323bd 100644
--- a/clang/lib/AST/OpenMPClause.cpp
+++ b/clang/lib/AST/OpenMPClause.cpp
@@ -2903,7 +2903,10 @@ TargetOMPContext::TargetOMPContext(
 const FunctionDecl *CurrentFunctionDecl,
 ArrayRef ConstructTraits)
 : OMPContext(ASTCtx.getLangOpts().OpenMPIsTargetDevice,
- ASTCtx.getTargetInfo().getTriple()),
+ ASTCtx.getTargetInfo().getTriple(),
+ ASTCtx.getLangOpts().OMPTargetTriples.empty()
+ ? llvm::Triple()
+ : ASTCtx.getLangOpts().OMPTargetTriples[0]),
   FeatureValidityCheck([&](StringRef FeatureName) {
 return ASTCtx.getTargetInfo().isValidFeatureName(FeatureName);
   }),
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index b91928063169ee..84f1fcdb6e83f2 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -888,7 +888,18 @@ void Parser::parseOMPTraitPropertyKind(OMPTraitProperty 
&TIProperty,
   TIProperty.Kind = TraitProperty::invalid;
 
   SourceLocation NameLoc = Tok.getLocation();
-  StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
+  StringRef Name;
+  if (Selector == llvm::omp::TraitSelector::target_device_device_num) {
+Name = "number";
+TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
+ExprResult DeviceNumExprResult = ParseExpression();
+if (!DeviceNumExprResult.isInvalid()) {
+  Expr *DeviceNumExpr = DeviceNumExprResult.get();
+  Actions.OpenMP().ActOnOpenMPDeviceNum(DeviceNumExpr);
+}
+return;
+  }
+  Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
   if (Name.empty()) {
 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, 
Selector);
@@ -918,7 +929,8 @@ void Parser::parseOMPTraitPropertyKind(OMPTraitProperty 
&TIProperty,
 << "()";
 return;
   }
-  TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
+  TraitSelector SelectorForName =
+  getOpenMPContextTraitSelectorKind(Name, SetForName);
   if (SelectorForName != TraitSelector::invalid) {
 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
@@ -935,7 +947,7 @@ void Parser::parseOMPTraitPropertyKind(OMPTraitProperty 
&TIProperty,
   }
   for (const auto &PotentialSet :
{TraitSet::construct, TraitSet::user, TraitSet::implementation,
-TraitSet::device}) {
+TraitSet::device, TraitSet::target_device}) {
 TraitProperty PropertyForName =
 getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name);
 if (PropertyForName == TraitProperty::invalid)
@@ -1062,7 +1074,7 @@ void Parser::parseOMPTraitSelectorKind(OMPTraitSelector 
&TISelector,
 return;
   }
 
-  TISelector.Kind = getOpenMPContextTraitSelectorKind(Name);
+  TISelector.Kind = g

[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Youngsuk Kim via cfe-commits

https://github.com/JOE1994 updated 
https://github.com/llvm/llvm-project/pull/119246

>From 9dbcf65775a979553bee2c95b16e3e2328e957a1 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Mon, 9 Dec 2024 10:33:18 -0600
Subject: [PATCH 1/2] [clang] Recover necessary AddrSpaceCast

A necessary AddrSpaceCast was wrongfully deleted in 
5c91b2886f6bf400b60ca7839069839ac3980f8f .
Recover the AddrSpaceCast.

This fixes #86791 .
---
 clang/lib/CodeGen/ItaniumCXXABI.cpp|  3 +++
 clang/test/OpenMP/amdgpu_threadprivate.cpp | 11 +++
 2 files changed, 14 insertions(+)
 create mode 100644 clang/test/OpenMP/amdgpu_threadprivate.cpp

diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index 8cbd09d02c7556..0abea335ad69e4 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -3302,6 +3302,9 @@ void ItaniumCXXABI::EmitThreadLocalInitFuncs(
   CharUnits Align = CGM.getContext().getDeclAlign(VD);
   Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
 }
+if (Val->getType() != Wrapper->getReturnType()) {
+  Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
+}
 
 Builder.CreateRet(Val);
   }
diff --git a/clang/test/OpenMP/amdgpu_threadprivate.cpp 
b/clang/test/OpenMP/amdgpu_threadprivate.cpp
new file mode 100644
index 00..5b15255ee62d4a
--- /dev/null
+++ b/clang/test/OpenMP/amdgpu_threadprivate.cpp
@@ -0,0 +1,11 @@
+// REQUIRES: asserts
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 
-disable-llvm-passes -fopenmp-targets=amdgcn-amd-amdhsa -x c++ -emit-llvm-bc %s 
-o %t-x86-host.bc
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple 
x86_64-unknown-linux-gnu -target-cpu gfx906 -fopenmp -nogpulib 
-fopenmp-is-target-device -fopenmp-host-ir-file-path %t-x86-host.bc -x c++ %s
+
+// Don't crash with assertions build.
+int MyGlobVar;
+#pragma omp threadprivate(MyGlobVar)
+int main() {
+  MyGlobVar = 1;
+}

>From 4af1ba587d01ab74f222efaa1a14cf95c652964a Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Thu, 12 Dec 2024 10:00:53 -0600
Subject: [PATCH 2/2] Avoid redundant type check before AddrSpaceCast

As per feedback from reviewers.
---
 clang/lib/CodeGen/ItaniumCXXABI.cpp | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index 0abea335ad69e4..cf9e338236e556 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -3302,9 +3302,7 @@ void ItaniumCXXABI::EmitThreadLocalInitFuncs(
   CharUnits Align = CGM.getContext().getDeclAlign(VD);
   Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
 }
-if (Val->getType() != Wrapper->getReturnType()) {
-  Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
-}
+Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
 
 Builder.CreateRet(Val);
   }

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


[clang] 4aacafd - [clang][ASTVisitor] Visit `HoldingVar` from `BindingDecl`. (#117858)

2024-12-12 Thread via cfe-commits

Author: Clement Courbet
Date: 2024-12-12T17:01:59+01:00
New Revision: 4aacafd49b74dc168e0d99018b4c8289ce9c923e

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

LOG: [clang][ASTVisitor] Visit `HoldingVar` from `BindingDecl`. (#117858)

Tuple-like types introduce `VarDecl`s in the AST for their "holding
vars", but AST visitors do not visit those. As a result the `VarDecl`
for the holding var is orphaned when trying to retreive its parents.

Fix a `FlowSensitive` test that assumes that only a `BindingDecl` is
introduced with the given name (the matcher now can also reach the
`VarDecl` for the holding var).

Added: 


Modified: 
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/AST/ASTContextParentMapTest.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 33363072c716f2..5d5c91ff91d553 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2151,8 +2151,11 @@ DEF_TRAVERSE_DECL(DecompositionDecl, {
 })
 
 DEF_TRAVERSE_DECL(BindingDecl, {
-  if (getDerived().shouldVisitImplicitCode())
+  if (getDerived().shouldVisitImplicitCode()) {
 TRY_TO(TraverseStmt(D->getBinding()));
+if (const auto HoldingVar = D->getHoldingVar())
+  TRY_TO(TraverseDecl(HoldingVar));
+  }
 })
 
 DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })

diff  --git a/clang/unittests/AST/ASTContextParentMapTest.cpp 
b/clang/unittests/AST/ASTContextParentMapTest.cpp
index 515dfb99e1126d..9af0a46817a25f 100644
--- a/clang/unittests/AST/ASTContextParentMapTest.cpp
+++ b/clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -148,5 +148,54 @@ TEST(GetParents, FriendTypeLoc) {
   ElementsAre(DynTypedNode::create(FrA)));
 }
 
+TEST(GetParents, UserDefinedTupleLikeTypes) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(Verifier.match(
+  R"(
+namespace std {
+
+using size_t = __typeof(sizeof(int));
+
+template 
+struct tuple_size;
+
+template 
+struct tuple_size : tuple_size{};
+
+template 
+requires requires { tuple_size::value; }
+struct tuple_size : tuple_size{};
+
+
+template
+struct tuple_element;
+
+
+}  // namespace std
+
+struct Decomposable {};
+
+template<> struct std::tuple_size {
+  static constexpr size_t value = 2;
+};
+
+template struct std::tuple_element {
+  using type = int;
+};
+
+template struct std::tuple_element {
+  using type = const int;
+};
+
+template
+const int& get(const Decomposable& d);
+
+void F(const Decomposable& d) {
+const auto& [x, y] = d;
+}
+)",
+  varDecl(hasName("x"), hasAncestor(decompositionDecl())), Lang_CXX20));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 39e7001393e5e9..0f731f4532535e 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -25,6 +25,7 @@
 #include "gtest/gtest.h"
 #include 
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -143,6 +144,15 @@ const Formula &getFormula(const ValueDecl &D, const 
Environment &Env) {
   return cast(Env.getValue(D))->formula();
 }
 
+const BindingDecl *findBindingDecl(ASTContext &ASTCtx, std::string_view Name) {
+  using ast_matchers::bindingDecl;
+  using ast_matchers::hasName;
+  auto TargetNodes =
+  ast_matchers::match(bindingDecl(hasName(Name)).bind("v"), ASTCtx);
+  assert(TargetNodes.size() == 1 && "Name must be unique");
+  return ast_matchers::selectFirst("v", TargetNodes);
+}
+
 TEST(TransferTest, CNotSupported) {
   TestInputs Inputs("void target() {}");
   Inputs.Language = TestLanguage::Lang_C89;
@@ -5515,10 +5525,10 @@ TEST(TransferTest, 
StructuredBindingAssignFromTupleLikeType) {
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
 
-const ValueDecl *BoundFooDecl = findValueDecl(ASTCtx, "BoundFoo");
+const ValueDecl *BoundFooDecl = findBindingDecl(ASTCtx, "BoundFoo");
 ASSERT_THAT(BoundFooDecl, NotNull());
 
-const ValueDecl *BoundBarDecl = findValueDecl(ASTCtx, "BoundBar");
+const ValueDecl *BoundBarDecl = findBindingDecl(ASTCtx, "BoundBar");
 ASSERT_THAT(BoundBarDecl, NotNull());
 
 const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
@@ -5596,10 +5606,10 @@ TEST(TransferTest, 
StructuredBindingAssignRefFromTupleLikeType) {
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
 const Environment &Env1 = getEnvironmentAtAnnotation(Re

[clang] [clang][ASTVisitor] Visit `HoldingVar` from `BindingDecl`. (PR #117858)

2024-12-12 Thread Clement Courbet via cfe-commits

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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-12 Thread Nikita Popov via cfe-commits

nikic wrote:

I think https://github.com/llvm/llvm-test-suite/pull/190 should fix this issue, 
but haven't tested on an affected arch.

I'm a bit worried that we don't have a sanitizer to catch this issue (the 
negative left shift issue is an unrelated one).

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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Youngsuk Kim via cfe-commits

JOE1994 wrote:

> I mean, why do we have to watch for type mismatches and fix them instead of 
> creating the correct type in the first place?
There is getPointerType(RetQT) just above, shouldn't it be something like 
getPointerType(RetQT, )?
Or RetQT should have had the correct address space, but for some reason it was 
lost?

I totally agree with you.
I'm unfamiliar with Clang Qualtypes
and how clang QualTypes' addrspace info
match to llvm types' addrspace info,
so I shared a quick dirty fix to at least share a direction.


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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-12 Thread Lu Weining via cfe-commits

SixWeining wrote:

Seems that this change causes Segment Fault on multiple targets including 
aarch64, loongarch64 and riscv64.

This is detected by a LoongArch 
[buildbot](https://lab.llvm.org/staging/#/builders/20/builds/6282) and manually 
checked on aarch64 and riscv64 QEMUs.

I wonder why aarch64 buildbot doesn't report this. I find that 
`CMAKE_CXX_FLAGS_RELEASE` is empty on aarch64 bot while it is `-O3 -DNDEBUG` on 
loongarch64. Is it an issue of the llvm-zorg framework?

# Reproduce
$ clang llvm-test-suite/SingleSource/Benchmarks/CoyoteBench/huffbench.c -O3 -o 
huffbench
$ ./huffbench


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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-12 Thread Nikita Popov via cfe-commits

nikic wrote:

>From a quick look, it's probably due to UB on this line: 
>https://github.com/llvm/llvm-test-suite/blob/4f14adb8a2f2c5fa02c6b3643d45e74adfcb31f9/SingleSource/Benchmarks/CoyoteBench/huffbench.c#L114
> It indexes below the start of an object.

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


[clang] [clang] Enable the -Wdangling-capture diagnostic by default. (PR #119685)

2024-12-12 Thread Haojian Wu via cfe-commits

hokein wrote:

> Did you benchmark the impact on compile times?

I don't have concrete numbers, this warning works similarly to other -Wdangling 
warnings, performing only a lightweight, single-statement analysis on the 
annotated parameter, I believe the cost on compile times is negligible. 

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


[clang] [Clang] Fix crash for incompatible types in inline assembly (PR #119098)

2024-12-12 Thread via cfe-commits


@@ -664,11 +664,22 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, 
bool IsSimple,
   SmallerValueMentioned |= OutSize < InSize;
 }
 
+// If the input is an integer register while the output is floating point,
+// there is no way they can work together.
+bool FPBoundToInt = false;
+if (InputDomain != AD_FP && OutputDomain == AD_FP) {
+  FPBoundToInt = true;
+}
+if (InputDomain == AD_FP && OutputDomain != AD_FP) {
+  FPBoundToInt = true;
+}

AdUhTkJm wrote:

I think this might be clearer than expressions like `(InputDomain == AD_FP) ^ 
(OutputDomain == AD_FP)`. By the way the previous parts uses "Tied", so I think 
I'd change it this way.

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


[clang] [clang] Generate appropriate assume in presence of libc's memcpy (PR #119704)

2024-12-12 Thread via cfe-commits

https://github.com/serge-sans-paille created 
https://github.com/llvm/llvm-project/pull/119704

It is an undefined behavior to pass null arguments as memcpy source or 
destination parameter, so generate the appropriate llvm.assume call to 
communicate this to the backend.

Don't do it for builtin memcpy as they don't suffer the same behavior in case 
of null size.

>From 9d013f37df124fde0ed637d4b979de5ab01cbc22 Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Thu, 12 Dec 2024 14:45:31 +0100
Subject: [PATCH] [clang] Generate appropriate assume in presence of libc's
 memcpy

It is an undefined behavior to pass null arguments as memcpy source or
destination parameter, so generate the appropriate llvm.assume call to
communicate this to the backend.

Don't do it for builtin memcpy as they don't suffer the same behavior in
case of null size.
---
 clang/lib/CodeGen/CGBuiltin.cpp   | 6 ++
 clang/test/CodeGen/catch-undef-behavior.c | 4 
 2 files changed, 10 insertions(+)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 497a0b3952af8c..50cd8529120d36 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4531,6 +4531,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Value *SizeVal = EmitScalarExpr(E->getArg(2));
 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
+if (BuiltinID == Builtin::BImemcpy || BuiltinID == Builtin::BImempcpy) {
+  Builder.CreateAssumption(
+  Builder.CreateIsNotNull(Dest.emitRawPointer(*this)));
+  Builder.CreateAssumption(
+  Builder.CreateIsNotNull(Src.emitRawPointer(*this)));
+}
 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
 if (BuiltinID == Builtin::BImempcpy ||
 BuiltinID == Builtin::BI__builtin_mempcpy)
diff --git a/clang/test/CodeGen/catch-undef-behavior.c 
b/clang/test/CodeGen/catch-undef-behavior.c
index 7580290b0b0333..7ef7c78f1cebb7 100644
--- a/clang/test/CodeGen/catch-undef-behavior.c
+++ b/clang/test/CodeGen/catch-undef-behavior.c
@@ -371,6 +371,10 @@ void call_memcpy_nonnull(void *p, void *q, int sz) {
   // CHECK-TRAP: call void @llvm.ubsantrap(i8 16)
   // CHECK-COMMON-NOT: call
 
+  // CHECK-COMMON: %5 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %5)
+  // CHECK-COMMON: %6 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %6)
   // CHECK-COMMON: call void @llvm.memcpy.p0.p0.i64(ptr align 1 %0, ptr align 
1 %1, i64 %conv, i1 false)
   memcpy(p, q, sz);
 }

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


[clang] [clang] Generate appropriate assume in presence of libc's memcpy (PR #119704)

2024-12-12 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: None (serge-sans-paille)


Changes

It is an undefined behavior to pass null arguments as memcpy source or 
destination parameter, so generate the appropriate llvm.assume call to 
communicate this to the backend.

Don't do it for builtin memcpy as they don't suffer the same behavior in case 
of null size.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+6) 
- (modified) clang/test/CodeGen/catch-undef-behavior.c (+4) 


``diff
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 497a0b3952af8c..50cd8529120d36 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4531,6 +4531,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Value *SizeVal = EmitScalarExpr(E->getArg(2));
 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
+if (BuiltinID == Builtin::BImemcpy || BuiltinID == Builtin::BImempcpy) {
+  Builder.CreateAssumption(
+  Builder.CreateIsNotNull(Dest.emitRawPointer(*this)));
+  Builder.CreateAssumption(
+  Builder.CreateIsNotNull(Src.emitRawPointer(*this)));
+}
 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
 if (BuiltinID == Builtin::BImempcpy ||
 BuiltinID == Builtin::BI__builtin_mempcpy)
diff --git a/clang/test/CodeGen/catch-undef-behavior.c 
b/clang/test/CodeGen/catch-undef-behavior.c
index 7580290b0b0333..7ef7c78f1cebb7 100644
--- a/clang/test/CodeGen/catch-undef-behavior.c
+++ b/clang/test/CodeGen/catch-undef-behavior.c
@@ -371,6 +371,10 @@ void call_memcpy_nonnull(void *p, void *q, int sz) {
   // CHECK-TRAP: call void @llvm.ubsantrap(i8 16)
   // CHECK-COMMON-NOT: call
 
+  // CHECK-COMMON: %5 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %5)
+  // CHECK-COMMON: %6 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %6)
   // CHECK-COMMON: call void @llvm.memcpy.p0.p0.i64(ptr align 1 %0, ptr align 
1 %1, i64 %conv, i1 false)
   memcpy(p, q, sz);
 }

``




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


[clang] [clang] Recover necessary AddrSpaceCast (PR #119246)

2024-12-12 Thread Sergei Barannikov via cfe-commits

s-barannikov wrote:

> I'm unfamiliar with Clang Qualtypes

I see. Well, neither am I :) I brought this up in case someone else could 
suggest the preferred way to fix the issue.
I don't have objections against the current approach, but I'm not qualified to 
review it either.


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


[clang] [Clang][Parser] Add a warning to ambiguous uses of T...[N] types (PR #116332)

2024-12-12 Thread via cfe-commits

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

LGTM.
I'll be amazed if this warning ever get seen in the wild though 

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


[clang] 8eec301 - [OpenACC] Implement 'device_type' for 'data' construct

2024-12-12 Thread via cfe-commits

Author: erichkeane
Date: 2024-12-12T08:37:20-08:00
New Revision: 8eec301fe3ac5fdcb4de4757806661b99c9e6580

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

LOG: [OpenACC] Implement 'device_type' for 'data' construct

Semantically this is identical to all other constructs with this tag,
except in this case the 'wait' and 'async' are the only ones allowed
after it. This patch implements that rule using the existing
infrastructure.

Added: 
clang/test/SemaOpenACC/data-construct-device_type-ast.cpp
clang/test/SemaOpenACC/data-construct-device_type-clause.c

Modified: 
clang/lib/Sema/SemaOpenACC.cpp
clang/test/AST/ast-print-openacc-data-construct.cpp
clang/test/SemaOpenACC/data-construct.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenACC.cpp b/clang/lib/Sema/SemaOpenACC.cpp
index 5575dd730e5596..981a98d024a281 100644
--- a/clang/lib/Sema/SemaOpenACC.cpp
+++ b/clang/lib/Sema/SemaOpenACC.cpp
@@ -435,11 +435,12 @@ bool checkAlreadyHasClauseOfKind(
 bool checkValidAfterDeviceType(
 SemaOpenACC &S, const OpenACCDeviceTypeClause &DeviceTypeClause,
 const SemaOpenACC::OpenACCParsedClause &NewClause) {
-  // This is only a requirement on compute and loop constructs so far, so this
-  // is fine otherwise.
+  // This is only a requirement on compute, combined, data and loop constructs
+  // so far, so this is fine otherwise.
   if (!isOpenACCComputeDirectiveKind(NewClause.getDirectiveKind()) &&
   !isOpenACCCombinedDirectiveKind(NewClause.getDirectiveKind()) &&
-  NewClause.getDirectiveKind() != OpenACCDirectiveKind::Loop)
+  NewClause.getDirectiveKind() != OpenACCDirectiveKind::Loop &&
+  NewClause.getDirectiveKind() != OpenACCDirectiveKind::Data)
 return false;
 
   // OpenACC3.3: Section 2.4: Clauses that precede any device_type clause are
@@ -504,6 +505,16 @@ bool checkValidAfterDeviceType(
 default:
   break;
 }
+  } else if (NewClause.getDirectiveKind() == OpenACCDirectiveKind::Data) {
+// OpenACC3.3 section 2.6.5: Only the async and wait clauses may follow a
+// device_type clause.
+switch (NewClause.getClauseKind()) {
+case OpenACCClauseKind::Async:
+case OpenACCClauseKind::Wait:
+  return false;
+default:
+  break;
+}
   }
   S.Diag(NewClause.getBeginLoc(), diag::err_acc_clause_after_device_type)
   << NewClause.getClauseKind() << DeviceTypeClause.getClauseKind()
@@ -1067,12 +1078,13 @@ OpenACCClause 
*SemaOpenACCClauseVisitor::VisitWaitClause(
 
 OpenACCClause *SemaOpenACCClauseVisitor::VisitDeviceTypeClause(
 SemaOpenACC::OpenACCParsedClause &Clause) {
-  // Restrictions only properly implemented on 'compute', 'combined',  and
-  // 'loop' constructs, and 'compute'/'combined'/'loop' constructs are the only
-  // construct that can do anything with this yet, so skip/treat as
+  // Restrictions only properly implemented on 'compute', 'combined', 'data' 
and
+  // 'loop' constructs, and 'compute'/'combined'/'data'/'loop' constructs are
+  // the only construct that can do anything with this yet, so skip/treat as
   // unimplemented in this case.
   if (!isOpenACCComputeDirectiveKind(Clause.getDirectiveKind()) &&
   Clause.getDirectiveKind() != OpenACCDirectiveKind::Loop &&
+  Clause.getDirectiveKind() != OpenACCDirectiveKind::Data &&
   !isOpenACCCombinedDirectiveKind(Clause.getDirectiveKind()))
 return isNotImplemented();
 

diff  --git a/clang/test/AST/ast-print-openacc-data-construct.cpp 
b/clang/test/AST/ast-print-openacc-data-construct.cpp
index fc15add15c6b89..c65121317c099d 100644
--- a/clang/test/AST/ast-print-openacc-data-construct.cpp
+++ b/clang/test/AST/ast-print-openacc-data-construct.cpp
@@ -10,6 +10,11 @@ void foo() {
 // CHECK-NOT: default(none)
 #pragma acc data default(none)
   ;
+
+// CHECK: #pragma acc data device_type(int)
+#pragma acc data device_type(int)
+  ;
+
 // CHECK: #pragma acc enter data
 // CHECK-NOT: copyin(Var)
 #pragma acc enter data copyin(Var)

diff  --git a/clang/test/SemaOpenACC/data-construct-device_type-ast.cpp 
b/clang/test/SemaOpenACC/data-construct-device_type-ast.cpp
new file mode 100644
index 00..23f00490f0674f
--- /dev/null
+++ b/clang/test/SemaOpenACC/data-construct-device_type-ast.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 %s -fopenacc -ast-dump | FileCheck %s
+
+// Test this with PCH.
+// RUN: %clang_cc1 %s -fopenacc -emit-pch -o %t %s
+// RUN: %clang_cc1 %s -fopenacc -include-pch %t -ast-dump-all | FileCheck %s
+#ifndef PCH_HELPER
+#define PCH_HELPER
+
+template
+void TemplUses() {
+  // CHECK: FunctionTemplateDecl{{.*}}TemplUses
+  // CHECK-NEXT: TemplateTypeParmDecl{{.*}}T
+  // CHECK-NEXT: FunctionDecl{{.*}}TemplUses
+  // CHECK-NEXT: CompoundStmt
+
+#pragma acc data device_type(T) dtype(T)
+  ;
+  // 

[clang] [flang] [flang] Add -f[no-]vectorize flags (PR #119718)

2024-12-12 Thread David Truby via cfe-commits

https://github.com/DavidTruby created 
https://github.com/llvm/llvm-project/pull/119718

This patch adds the -fvectorize and -fno-vectorize flags to flang. 

Note that this also changes the behaviour of `flang -fc1` to match that of 
`clang -cc1`, which is that vectorization is only enabled in the presence of 
the `-vectorize-loops` flag.

Additionally, this patch changes the behaviour of the default optimisation 
levels to match clang, such that vectorization only happens at the same levels 
as it does there. 

This patch is in draft while I write an RFC to discuss the above two changes.

>From 0b9cbef8073cdfc511087c315deb82a90c408640 Mon Sep 17 00:00:00 2001
From: David Truby 
Date: Thu, 12 Dec 2024 14:50:19 +
Subject: [PATCH] [flang] Add -f[no-]vectorize flags

---
 clang/include/clang/Driver/Driver.h   |  3 ++
 clang/include/clang/Driver/Options.td | 11 --
 clang/lib/Driver/Driver.cpp   | 34 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 33 --
 clang/lib/Driver/ToolChains/Flang.cpp | 10 ++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/lib/Frontend/CompilerInvocation.cpp |  4 +++
 flang/lib/Frontend/FrontendActions.cpp|  3 ++
 flang/test/Driver/optimization-remark.f90 | 22 ++--
 9 files changed, 74 insertions(+), 47 deletions(-)

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index c23d037e725bb9..4c4375b25902c4 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -856,6 +856,9 @@ void applyOverrideOptions(SmallVectorImpl 
&Args,
   llvm::StringSet<> &SavedStrings,
   raw_ostream *OS = nullptr);
 
+bool shouldEnableVectorizerAtOLevel(const llvm::opt::ArgList &Args,
+bool isSlpVec);
+
 } // end namespace driver
 } // end namespace clang
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 88862ae9edb29d..bc3c1e4a0045ff 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4038,11 +4038,15 @@ defm assumptions : BoolFOption<"assumptions",
   "Disable codegen and compile-time checks for C++23's [[assume]] 
attribute">,
   PosFlag>;
 
+
+let Visibility = [ClangOption, FlangOption] in {
 def fvectorize : Flag<["-"], "fvectorize">, Group,
   HelpText<"Enable the loop vectorization passes">;
 def fno_vectorize : Flag<["-"], "fno-vectorize">, Group;
 def : Flag<["-"], "ftree-vectorize">, Alias;
 def : Flag<["-"], "fno-tree-vectorize">, Alias;
+}
+
 def fslp_vectorize : Flag<["-"], "fslp-vectorize">, Group,
   HelpText<"Enable the superword-level parallelism vectorization passes">;
 def fno_slp_vectorize : Flag<["-"], "fno-slp-vectorize">, Group;
@@ -7323,6 +7327,10 @@ let Visibility = [CC1Option, FC1Option] in {
 def mlink_builtin_bitcode : Separate<["-"], "mlink-builtin-bitcode">,
   HelpText<"Link and internalize needed symbols from the given bitcode file "
"before performing optimizations.">;
+
+def vectorize_loops : Flag<["-"], "vectorize-loops">,
+  HelpText<"Run the Loop vectorization passes">,
+  MarshallingInfoFlag>;
 } // let Visibility = [CC1Option, FC1Option]
 
 let Visibility = [CC1Option] in {
@@ -7439,9 +7447,6 @@ defm link_builtin_bitcode_postopt: 
BoolMOption<"link-builtin-bitcode-postopt",
   PosFlag,
   NegFlag>;
-def vectorize_loops : Flag<["-"], "vectorize-loops">,
-  HelpText<"Run the Loop vectorization passes">,
-  MarshallingInfoFlag>;
 def vectorize_slp : Flag<["-"], "vectorize-slp">,
   HelpText<"Run the SLP vectorization passes">,
   MarshallingInfoFlag>;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index fb73b62cf2daed..1510af0047fc47 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6980,3 +6980,37 @@ void driver::applyOverrideOptions(SmallVectorImpl &Args,
   ++S;
   }
 }
+
+/// Vectorize at all optimization levels greater than 1 except for -Oz.
+/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
+/// enabled.
+bool driver::shouldEnableVectorizerAtOLevel(const ArgList &Args,
+bool isSlpVec) {
+  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
+if (A->getOption().matches(options::OPT_O4) ||
+A->getOption().matches(options::OPT_Ofast))
+  return true;
+
+if (A->getOption().matches(options::OPT_O0))
+  return false;
+
+assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
+
+// Vectorize -Os.
+StringRef S(A->getValue());
+if (S == "s")
+  return true;
+
+// Don't vectorize -Oz, unless it's the slp vectorizer.
+if (S == "z")
+  return isSlpVec;
+
+unsigned OptLevel = 0;
+if (S.getAsInteger(10, OptLevel))
+  return false;
+
+return OptLevel > 1;
+  }
+
+  return false;
+

[clang] [flang] [flang] Add -f[no-]vectorize flags (PR #119718)

2024-12-12 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-flang-driver

@llvm/pr-subscribers-clang

Author: David Truby (DavidTruby)


Changes

This patch adds the -fvectorize and -fno-vectorize flags to flang. 

Note that this also changes the behaviour of `flang -fc1` to match that of 
`clang -cc1`, which is that vectorization is only enabled in the presence of 
the `-vectorize-loops` flag.

Additionally, this patch changes the behaviour of the default optimisation 
levels to match clang, such that vectorization only happens at the same levels 
as it does there. 

This patch is in draft while I write an RFC to discuss the above two changes.

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


9 Files Affected:

- (modified) clang/include/clang/Driver/Driver.h (+3) 
- (modified) clang/include/clang/Driver/Options.td (+8-3) 
- (modified) clang/lib/Driver/Driver.cpp (+34) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (-33) 
- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+10) 
- (modified) flang/include/flang/Frontend/CodeGenOptions.def (+1) 
- (modified) flang/lib/Frontend/CompilerInvocation.cpp (+4) 
- (modified) flang/lib/Frontend/FrontendActions.cpp (+3) 
- (modified) flang/test/Driver/optimization-remark.f90 (+11-11) 


``diff
diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index c23d037e725bb9..4c4375b25902c4 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -856,6 +856,9 @@ void applyOverrideOptions(SmallVectorImpl 
&Args,
   llvm::StringSet<> &SavedStrings,
   raw_ostream *OS = nullptr);
 
+bool shouldEnableVectorizerAtOLevel(const llvm::opt::ArgList &Args,
+bool isSlpVec);
+
 } // end namespace driver
 } // end namespace clang
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 88862ae9edb29d..bc3c1e4a0045ff 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4038,11 +4038,15 @@ defm assumptions : BoolFOption<"assumptions",
   "Disable codegen and compile-time checks for C++23's [[assume]] 
attribute">,
   PosFlag>;
 
+
+let Visibility = [ClangOption, FlangOption] in {
 def fvectorize : Flag<["-"], "fvectorize">, Group,
   HelpText<"Enable the loop vectorization passes">;
 def fno_vectorize : Flag<["-"], "fno-vectorize">, Group;
 def : Flag<["-"], "ftree-vectorize">, Alias;
 def : Flag<["-"], "fno-tree-vectorize">, Alias;
+}
+
 def fslp_vectorize : Flag<["-"], "fslp-vectorize">, Group,
   HelpText<"Enable the superword-level parallelism vectorization passes">;
 def fno_slp_vectorize : Flag<["-"], "fno-slp-vectorize">, Group;
@@ -7323,6 +7327,10 @@ let Visibility = [CC1Option, FC1Option] in {
 def mlink_builtin_bitcode : Separate<["-"], "mlink-builtin-bitcode">,
   HelpText<"Link and internalize needed symbols from the given bitcode file "
"before performing optimizations.">;
+
+def vectorize_loops : Flag<["-"], "vectorize-loops">,
+  HelpText<"Run the Loop vectorization passes">,
+  MarshallingInfoFlag>;
 } // let Visibility = [CC1Option, FC1Option]
 
 let Visibility = [CC1Option] in {
@@ -7439,9 +7447,6 @@ defm link_builtin_bitcode_postopt: 
BoolMOption<"link-builtin-bitcode-postopt",
   PosFlag,
   NegFlag>;
-def vectorize_loops : Flag<["-"], "vectorize-loops">,
-  HelpText<"Run the Loop vectorization passes">,
-  MarshallingInfoFlag>;
 def vectorize_slp : Flag<["-"], "vectorize-slp">,
   HelpText<"Run the SLP vectorization passes">,
   MarshallingInfoFlag>;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index fb73b62cf2daed..1510af0047fc47 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6980,3 +6980,37 @@ void driver::applyOverrideOptions(SmallVectorImpl &Args,
   ++S;
   }
 }
+
+/// Vectorize at all optimization levels greater than 1 except for -Oz.
+/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
+/// enabled.
+bool driver::shouldEnableVectorizerAtOLevel(const ArgList &Args,
+bool isSlpVec) {
+  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
+if (A->getOption().matches(options::OPT_O4) ||
+A->getOption().matches(options::OPT_Ofast))
+  return true;
+
+if (A->getOption().matches(options::OPT_O0))
+  return false;
+
+assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
+
+// Vectorize -Os.
+StringRef S(A->getValue());
+if (S == "s")
+  return true;
+
+// Don't vectorize -Oz, unless it's the slp vectorizer.
+if (S == "z")
+  return isSlpVec;
+
+unsigned OptLevel = 0;
+if (S.getAsInteger(10, OptLevel))
+  return false;
+
+return OptLevel > 1;
+  }
+
+  return false;
+}
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index d3206c3e8e25e

[clang] [flang] [flang] Add -f[no-]vectorize flags (PR #119718)

2024-12-12 Thread David Truby via cfe-commits

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


[clang] [SystemZ][z/OS] Add visibility features for z/OS (eg. _Export, pragma export) (PR #111035)

2024-12-12 Thread Sean Perry via cfe-commits

https://github.com/perry-ca updated 
https://github.com/llvm/llvm-project/pull/111035

>From e8d355c9cd165e0a255bbbfb5b0126cf7b1461a6 Mon Sep 17 00:00:00 2001
From: Sean Perry 
Date: Wed, 2 Oct 2024 12:56:43 -0500
Subject: [PATCH 1/9] initial work for pragma export & _Export keyword

---
 clang/include/clang/AST/ASTConsumer.h |   3 +
 clang/include/clang/Basic/Attr.td |   6 +
 clang/include/clang/Basic/AttrDocs.td |  21 ++
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Basic/TokenKinds.def  |   5 +
 clang/include/clang/Parse/Parser.h|  13 ++
 clang/include/clang/Sema/DeclSpec.h   |  31 ++-
 clang/include/clang/Sema/Sema.h   |  30 +++
 clang/lib/CodeGen/BackendConsumer.h   |   1 +
 clang/lib/CodeGen/CodeGenAction.cpp   |   4 +
 clang/lib/CodeGen/CodeGenModule.cpp   |  15 ++
 clang/lib/CodeGen/CodeGenModule.h |   2 +
 clang/lib/CodeGen/ModuleBuilder.cpp   |   6 +-
 clang/lib/Driver/ToolChains/ZOS.cpp   |  12 +-
 clang/lib/Parse/ParseDecl.cpp |  18 ++
 clang/lib/Parse/ParseDeclCXX.cpp  |   6 +
 clang/lib/Parse/ParsePragma.cpp   | 208 ++
 clang/lib/Parse/Parser.cpp|   3 +
 clang/lib/Sema/DeclSpec.cpp   |   6 +
 clang/lib/Sema/Sema.cpp   |  21 ++
 clang/lib/Sema/SemaAttr.cpp   | 162 ++
 clang/lib/Sema/SemaDecl.cpp   |  13 ++
 clang/test/CodeGen/attr-export-failing.cpp|   4 +
 clang/test/CodeGen/attr-export.cpp|  51 +
 clang/test/CodeGen/pragma-export.c|  39 
 clang/test/CodeGen/pragma-export.cpp  |  82 +++
 clang/test/CodeGen/zos-pragmas.c  |  11 +
 clang/test/CodeGen/zos-pragmas.cpp|  11 +
 28 files changed, 784 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/CodeGen/attr-export-failing.cpp
 create mode 100644 clang/test/CodeGen/attr-export.cpp
 create mode 100644 clang/test/CodeGen/pragma-export.c
 create mode 100644 clang/test/CodeGen/pragma-export.cpp
 create mode 100644 clang/test/CodeGen/zos-pragmas.c
 create mode 100644 clang/test/CodeGen/zos-pragmas.cpp

diff --git a/clang/include/clang/AST/ASTConsumer.h 
b/clang/include/clang/AST/ASTConsumer.h
index 447f2592d23595..b15d53e700c679 100644
--- a/clang/include/clang/AST/ASTConsumer.h
+++ b/clang/include/clang/AST/ASTConsumer.h
@@ -108,6 +108,9 @@ class ASTConsumer {
   /// completed.
   virtual void CompleteExternalDeclaration(DeclaratorDecl *D) {}
 
+  /// CompletePragmaExport - complete #pragma export statements.
+  virtual void CompletePragmaExport(Decl *D) {}
+
   /// Callback invoked when an MSInheritanceAttr has been attached to a
   /// CXXRecordDecl.
   virtual void AssignInheritanceModel(CXXRecordDecl *RD) {}
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fbcbf0ed416416..884c4147cf1285 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4520,6 +4520,12 @@ def ReleaseHandle : InheritableParamAttr {
   let Documentation = [ReleaseHandleDocs];
 }
 
+def zOSExport : InheritableAttr {
+  let Spellings = [CustomKeyword<"_Export">];
+  let Subjects = SubjectList<[Function, Var, CXXRecord]>;
+  let Documentation = [zOSExportDocs];
+}
+
 def UnsafeBufferUsage : InheritableAttr {
   let Spellings = [Clang<"unsafe_buffer_usage">];
   let Subjects = SubjectList<[Function, Field]>;
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 53d88482698f00..bf56fa6ad7162f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6863,6 +6863,27 @@ attribute requires a string literal argument to identify 
the handle being releas
   }];
 }
 
+def zOSExportDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+Use the _Export keyword with a function name or external variable to declare
+that it is to be exported (made available to other modules). You must define
+the object name in the same translation unit in which you use the _Export
+keyword. For example:
+
+.. code-block:: c
+
+  int _Export anthony(float);
+
+This statement exports the function anthony, if you define the function in the
+translation unit. The _Export keyword must immediately precede the object name.
+If you apply the _Export keyword to a class, the compiler automatically exports
+all static data members and member functions of the class. However, if you want
+it to apply to individual class members, then you must apply it to each member
+that can be referenced.
+  }];
+}
+
 def UnsafeBufferUsageDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 64e6d0407b0ce3..09842ed02efd4b 100644
--- a/c

[clang] [clang-cl] Don't add implicit NoBuiltinAttr to deleted or defaulted functions (#116256) (PR #119719)

2024-12-12 Thread via cfe-commits

https://github.com/VScigolevs created 
https://github.com/llvm/llvm-project/pull/119719

None

>From 7babf835ecaf3081473b42ee48f522ff3bfb39ee Mon Sep 17 00:00:00 2001
From: Vladimirs Scigolevs 
Date: Fri, 22 Nov 2024 11:26:37 +0200
Subject: [PATCH] [clang-cl] Don't add implicit NoBuiltinAttr to deleted or
 defaulted functions (#116256)

---
 clang/lib/Sema/SemaAttr.cpp   |  2 ++
 .../msvc-pragma-function-no-builtin-attr.cpp  | 32 +++
 2 files changed, 34 insertions(+)
 create mode 100644 clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp

diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 479f47962a7c3d..44485e71d57a01 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -1310,6 +1310,8 @@ void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl 
*FD,
 }
 
 void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
+  if (FD->isDeleted() || FD->isDefaulted())
+return;
   SmallVector V(MSFunctionNoBuiltins.begin(),
MSFunctionNoBuiltins.end());
   if (!MSFunctionNoBuiltins.empty())
diff --git a/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp 
b/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp
new file mode 100644
index 00..cd2ac7d1edbefb
--- /dev/null
+++ b/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cl -fms-compatibility -Xclang -ast-dump -fsyntax-only %s | 
FileCheck %s
+
+extern "C" __inline float __cdecl fabsf(  float _X);
+// CHECK: FunctionDecl {{.*}} fabsf
+#pragma function(fabsf)
+  __inline float __cdecl fabsf(  float _X)
+{
+return 0;
+}
+// CHECK: FunctionDecl {{.*}} fabsf
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf
+
+int bar() {
+  return 0;
+}
+// CHECK: FunctionDecl {{.*}} bar
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf
+
+struct A {
+int foo() = delete;
+// CHECK: CXXMethodDecl {{.*}} foo 'int ()' delete
+// CHECK-NOT: NoBuiltinAttr
+A() = default;
+// CHECK: CXXConstructorDecl {{.*}} A 'void ()' default
+// CHECK-NOT: NoBuiltinAttr
+};
+
+int main() {
+return 0;
+}
+// CHECK: FunctionDecl {{.*}} main
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf

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


[clang] [clang-cl] Don't add implicit NoBuiltinAttr to deleted or defaulted functions (#116256) (PR #119719)

2024-12-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (VScigolevs)


Changes



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


2 Files Affected:

- (modified) clang/lib/Sema/SemaAttr.cpp (+2) 
- (added) clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp (+32) 


``diff
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 479f47962a7c3d..44485e71d57a01 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -1310,6 +1310,8 @@ void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl 
*FD,
 }
 
 void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
+  if (FD->isDeleted() || FD->isDefaulted())
+return;
   SmallVector V(MSFunctionNoBuiltins.begin(),
MSFunctionNoBuiltins.end());
   if (!MSFunctionNoBuiltins.empty())
diff --git a/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp 
b/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp
new file mode 100644
index 00..cd2ac7d1edbefb
--- /dev/null
+++ b/clang/test/SemaCXX/msvc-pragma-function-no-builtin-attr.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cl -fms-compatibility -Xclang -ast-dump -fsyntax-only %s | 
FileCheck %s
+
+extern "C" __inline float __cdecl fabsf(  float _X);
+// CHECK: FunctionDecl {{.*}} fabsf
+#pragma function(fabsf)
+  __inline float __cdecl fabsf(  float _X)
+{
+return 0;
+}
+// CHECK: FunctionDecl {{.*}} fabsf
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf
+
+int bar() {
+  return 0;
+}
+// CHECK: FunctionDecl {{.*}} bar
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf
+
+struct A {
+int foo() = delete;
+// CHECK: CXXMethodDecl {{.*}} foo 'int ()' delete
+// CHECK-NOT: NoBuiltinAttr
+A() = default;
+// CHECK: CXXConstructorDecl {{.*}} A 'void ()' default
+// CHECK-NOT: NoBuiltinAttr
+};
+
+int main() {
+return 0;
+}
+// CHECK: FunctionDecl {{.*}} main
+// CHECK: NoBuiltinAttr {{.*}} <> Implicit fabsf

``




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


[clang] [clang-cl] Don't add implicit NoBuiltinAttr to deleted or defaulted functions (#116256) (PR #119719)

2024-12-12 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang] Fix a use-after-free in expression evaluation (PR #118480)

2024-12-12 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

Here's a small reprocase (thanks for cvise for getting it):

```cpp
// Run under ASAN: clang -fsyntax-only 
template 
constexpr _InputIterator find_if(_InputIterator __first, _Predicate __pred) {
  if (__pred(*__first))
;
}

template 
struct basic_string_view {
  char __data_;
};

template 
struct Span {
  T *begin;
};

constexpr Span> kNames((basic_string_view[]){});

void StripConsentJoinIfNeeded() {
  !find_if(kNames.begin, [](basic_string_view) { return true; });
}
```

Somebody would need to dig a little deeper to understand what's causing the 
crash here, but it should be manageable with this size. (I'd look at it myself, 
but probably not until next week)

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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-12 Thread via cfe-commits

serge-sans-paille wrote:

Hey @nikic,
I've bisected the failures from this buildbot:
https://lab.llvm.org/buildbot/#/builders/199/builds/57
down to this commit.

The reproducer is unfortunately not pleasant:
get a stage-2 build of clang then run the llvm-test suite. This reproducibility 
chokes on `SingleSource/Benchmarks/CoyoteBench/huffbench.test`, as can be seen 
on the buildbot log.

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


[clang] [Clang][Parser] Add a warning to ambiguous uses of T...[N] types (PR #116332)

2024-12-12 Thread Younan Zhang via cfe-commits


@@ -253,6 +254,19 @@ bool Parser::ParseOptionalCXXScopeSpecifier(
 if (Type.isNull())
   return false;
 
+// C++ [cpp23.dcl.dcl-2]:
+//   Previously, T...[n] would declare a pack of function parameters.
+//   T...[n] is now a pack-index-specifier. [...] Valid C++ 2023 code that
+//   declares a pack of parameters without specifying a declarator-id
+//   becomes ill-formed.
+//
+// However, we still avoid parsing them as pack expansions because this is 
a
+// rare use case of packs, despite being partway non-conforming, to ensure
+// semantic consistency given that we have backported this feature.

zyn0217 wrote:

Good catch, fixed

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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-12 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> Seems that this change causes Segment Fault on multiple targets including 
> aarch64, loongarch64 and riscv64.
> 
> This is detected by a LoongArch 
> [buildbot](https://lab.llvm.org/staging/#/builders/20/builds/6282) and 
> manually checked on aarch64 and riscv64 QEMUs.
> 
> I wonder why aarch64 buildbot doesn't report this. I find that 
> `CMAKE_CXX_FLAGS_RELEASE` is empty on [aarch64 
> bot](https://lab.llvm.org/buildbot/#/builders/121/builds/614) while it is 
> `-O3 -DNDEBUG` on loongarch64. Is it an issue of the llvm-zorg framework?
> 
> UPDATE: This 
> [buildbot](https://lab.llvm.org/buildbot/#/builders/143)(aarch64) also fail 
> which uses `-O3`.
> 
> # Reproduce
> $ clang llvm-test-suite/SingleSource/Benchmarks/CoyoteBench/huffbench.c -O3 
> -o huffbench $ ./huffbench

Reproduced on Loongson-3A5000. I will provide a reduced test case later.


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


[clang] Fix a bug that CXXConstructExpr wasn't recognized by tryToFindPtrOrigin (PR #119336)

2024-12-12 Thread Rashmi Mudduluru via cfe-commits

https://github.com/t-rasmud approved this pull request.

Thanks for fixing the tests, LGTM!

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


  1   2   3   4   >