[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-07 Thread David Chisnall via cfe-commits

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

Looks good to me. It might be worth updating the test to make sure that one 
ivar is implicitly `@protected` if it isn’t already.

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


[clang] [clang][bytecode] Implement __builtin_operator{new,delete} (PR #107672)

2024-09-07 Thread Timm Baeder via cfe-commits

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

None

>From fbdde33e018a721bab026dcffb4af22987cc7366 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 7 Sep 2024 09:10:00 +0200
Subject: [PATCH] [clang][bytecode] Implement __builtin_operator{new,delete}

---
 clang/lib/AST/ByteCode/DynamicAllocator.cpp |  15 +-
 clang/lib/AST/ByteCode/DynamicAllocator.h   |  27 ++--
 clang/lib/AST/ByteCode/Interp.cpp   |  19 ++-
 clang/lib/AST/ByteCode/Interp.h |  32 ++--
 clang/lib/AST/ByteCode/InterpBuiltin.cpp| 160 
 clang/test/AST/ByteCode/new-delete.cpp  | 112 ++
 6 files changed, 334 insertions(+), 31 deletions(-)

diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp 
b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
index a5159977407805..819fbdb8b070bf 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
@@ -40,27 +40,30 @@ void DynamicAllocator::cleanup() {
 }
 
 Block *DynamicAllocator::allocate(const Expr *Source, PrimType T,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   Source, T, Descriptor::InlineDescMD, NumElements, /*IsConst=*/false,
   /*IsTemporary=*/false, /*IsMutable=*/false);
 
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
 Block *DynamicAllocator::allocate(const Descriptor *ElementDesc,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   ElementDesc->asExpr(), ElementDesc, Descriptor::InlineDescMD, 
NumElements,
   /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false);
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
-Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID) {
+Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID,
+  Form AllocForm) {
   assert(D);
   assert(D->asExpr());
 
@@ -84,7 +87,7 @@ Block *DynamicAllocator::allocate(const Descriptor *D, 
unsigned EvalID) {
 It->second.Allocations.emplace_back(std::move(Memory));
   else
 AllocationSites.insert(
-{D->asExpr(), AllocationSite(std::move(Memory), D->isArray())});
+{D->asExpr(), AllocationSite(std::move(Memory), AllocForm)});
   return B;
 }
 
diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.h 
b/clang/lib/AST/ByteCode/DynamicAllocator.h
index a84600aa54cc56..1ed5dc843e4c8c 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.h
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.h
@@ -31,6 +31,14 @@ class InterpState;
 /// For all array allocations, we need to allocate new Descriptor instances,
 /// so the DynamicAllocator has a llvm::BumpPtrAllocator similar to Program.
 class DynamicAllocator final {
+public:
+  enum class Form : uint8_t {
+NonArray,
+Array,
+Operator,
+  };
+
+private:
   struct Allocation {
 std::unique_ptr Memory;
 Allocation(std::unique_ptr Memory)
@@ -39,10 +47,10 @@ class DynamicAllocator final {
 
   struct AllocationSite {
 llvm::SmallVector Allocations;
-bool IsArrayAllocation = false;
+Form AllocForm;
 
-AllocationSite(std::unique_ptr Memory, bool Array)
-: IsArrayAllocation(Array) {
+AllocationSite(std::unique_ptr Memory, Form AllocForm)
+: AllocForm(AllocForm) {
   Allocations.push_back({std::move(Memory)});
 }
 
@@ -58,12 +66,13 @@ class DynamicAllocator final {
   unsigned getNumAllocations() const { return AllocationSites.size(); }
 
   /// Allocate ONE element of the given descriptor.
-  Block *allocate(const Descriptor *D, unsigned EvalID);
+  Block *allocate(const Descriptor *D, unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements primitive elements of the given type.
   Block *allocate(const Expr *Source, PrimType T, size_t NumElements,
-  unsigned EvalID);
+  unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements elements of the given descriptor.
-  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID);
+  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID,
+  Form AllocForm);
 
   /// Deallocate the given source+block combination.
   /// Returns \c true if anything has been deallocatd, \c false otherwise.
@@ -72,10 +81,10 @@ class DynamicAllocator final {
 
   /// Checks whether the allocation done at the given sour

[clang] [clang][bytecode] Implement __builtin_operator{new,delete} (PR #107672)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



---

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


6 Files Affected:

- (modified) clang/lib/AST/ByteCode/DynamicAllocator.cpp (+9-6) 
- (modified) clang/lib/AST/ByteCode/DynamicAllocator.h (+18-9) 
- (modified) clang/lib/AST/ByteCode/Interp.cpp (+14-5) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+21-11) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+160) 
- (modified) clang/test/AST/ByteCode/new-delete.cpp (+112) 


``diff
diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp 
b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
index a5159977407805..819fbdb8b070bf 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
@@ -40,27 +40,30 @@ void DynamicAllocator::cleanup() {
 }
 
 Block *DynamicAllocator::allocate(const Expr *Source, PrimType T,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   Source, T, Descriptor::InlineDescMD, NumElements, /*IsConst=*/false,
   /*IsTemporary=*/false, /*IsMutable=*/false);
 
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
 Block *DynamicAllocator::allocate(const Descriptor *ElementDesc,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   ElementDesc->asExpr(), ElementDesc, Descriptor::InlineDescMD, 
NumElements,
   /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false);
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
-Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID) {
+Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID,
+  Form AllocForm) {
   assert(D);
   assert(D->asExpr());
 
@@ -84,7 +87,7 @@ Block *DynamicAllocator::allocate(const Descriptor *D, 
unsigned EvalID) {
 It->second.Allocations.emplace_back(std::move(Memory));
   else
 AllocationSites.insert(
-{D->asExpr(), AllocationSite(std::move(Memory), D->isArray())});
+{D->asExpr(), AllocationSite(std::move(Memory), AllocForm)});
   return B;
 }
 
diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.h 
b/clang/lib/AST/ByteCode/DynamicAllocator.h
index a84600aa54cc56..1ed5dc843e4c8c 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.h
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.h
@@ -31,6 +31,14 @@ class InterpState;
 /// For all array allocations, we need to allocate new Descriptor instances,
 /// so the DynamicAllocator has a llvm::BumpPtrAllocator similar to Program.
 class DynamicAllocator final {
+public:
+  enum class Form : uint8_t {
+NonArray,
+Array,
+Operator,
+  };
+
+private:
   struct Allocation {
 std::unique_ptr Memory;
 Allocation(std::unique_ptr Memory)
@@ -39,10 +47,10 @@ class DynamicAllocator final {
 
   struct AllocationSite {
 llvm::SmallVector Allocations;
-bool IsArrayAllocation = false;
+Form AllocForm;
 
-AllocationSite(std::unique_ptr Memory, bool Array)
-: IsArrayAllocation(Array) {
+AllocationSite(std::unique_ptr Memory, Form AllocForm)
+: AllocForm(AllocForm) {
   Allocations.push_back({std::move(Memory)});
 }
 
@@ -58,12 +66,13 @@ class DynamicAllocator final {
   unsigned getNumAllocations() const { return AllocationSites.size(); }
 
   /// Allocate ONE element of the given descriptor.
-  Block *allocate(const Descriptor *D, unsigned EvalID);
+  Block *allocate(const Descriptor *D, unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements primitive elements of the given type.
   Block *allocate(const Expr *Source, PrimType T, size_t NumElements,
-  unsigned EvalID);
+  unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements elements of the given descriptor.
-  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID);
+  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID,
+  Form AllocForm);
 
   /// Deallocate the given source+block combination.
   /// Returns \c true if anything has been deallocatd, \c false otherwise.
@@ -72,10 +81,10 @@ class DynamicAllocator final {
 
   /// Checks whether the allocation done at the given source is an array
   /// allocation.
-  bool isArrayAllocation(const Expr *Source) const {
+  std::optional getAllocation

[clang] 83fea8b - [clang][bytecode] Allow continuing when discarded MemberExpr Base fails (#107231)

2024-09-07 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-09-07T09:33:27+02:00
New Revision: 83fea8b809b284594e6dd133150bb6d365775e5b

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

LOG: [clang][bytecode] Allow continuing when discarded MemberExpr Base fails 
(#107231)

We don't need the value in this case, since we're discarding it anyway.
Allow continuing the interpretation but note the side effect.

Added: 


Modified: 
clang/lib/AST/ByteCode/ByteCodeEmitter.h
clang/lib/AST/ByteCode/Compiler.cpp
clang/lib/AST/ByteCode/Compiler.h
clang/lib/AST/ByteCode/Context.cpp
clang/lib/AST/ByteCode/Context.h
clang/lib/AST/ByteCode/EvalEmitter.cpp
clang/lib/AST/ByteCode/EvalEmitter.h
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/InterpFrame.cpp
clang/lib/AST/ByteCode/InterpFrame.h
clang/lib/AST/ByteCode/InterpState.h
clang/lib/AST/ByteCode/Opcodes.td
clang/lib/AST/ByteCode/State.h
clang/lib/AST/ExprConstant.cpp
clang/test/AST/ByteCode/codegen.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/ByteCodeEmitter.h 
b/clang/lib/AST/ByteCode/ByteCodeEmitter.h
index 7cbbe651699b34..ac728830527a26 100644
--- a/clang/lib/AST/ByteCode/ByteCodeEmitter.h
+++ b/clang/lib/AST/ByteCode/ByteCodeEmitter.h
@@ -46,7 +46,7 @@ class ByteCodeEmitter {
 
   /// Methods implemented by the compiler.
   virtual bool visitFunc(const FunctionDecl *E) = 0;
-  virtual bool visitExpr(const Expr *E) = 0;
+  virtual bool visitExpr(const Expr *E, bool DestroyToplevelScope) = 0;
   virtual bool visitDeclAndReturn(const VarDecl *E, bool ConstantContext) = 0;
 
   /// Emits jumps.

diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 7d812301b6d36d..bada8621b9681f 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1874,8 +1874,12 @@ bool Compiler::VisitMemberExpr(const MemberExpr 
*E) {
 return false;
   }
 
-  if (!isa(Member))
-return this->discard(Base) && this->visitDeclRef(Member, E);
+  if (!isa(Member)) {
+if (!this->discard(Base) && !this->emitSideEffect(E))
+  return false;
+
+return this->visitDeclRef(Member, E);
+  }
 
   if (Initializing) {
 if (!this->delegate(Base))
@@ -2673,8 +2677,14 @@ bool Compiler::VisitCXXConstructExpr(const 
CXXConstructExpr *E) {
   if (!this->emitCallVar(Func, VarArgSize, E))
 return false;
 } else {
-  if (!this->emitCall(Func, 0, E))
+  if (!this->emitCall(Func, 0, E)) {
+// When discarding, we don't need the result anyway, so clean up
+// the instance dup we did earlier in case surrounding code wants
+// to keep evaluating.
+if (DiscardResult)
+  (void)this->emitPopPtr(E);
 return false;
+  }
 }
 
 if (DiscardResult)
@@ -3723,20 +3733,29 @@ const Function *Compiler::getFunction(const 
FunctionDecl *FD) {
   return Ctx.getOrCreateFunction(FD);
 }
 
-template  bool Compiler::visitExpr(const Expr *E) {
+template 
+bool Compiler::visitExpr(const Expr *E, bool DestroyToplevelScope) {
   LocalScope RootScope(this);
+
+  auto maybeDestroyLocals = [&]() -> bool {
+if (DestroyToplevelScope)
+  return RootScope.destroyLocals();
+return true;
+  };
+
   // Void expressions.
   if (E->getType()->isVoidType()) {
 if (!visit(E))
   return false;
-return this->emitRetVoid(E) && RootScope.destroyLocals();
+return this->emitRetVoid(E) && maybeDestroyLocals();
   }
 
   // Expressions with a primitive return type.
   if (std::optional T = classify(E)) {
 if (!visit(E))
   return false;
-return this->emitRet(*T, E) && RootScope.destroyLocals();
+
+return this->emitRet(*T, E) && maybeDestroyLocals();
   }
 
   // Expressions with a composite return type.
@@ -3754,10 +3773,10 @@ template  bool 
Compiler::visitExpr(const Expr *E) {
 // We are destroying the locals AFTER the Ret op.
 // The Ret op needs to copy the (alive) values, but the
 // destructors may still turn the entire expression invalid.
-return this->emitRetValue(E) && RootScope.destroyLocals();
+return this->emitRetValue(E) && maybeDestroyLocals();
   }
 
-  RootScope.destroyLocals();
+  (void)maybeDestroyLocals();
   return false;
 }
 

diff  --git a/clang/lib/AST/ByteCode/Compiler.h 
b/clang/lib/AST/ByteCode/Compiler.h
index e6f54fe05427b7..eb1252fec054bb 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -222,7 +222,7 @@ class Compiler : public ConstStmtVisitor, 
bool>,
 
 protected:
   bool visitStmt(const Stmt *S);
-  bool visitExpr(const Expr *E) override;
+  bool visitExpr(const Expr *E, bool DestroyToplevelScope) override;
   bool visitFunc(const FunctionDecl *

[clang] [clang][bytecode] Allow continuing when discarded MemberExpr Base fails (PR #107231)

2024-09-07 Thread Timm Baeder via cfe-commits

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


[clang] [-Wunsafe-buffer-usage] Warning Libc functions (PR #101583)

2024-09-07 Thread Björn Pettersson via cfe-commits

bjope wrote:


> > Is that as expected? If so, how should snprintf be used to avoid the 
> > warning?
> 
> Yes, this is expected. According to the C++ Safe Buffers programming model, 
> buffer pointers should be changed to std::span.

But this new warning is given also when compiling C code. As in the example 
from @mikaelholmen. So I doubt that the C++ programming model applies.

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


[clang] 610b853 - [clang][bytecode] Implement __builtin_operator{new,delete} (#107672)

2024-09-07 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-09-07T09:57:26+02:00
New Revision: 610b85395d233b5cbc5a1f112ac3039b888c0a88

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

LOG: [clang][bytecode] Implement __builtin_operator{new,delete} (#107672)

Added: 


Modified: 
clang/lib/AST/ByteCode/DynamicAllocator.cpp
clang/lib/AST/ByteCode/DynamicAllocator.h
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/test/AST/ByteCode/new-delete.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp 
b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
index a5159977407805..819fbdb8b070bf 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp
@@ -40,27 +40,30 @@ void DynamicAllocator::cleanup() {
 }
 
 Block *DynamicAllocator::allocate(const Expr *Source, PrimType T,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   Source, T, Descriptor::InlineDescMD, NumElements, /*IsConst=*/false,
   /*IsTemporary=*/false, /*IsMutable=*/false);
 
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
 Block *DynamicAllocator::allocate(const Descriptor *ElementDesc,
-  size_t NumElements, unsigned EvalID) {
+  size_t NumElements, unsigned EvalID,
+  Form AllocForm) {
   // Create a new descriptor for an array of the specified size and
   // element type.
   const Descriptor *D = allocateDescriptor(
   ElementDesc->asExpr(), ElementDesc, Descriptor::InlineDescMD, 
NumElements,
   /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false);
-  return allocate(D, EvalID);
+  return allocate(D, EvalID, AllocForm);
 }
 
-Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID) {
+Block *DynamicAllocator::allocate(const Descriptor *D, unsigned EvalID,
+  Form AllocForm) {
   assert(D);
   assert(D->asExpr());
 
@@ -84,7 +87,7 @@ Block *DynamicAllocator::allocate(const Descriptor *D, 
unsigned EvalID) {
 It->second.Allocations.emplace_back(std::move(Memory));
   else
 AllocationSites.insert(
-{D->asExpr(), AllocationSite(std::move(Memory), D->isArray())});
+{D->asExpr(), AllocationSite(std::move(Memory), AllocForm)});
   return B;
 }
 

diff  --git a/clang/lib/AST/ByteCode/DynamicAllocator.h 
b/clang/lib/AST/ByteCode/DynamicAllocator.h
index a84600aa54cc56..1ed5dc843e4c8c 100644
--- a/clang/lib/AST/ByteCode/DynamicAllocator.h
+++ b/clang/lib/AST/ByteCode/DynamicAllocator.h
@@ -31,6 +31,14 @@ class InterpState;
 /// For all array allocations, we need to allocate new Descriptor instances,
 /// so the DynamicAllocator has a llvm::BumpPtrAllocator similar to Program.
 class DynamicAllocator final {
+public:
+  enum class Form : uint8_t {
+NonArray,
+Array,
+Operator,
+  };
+
+private:
   struct Allocation {
 std::unique_ptr Memory;
 Allocation(std::unique_ptr Memory)
@@ -39,10 +47,10 @@ class DynamicAllocator final {
 
   struct AllocationSite {
 llvm::SmallVector Allocations;
-bool IsArrayAllocation = false;
+Form AllocForm;
 
-AllocationSite(std::unique_ptr Memory, bool Array)
-: IsArrayAllocation(Array) {
+AllocationSite(std::unique_ptr Memory, Form AllocForm)
+: AllocForm(AllocForm) {
   Allocations.push_back({std::move(Memory)});
 }
 
@@ -58,12 +66,13 @@ class DynamicAllocator final {
   unsigned getNumAllocations() const { return AllocationSites.size(); }
 
   /// Allocate ONE element of the given descriptor.
-  Block *allocate(const Descriptor *D, unsigned EvalID);
+  Block *allocate(const Descriptor *D, unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements primitive elements of the given type.
   Block *allocate(const Expr *Source, PrimType T, size_t NumElements,
-  unsigned EvalID);
+  unsigned EvalID, Form AllocForm);
   /// Allocate \p NumElements elements of the given descriptor.
-  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID);
+  Block *allocate(const Descriptor *D, size_t NumElements, unsigned EvalID,
+  Form AllocForm);
 
   /// Deallocate the given source+block combination.
   /// Returns \c true if anything has been deallocatd, \c false otherwise.
@@ -72,10 +81,10 @@ class DynamicAllocator final {
 
   /// Checks whether the allocation 

[clang] [clang][bytecode] Implement __builtin_operator{new,delete} (PR #107672)

2024-09-07 Thread Timm Baeder via cfe-commits

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


[clang] [libcxx] [Clang] Add __common_type builtin (PR #99473)

2024-09-07 Thread Nikolas Klauser via cfe-commits


@@ -0,0 +1,184 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -verify 
-std=c++17 %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -verify 
-std=c++20 %s
+
+#if !__has_builtin(__builtin_common_type)
+#  error
+#endif
+
+// expected-note@*:* {{template declaration from hidden source: template 
 class, template  class, class, class ...>}}
+
+void test() {
+  __builtin_common_type<> a; // expected-error {{too few template arguments 
for template '__builtin_common_type'}}
+}
+
+struct empty_type {};
+
+template 
+struct type_identity {
+  using type = T;
+};
+
+template 
+struct common_type;
+
+template 
+using common_type_t = typename common_type::type;
+
+template 
+using common_type_base = __builtin_common_type;
+
+template 
+struct common_type : common_type_base {};
+
+struct Incomplete;
+
+template<>
+struct common_type;
+
+static_assert(__is_same(common_type_base<>, empty_type));

philnik777 wrote:

`[[clang::annotate_type]]` doesn't seem to affect `__is_same`: 
https://godbolt.org/z/MznjrWMME. So I'm not sure I can test much with it.

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


[clang] [libcxx] [Clang] Add __common_type builtin (PR #99473)

2024-09-07 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/99473

>From d6903daf0da6979822b8981ea3641455ff6d06f8 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Tue, 16 Jul 2024 14:48:10 +0200
Subject: [PATCH 1/7] [Clang] Add __common_type builtin

---
 clang/include/clang/AST/ASTContext.h  |  11 ++
 clang/include/clang/AST/DeclID.h  |   5 +-
 clang/include/clang/Basic/Builtins.h  |   5 +-
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/AST/ASTContext.cpp  |   7 +
 clang/lib/AST/ASTImporter.cpp |   3 +
 clang/lib/AST/DeclTemplate.cpp|  53 ++
 clang/lib/Lex/PPMacroExpansion.cpp|   1 +
 clang/lib/Sema/SemaChecking.cpp   |   8 +
 clang/lib/Sema/SemaLookup.cpp |   4 +
 clang/lib/Sema/SemaTemplate.cpp   | 160 +-
 clang/lib/Serialization/ASTReader.cpp |   3 +
 clang/lib/Serialization/ASTWriter.cpp |   2 +
 clang/test/SemaCXX/type-trait-common-type.cpp | 126 ++
 libcxx/include/__type_traits/common_type.h|  16 +-
 libcxx/include/module.modulemap   |   2 +
 16 files changed, 404 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/SemaCXX/type-trait-common-type.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 608bd90fcc3ff9..d02e742297898c 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -399,6 +399,9 @@ class ASTContext : public RefCountedBase {
   /// The identifier '__type_pack_element'.
   mutable IdentifierInfo *TypePackElementName = nullptr;
 
+  /// The identifier '__common_type'.
+  mutable IdentifierInfo *CommonTypeName = nullptr;
+
   QualType ObjCConstantStringType;
   mutable RecordDecl *CFConstantStringTagDecl = nullptr;
   mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
@@ -606,6 +609,7 @@ class ASTContext : public RefCountedBase {
   mutable ExternCContextDecl *ExternCContext = nullptr;
   mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
   mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
+  mutable BuiltinTemplateDecl *CommonTypeDecl = nullptr;
 
   /// The associated SourceManager object.
   SourceManager &SourceMgr;
@@ -1107,6 +,7 @@ class ASTContext : public RefCountedBase {
   ExternCContextDecl *getExternCContextDecl() const;
   BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
   BuiltinTemplateDecl *getTypePackElementDecl() const;
+  BuiltinTemplateDecl *getCommonTypeDecl() const;
 
   // Builtin Types.
   CanQualType VoidTy;
@@ -1984,6 +1989,12 @@ class ASTContext : public RefCountedBase {
 return TypePackElementName;
   }
 
+  IdentifierInfo *getCommonTypeName() const {
+if (!CommonTypeName)
+  CommonTypeName = &Idents.get("__common_type");
+return CommonTypeName;
+  }
+
   /// Retrieve the Objective-C "instancetype" type, if already known;
   /// otherwise, returns a NULL type;
   QualType getObjCInstanceType() {
diff --git a/clang/include/clang/AST/DeclID.h b/clang/include/clang/AST/DeclID.h
index e5e27389fac60d..875e9a72b39512 100644
--- a/clang/include/clang/AST/DeclID.h
+++ b/clang/include/clang/AST/DeclID.h
@@ -84,13 +84,16 @@ enum PredefinedDeclIDs {
 
   /// The internal '__type_pack_element' template.
   PREDEF_DECL_TYPE_PACK_ELEMENT_ID = 17,
+
+  /// The internal '__common_type' template.
+  PREDEF_DECL_COMMON_TYPE_ID = 18,
 };
 
 /// The number of declaration IDs that are predefined.
 ///
 /// For more information about predefined declarations, see the
 /// \c PredefinedDeclIDs type and the PREDEF_DECL_*_ID constants.
-const unsigned int NUM_PREDEF_DECL_IDS = 18;
+const unsigned int NUM_PREDEF_DECL_IDS = 19;
 
 /// GlobalDeclID means DeclID in the current ASTContext and LocalDeclID means
 /// DeclID specific to a certain ModuleFile. Specially, in ASTWriter, the
diff --git a/clang/include/clang/Basic/Builtins.h 
b/clang/include/clang/Basic/Builtins.h
index e85ec5b2dca14e..4353b72f713838 100644
--- a/clang/include/clang/Basic/Builtins.h
+++ b/clang/include/clang/Basic/Builtins.h
@@ -309,7 +309,10 @@ enum BuiltinTemplateKind : int {
   BTK__make_integer_seq,
 
   /// This names the __type_pack_element BuiltinTemplateDecl.
-  BTK__type_pack_element
+  BTK__type_pack_element,
+
+  /// This names the __common_type BuiltinTemplateDecl.
+  BTK__common_type,
 };
 
 } // end namespace clang
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3cb1aa935fe461..5c7945c4c5c583 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2282,6 +2282,10 @@ class Sema final : public SemaBase {
   /// Check to see if a given expression could have '.c_str()' called on it.
   bool hasCStrMethod(const Expr *E);
 
+  // Check whether a type member 'Type::Name' exists, and if yes, return the
+  // type. If there is no type, the QualType is null
+  QualTy

[clang] [clang-format] Fix a bug in annotating CastRParen (PR #107675)

2024-09-07 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/107675

Fixes #107568.

>From 6deac871ceae8ba3918570a4bdbd8476e014a3a1 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 7 Sep 2024 01:39:34 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating CastRParen

Fixes #107568.
---
 clang/lib/Format/TokenAnnotator.cpp   | 29 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp |  6 
 2 files changed, 23 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6a1cf61659fd97..dfa703aed0d34d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2874,21 +2874,26 @@ class AnnotatingParser {
 if (Line.InPPDirective && AfterRParen->is(tok::minus))
   return false;
 
+const auto *Prev = BeforeRParen;
+
+// Look for a function pointer type, e.g. `(*)()`.
+if (Prev->is(tok::r_paren)) {
+  if (Prev->is(TT_CastRParen))
+return false;
+  Prev = Prev->MatchingParen;
+  if (!Prev)
+return false;
+  Prev = Prev->Previous;
+  if (!Prev || Prev->isNot(tok::r_paren))
+return false;
+  Prev = Prev->MatchingParen;
+  return Prev && Prev->is(TT_FunctionTypeLParen);
+}
+
 // Search for unexpected tokens.
-for (auto *Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous) {
-  if (Prev->is(tok::r_paren)) {
-if (Prev->is(TT_CastRParen))
-  return false;
-Prev = Prev->MatchingParen;
-if (!Prev)
-  return false;
-if (Prev->is(TT_FunctionTypeLParen))
-  break;
-continue;
-  }
+for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
   if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
 return false;
-}
 
 return true;
   }
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 1bb796fd6f5ee9..36a6db9283893e 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -775,6 +775,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
   EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_Unknown);
   EXPECT_TOKEN(Tokens[9], tok::minus, TT_BinaryOperator);
 
+  Tokens = annotate("return (double)(foo(30)) - 15;");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_CastRParen);
+  EXPECT_TOKEN(Tokens[9], tok::r_paren, TT_Unknown);
+  EXPECT_TOKEN(Tokens[10], tok::minus, TT_BinaryOperator);
+
   auto Style = getLLVMStyle();
   Style.TypeNames.push_back("Foo");
   Tokens = annotate("#define FOO(bar) foo((Foo)&bar)", Style);

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


[clang] [webkit.RefCntblBaseVirtualDtor] Make ThreadSafeRefCounted not generate warnings (PR #107676)

2024-09-07 Thread Ryosuke Niwa via cfe-commits

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

This PR makes WebKit's RefCntblBaseVirtualDtor checker not generate a warning 
for ThreadSafeRefCounted when the destruction thread is a specific thread.

Prior to this PR, we only allowed CRTP classes without a virtual destructor if 
its deref function had an explicit cast to the derived type, skipping any 
lambda declarations which aren't invoked. This ends up generating a warning for 
ThreadSafeRefCounted when a specific thread is used to destruct the object 
because there is no inline body / definition for ensureOnMainThread and 
ensureOnMainRunLoop and DerefFuncDeleteExprVisitor concludes that there is no 
explicit delete of the derived type.

This PR relaxes the condition DerefFuncDeleteExprVisitor checks by allowing a 
delete expression to appear within a lambda declaration if it's an argument to 
an "opaque" function; i.e. a function without definition / body.

>From 9a8c60355f88d7d4cee6d9f75312bb87d13b74a9 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 7 Sep 2024 01:45:05 -0700
Subject: [PATCH] [webkit.RefCntblBaseVirtualDtor] Make ThreadSafeRefCounted
 not generate warnings

This PR makes WebKit's RefCntblBaseVirtualDtor checker not generate a warning 
for
ThreadSafeRefCounted when the destruction thread is a specific thread.

Prior to this PR, we only allowed CRTP classes without a virtual destructor
if its deref function had an explicit cast to the derived type, skipping any
lambda declarations which aren't invoked. This ends up generating a warning for
ThreadSafeRefCounted when a specific thread is used to destruct the object
because there is no inline body / definition for ensureOnMainThread and
ensureOnMainRunLoop and DerefFuncDeleteExprVisitor concludes that there is no
explicit delete of the derived type.

This PR relaxes the condition DerefFuncDeleteExprVisitor checks by allowing
a delete expression to appear within a lambda declaration if it's an argument
to an "opaque" function; i.e. a function without definition / body.
---
 .../WebKit/RefCntblBaseVirtualDtorChecker.cpp |  22 +-
 .../ref-cntbl-crtp-base-no-virtual-dtor.cpp   | 232 ++
 2 files changed, 253 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8be..8e97efc1ab8e8e 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SetVector.h"
 #include 
 
@@ -67,6 +68,15 @@ class DerefFuncDeleteExprVisitor
 const Decl *D = CE->getCalleeDecl();
 if (D && D->hasBody())
   return VisitBody(D->getBody());
+else if (!VisitLambdaBody) {
+  for (unsigned i = 0; i < CE->getNumArgs(); ++i) {
+auto *Arg = CE->getArg(i);
+VisitLambdaBody = true;
+auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = false; });
+if (VisitChildren(Arg))
+  return true;
+  }
+}
 return false;
   }
 
@@ -113,12 +123,22 @@ class DerefFuncDeleteExprVisitor
 
   // Return false since the contents of lambda isn't necessarily executed.
   // If it is executed, VisitCallExpr above will visit its body.
-  bool VisitLambdaExpr(const LambdaExpr *) { return false; }
+  // Allow returning true for a lambda if it's a function argument to another
+  // function without body / definition.
+  bool VisitLambdaExpr(const LambdaExpr *E) {
+if (VisitLambdaBody) {
+  VisitLambdaBody = false;
+  auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = true; });
+  return VisitChildren(E);
+}
+return false;
+  }
 
 private:
   const TemplateArgumentList *ArgList{nullptr};
   const CXXRecordDecl *ClassDecl;
   llvm::DenseSet VisitedBody;
+  bool VisitLambdaBody{false};
 };
 
 class RefCntblBaseVirtualDtorChecker
diff --git 
a/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
new file mode 100644
index 00..e149c1d3d3575f
--- /dev/null
+++ 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
@@ -0,0 +1,232 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=webkit.RefCntblBaseVirtualDtor 
-verify %s
+
+#include "mock-types.h"
+
+namespace Detail {
+
+template
+class CallableWrapperBase {
+public:
+virtual ~CallableWrapperBase() { }
+virtual Out call(In...) = 0;
+};
+
+template class CallableWrapper;
+
+template
+class CallableWrapper : public CallableWrap

[clang] [clang-format] Fix a bug in annotating CastRParen (PR #107675)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixes #107568.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+17-12) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+6) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6a1cf61659fd97..dfa703aed0d34d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2874,21 +2874,26 @@ class AnnotatingParser {
 if (Line.InPPDirective && AfterRParen->is(tok::minus))
   return false;
 
+const auto *Prev = BeforeRParen;
+
+// Look for a function pointer type, e.g. `(*)()`.
+if (Prev->is(tok::r_paren)) {
+  if (Prev->is(TT_CastRParen))
+return false;
+  Prev = Prev->MatchingParen;
+  if (!Prev)
+return false;
+  Prev = Prev->Previous;
+  if (!Prev || Prev->isNot(tok::r_paren))
+return false;
+  Prev = Prev->MatchingParen;
+  return Prev && Prev->is(TT_FunctionTypeLParen);
+}
+
 // Search for unexpected tokens.
-for (auto *Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous) {
-  if (Prev->is(tok::r_paren)) {
-if (Prev->is(TT_CastRParen))
-  return false;
-Prev = Prev->MatchingParen;
-if (!Prev)
-  return false;
-if (Prev->is(TT_FunctionTypeLParen))
-  break;
-continue;
-  }
+for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
   if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
 return false;
-}
 
 return true;
   }
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 1bb796fd6f5ee9..36a6db9283893e 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -775,6 +775,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
   EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_Unknown);
   EXPECT_TOKEN(Tokens[9], tok::minus, TT_BinaryOperator);
 
+  Tokens = annotate("return (double)(foo(30)) - 15;");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_CastRParen);
+  EXPECT_TOKEN(Tokens[9], tok::r_paren, TT_Unknown);
+  EXPECT_TOKEN(Tokens[10], tok::minus, TT_BinaryOperator);
+
   auto Style = getLLVMStyle();
   Style.TypeNames.push_back("Foo");
   Tokens = annotate("#define FOO(bar) foo((Foo)&bar)", Style);

``




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


[clang] [webkit.RefCntblBaseVirtualDtor] Make ThreadSafeRefCounted not generate warnings (PR #107676)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

This PR makes WebKit's RefCntblBaseVirtualDtor checker not generate a warning 
for ThreadSafeRefCounted when the destruction thread is a specific thread.

Prior to this PR, we only allowed CRTP classes without a virtual destructor if 
its deref function had an explicit cast to the derived type, skipping any 
lambda declarations which aren't invoked. This ends up generating a warning for 
ThreadSafeRefCounted when a specific thread is used to destruct the object 
because there is no inline body / definition for ensureOnMainThread and 
ensureOnMainRunLoop and DerefFuncDeleteExprVisitor concludes that there is no 
explicit delete of the derived type.

This PR relaxes the condition DerefFuncDeleteExprVisitor checks by allowing a 
delete expression to appear within a lambda declaration if it's an argument to 
an "opaque" function; i.e. a function without definition / body.

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


2 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
(+21-1) 
- (added) 
clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp 
(+232) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8be..8e97efc1ab8e8e 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SetVector.h"
 #include 
 
@@ -67,6 +68,15 @@ class DerefFuncDeleteExprVisitor
 const Decl *D = CE->getCalleeDecl();
 if (D && D->hasBody())
   return VisitBody(D->getBody());
+else if (!VisitLambdaBody) {
+  for (unsigned i = 0; i < CE->getNumArgs(); ++i) {
+auto *Arg = CE->getArg(i);
+VisitLambdaBody = true;
+auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = false; });
+if (VisitChildren(Arg))
+  return true;
+  }
+}
 return false;
   }
 
@@ -113,12 +123,22 @@ class DerefFuncDeleteExprVisitor
 
   // Return false since the contents of lambda isn't necessarily executed.
   // If it is executed, VisitCallExpr above will visit its body.
-  bool VisitLambdaExpr(const LambdaExpr *) { return false; }
+  // Allow returning true for a lambda if it's a function argument to another
+  // function without body / definition.
+  bool VisitLambdaExpr(const LambdaExpr *E) {
+if (VisitLambdaBody) {
+  VisitLambdaBody = false;
+  auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = true; });
+  return VisitChildren(E);
+}
+return false;
+  }
 
 private:
   const TemplateArgumentList *ArgList{nullptr};
   const CXXRecordDecl *ClassDecl;
   llvm::DenseSet VisitedBody;
+  bool VisitLambdaBody{false};
 };
 
 class RefCntblBaseVirtualDtorChecker
diff --git 
a/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
new file mode 100644
index 00..e149c1d3d3575f
--- /dev/null
+++ 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
@@ -0,0 +1,232 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=webkit.RefCntblBaseVirtualDtor 
-verify %s
+
+#include "mock-types.h"
+
+namespace Detail {
+
+template
+class CallableWrapperBase {
+public:
+virtual ~CallableWrapperBase() { }
+virtual Out call(In...) = 0;
+};
+
+template class CallableWrapper;
+
+template
+class CallableWrapper : public CallableWrapperBase {
+public:
+explicit CallableWrapper(CallableType&& callable)
+: m_callable(WTFMove(callable)) { }
+CallableWrapper(const CallableWrapper&) = delete;
+CallableWrapper& operator=(const CallableWrapper&) = delete;
+Out call(In... in) final;
+private:
+CallableType m_callable;
+};
+
+} // namespace Detail
+
+template class Function;
+
+template Function 
adopt(Detail::CallableWrapperBase*);
+
+template 
+class Function {
+public:
+using Impl = Detail::CallableWrapperBase;
+
+Function() = default;
+
+template
+Function(FunctionType f);
+
+Out operator()(In... in) const;
+explicit operator bool() const { return !!m_callableWrapper; }
+
+private:
+enum AdoptTag { Adopt };
+Function(Impl* impl, AdoptTag)
+: m_callableWrapper(impl)
+{
+}
+
+friend Function adopt(Impl*);
+
+Impl* m_callableWrapper;
+};
+
+template Function 
adopt(Detail::CallableWrapperBase* impl)
+{
+return Function(impl, Function::Adopt);
+}
+
+template, typename 
RefDerefTraits = DefaultRefDerefTraits> Ref

[clang] [webkit.RefCntblBaseVirtualDtor] Make ThreadSafeRefCounted not generate warnings (PR #107676)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes

This PR makes WebKit's RefCntblBaseVirtualDtor checker not generate a warning 
for ThreadSafeRefCounted when the destruction thread is a specific thread.

Prior to this PR, we only allowed CRTP classes without a virtual destructor if 
its deref function had an explicit cast to the derived type, skipping any 
lambda declarations which aren't invoked. This ends up generating a warning for 
ThreadSafeRefCounted when a specific thread is used to destruct the object 
because there is no inline body / definition for ensureOnMainThread and 
ensureOnMainRunLoop and DerefFuncDeleteExprVisitor concludes that there is no 
explicit delete of the derived type.

This PR relaxes the condition DerefFuncDeleteExprVisitor checks by allowing a 
delete expression to appear within a lambda declaration if it's an argument to 
an "opaque" function; i.e. a function without definition / body.

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


2 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
(+21-1) 
- (added) 
clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp 
(+232) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8be..8e97efc1ab8e8e 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SetVector.h"
 #include 
 
@@ -67,6 +68,15 @@ class DerefFuncDeleteExprVisitor
 const Decl *D = CE->getCalleeDecl();
 if (D && D->hasBody())
   return VisitBody(D->getBody());
+else if (!VisitLambdaBody) {
+  for (unsigned i = 0; i < CE->getNumArgs(); ++i) {
+auto *Arg = CE->getArg(i);
+VisitLambdaBody = true;
+auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = false; });
+if (VisitChildren(Arg))
+  return true;
+  }
+}
 return false;
   }
 
@@ -113,12 +123,22 @@ class DerefFuncDeleteExprVisitor
 
   // Return false since the contents of lambda isn't necessarily executed.
   // If it is executed, VisitCallExpr above will visit its body.
-  bool VisitLambdaExpr(const LambdaExpr *) { return false; }
+  // Allow returning true for a lambda if it's a function argument to another
+  // function without body / definition.
+  bool VisitLambdaExpr(const LambdaExpr *E) {
+if (VisitLambdaBody) {
+  VisitLambdaBody = false;
+  auto Restore = llvm::make_scope_exit([&] { VisitLambdaBody = true; });
+  return VisitChildren(E);
+}
+return false;
+  }
 
 private:
   const TemplateArgumentList *ArgList{nullptr};
   const CXXRecordDecl *ClassDecl;
   llvm::DenseSet VisitedBody;
+  bool VisitLambdaBody{false};
 };
 
 class RefCntblBaseVirtualDtorChecker
diff --git 
a/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
new file mode 100644
index 00..e149c1d3d3575f
--- /dev/null
+++ 
b/clang/test/Analysis/Checkers/WebKit/ref-cntbl-crtp-base-no-virtual-dtor.cpp
@@ -0,0 +1,232 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=webkit.RefCntblBaseVirtualDtor 
-verify %s
+
+#include "mock-types.h"
+
+namespace Detail {
+
+template
+class CallableWrapperBase {
+public:
+virtual ~CallableWrapperBase() { }
+virtual Out call(In...) = 0;
+};
+
+template class CallableWrapper;
+
+template
+class CallableWrapper : public CallableWrapperBase {
+public:
+explicit CallableWrapper(CallableType&& callable)
+: m_callable(WTFMove(callable)) { }
+CallableWrapper(const CallableWrapper&) = delete;
+CallableWrapper& operator=(const CallableWrapper&) = delete;
+Out call(In... in) final;
+private:
+CallableType m_callable;
+};
+
+} // namespace Detail
+
+template class Function;
+
+template Function 
adopt(Detail::CallableWrapperBase*);
+
+template 
+class Function {
+public:
+using Impl = Detail::CallableWrapperBase;
+
+Function() = default;
+
+template
+Function(FunctionType f);
+
+Out operator()(In... in) const;
+explicit operator bool() const { return !!m_callableWrapper; }
+
+private:
+enum AdoptTag { Adopt };
+Function(Impl* impl, AdoptTag)
+: m_callableWrapper(impl)
+{
+}
+
+friend Function adopt(Impl*);
+
+Impl* m_callableWrapper;
+};
+
+template Function 
adopt(Detail::CallableWrapperBase* impl)
+{
+return Function(impl, Function::Adopt);
+}
+
+template, typename 
RefDerefTraits = DefaultR

[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits

https://github.com/yronglin created 
https://github.com/llvm/llvm-project/pull/107678

Implement `&&`, `||` logical operators for vector type.

>From b9da0771d479fe5384f6e83bb1e2b75cd48fd5b4 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 7 Sep 2024 16:53:12 +0800
Subject: [PATCH] [clang][bytecode] Implement logical operators for vector type

Signed-off-by: yronglin 
---
 clang/lib/AST/ByteCode/Compiler.cpp   | 23 -
 clang/test/AST/ByteCode/constexpr-vectors.cpp | 90 +++
 2 files changed, 111 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index eea77c2f0a9bb4..0dd690a69dca71 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -15,6 +15,7 @@
 #include "PrimType.h"
 #include "Program.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/OperationKinds.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -1232,7 +1233,7 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
 
   // FIXME: Current only support comparison binary operator, add support for
   // other binary operator.
-  if (!E->isComparisonOp())
+  if (!E->isComparisonOp() && !E->isLogicalOp())
 return this->emitInvalid(E);
   // Prepare storage for result.
   if (!Initializing) {
@@ -1267,7 +1268,15 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   auto getElem = [=](unsigned Offset, unsigned Index) {
 if (!this->emitGetLocal(PT_Ptr, Offset, E))
   return false;
-return this->emitArrayElemPop(ElemT, Index, E);
+if (!this->emitArrayElemPop(ElemT, Index, E))
+  return false;
+if (E->isLogicalOp()) {
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), 
E))
+return false;
+}
+return true;
   };
 
   for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
@@ -1300,6 +1309,16 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   if (!this->emitGT(ElemT, E))
 return false;
   break;
+case BO_LAnd:
+  // a && b is equivalent to a!=0 & b!=0
+  if (!this->emitBitAnd(ResultElemT, E))
+return false;
+  break;
+case BO_LOr:
+  // a || b is equivalent to a!=0 | b!=0
+  if (!this->emitBitOr(ResultElemT, E))
+return false;
+  break;
 default:
   llvm_unreachable("Unsupported binary operator");
 }
diff --git a/clang/test/AST/ByteCode/constexpr-vectors.cpp 
b/clang/test/AST/ByteCode/constexpr-vectors.cpp
index 684c5810702cc3..7a65b263784586 100644
--- a/clang/test/AST/ByteCode/constexpr-vectors.cpp
+++ b/clang/test/AST/ByteCode/constexpr-vectors.cpp
@@ -57,6 +57,20 @@ void CharUsage() {
   constexpr auto H = FourCharsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsVecSize{5, 0, 6, 0} &&
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsVecSize{5, 0, 6, 0} ||
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsVecSize{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsVecSize{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
   constexpr auto H1 = FourCharsVecSize{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -111,6 +125,21 @@ void CharExtVecUsage() {
   constexpr auto H = FourCharsExtVec{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsExtVec{5, 0, 6, 0} &&
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsExtVec{5, 0, 6, 0} ||
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsExtVec{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsExtVec{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
+
   constexpr auto H1 = FourCharsExtVec{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -165,10 +194,33 @@ void FloatUsage() {
   constexpr auto H = FourFloatsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O1 = FourFloatsVecSize{5, 0, 6, 0} &&
+ FourFloatsVecSize{5, 5, 0, 0};
+  

[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (yronglin)


Changes

Implement `&&`, `||` logical operators for vector type.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+21-2) 
- (modified) clang/test/AST/ByteCode/constexpr-vectors.cpp (+90) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index eea77c2f0a9bb4..0dd690a69dca71 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -15,6 +15,7 @@
 #include "PrimType.h"
 #include "Program.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/OperationKinds.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -1232,7 +1233,7 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
 
   // FIXME: Current only support comparison binary operator, add support for
   // other binary operator.
-  if (!E->isComparisonOp())
+  if (!E->isComparisonOp() && !E->isLogicalOp())
 return this->emitInvalid(E);
   // Prepare storage for result.
   if (!Initializing) {
@@ -1267,7 +1268,15 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   auto getElem = [=](unsigned Offset, unsigned Index) {
 if (!this->emitGetLocal(PT_Ptr, Offset, E))
   return false;
-return this->emitArrayElemPop(ElemT, Index, E);
+if (!this->emitArrayElemPop(ElemT, Index, E))
+  return false;
+if (E->isLogicalOp()) {
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), 
E))
+return false;
+}
+return true;
   };
 
   for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
@@ -1300,6 +1309,16 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   if (!this->emitGT(ElemT, E))
 return false;
   break;
+case BO_LAnd:
+  // a && b is equivalent to a!=0 & b!=0
+  if (!this->emitBitAnd(ResultElemT, E))
+return false;
+  break;
+case BO_LOr:
+  // a || b is equivalent to a!=0 | b!=0
+  if (!this->emitBitOr(ResultElemT, E))
+return false;
+  break;
 default:
   llvm_unreachable("Unsupported binary operator");
 }
diff --git a/clang/test/AST/ByteCode/constexpr-vectors.cpp 
b/clang/test/AST/ByteCode/constexpr-vectors.cpp
index 684c5810702cc3..7a65b263784586 100644
--- a/clang/test/AST/ByteCode/constexpr-vectors.cpp
+++ b/clang/test/AST/ByteCode/constexpr-vectors.cpp
@@ -57,6 +57,20 @@ void CharUsage() {
   constexpr auto H = FourCharsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsVecSize{5, 0, 6, 0} &&
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsVecSize{5, 0, 6, 0} ||
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsVecSize{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsVecSize{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
   constexpr auto H1 = FourCharsVecSize{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -111,6 +125,21 @@ void CharExtVecUsage() {
   constexpr auto H = FourCharsExtVec{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsExtVec{5, 0, 6, 0} &&
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsExtVec{5, 0, 6, 0} ||
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsExtVec{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsExtVec{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
+
   constexpr auto H1 = FourCharsExtVec{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -165,10 +194,33 @@ void FloatUsage() {
   constexpr auto H = FourFloatsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O1 = FourFloatsVecSize{5, 0, 6, 0} &&
+ FourFloatsVecSize{5, 5, 0, 0};
+  static_assert(O1[0] == 1 && O1[1] == 0 && O1[2] == 0 && O1[3] == 0, "");
+
+  constexpr auto P1 = FourFloatsVecSize{5, 0, 6, 0} ||
+ FourFloatsVecSize{5, 5, 0, 0};
+  stat

[clang] [clang][bytecode] Implement using operator new/operator delete (PR #107679)

2024-09-07 Thread Timm Baeder via cfe-commits

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

Reuse the __builtin_operator_{new,delete} implementations.

>From 654bc52d1e947d52942878a6a50c73053814d565 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 7 Sep 2024 10:52:40 +0200
Subject: [PATCH] [clang][bytecode] Implement using operator new/operator
 delete

Reuse the __builtin_operator_{new,delete} implementations.
---
 clang/lib/AST/ByteCode/Compiler.cpp  | 31 
 clang/lib/AST/ByteCode/Compiler.h|  2 +-
 clang/lib/AST/ByteCode/Interp.cpp|  4 +--
 clang/lib/AST/ByteCode/Interp.h  |  4 +--
 clang/lib/AST/ByteCode/InterpBuiltin.cpp |  4 +--
 clang/lib/AST/ByteCode/Opcodes.td|  2 +-
 clang/test/AST/ByteCode/new-delete.cpp   | 14 +++
 7 files changed, 43 insertions(+), 18 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index bada8621b9681f..115b0aa7dd29c9 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -4070,18 +4070,18 @@ bool Compiler::visitAPValueInitializer(const 
APValue &Val,
 }
 
 template 
-bool Compiler::VisitBuiltinCallExpr(const CallExpr *E) {
+bool Compiler::VisitBuiltinCallExpr(const CallExpr *E,
+ unsigned BuiltinID) {
   const Function *Func = getFunction(E->getDirectCallee());
   if (!Func)
 return false;
 
   // For these, we're expected to ultimately return an APValue pointing
   // to the CallExpr. This is needed to get the correct codegen.
-  unsigned Builtin = E->getBuiltinCallee();
-  if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
-  Builtin == Builtin::BI__builtin_function_start) {
+  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
+  BuiltinID == Builtin::BI__builtin_function_start) {
 if (std::optional GlobalOffset = P.createGlobal(E)) {
   if (!this->emitGetPtrGlobal(*GlobalOffset, E))
 return false;
@@ -4113,7 +4113,7 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 }
   }
 
-  if (!this->emitCallBI(Func, E, E))
+  if (!this->emitCallBI(Func, E, BuiltinID, E))
 return false;
 
   if (DiscardResult && !ReturnType->isVoidType()) {
@@ -4126,13 +4126,24 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 
 template 
 bool Compiler::VisitCallExpr(const CallExpr *E) {
-  if (E->getBuiltinCallee())
-return VisitBuiltinCallExpr(E);
+  if (unsigned BuiltinID = E->getBuiltinCallee())
+return VisitBuiltinCallExpr(E, BuiltinID);
+
+  const FunctionDecl *FuncDecl = E->getDirectCallee();
+  // Calls to replaceable operator new/operator delete.
+  if (FuncDecl && FuncDecl->isReplaceableGlobalAllocationFunction()) {
+if (FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_New ||
+FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
+} else {
+  assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
+}
+  }
 
   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
   std::optional T = classify(ReturnType);
   bool HasRVO = !ReturnType->isVoidType() && !T;
-  const FunctionDecl *FuncDecl = E->getDirectCallee();
 
   if (HasRVO) {
 if (DiscardResult) {
diff --git a/clang/lib/AST/ByteCode/Compiler.h 
b/clang/lib/AST/ByteCode/Compiler.h
index eb1252fec054bb..39c0736cb4e27e 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -133,7 +133,7 @@ class Compiler : public ConstStmtVisitor, 
bool>,
   bool VisitVectorBinOp(const BinaryOperator *E);
   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E);
   bool VisitCallExpr(const CallExpr *E);
-  bool VisitBuiltinCallExpr(const CallExpr *E);
+  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID);
   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E);
   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 99d01ca52645e0..ac02bd6d033487 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -1178,7 +1178,7 @@ bool CallVirt(InterpState &S, CodePtr OpPC, const 
Function *Func,
 }
 
 bool CallBI(InterpState &S, CodePtr &PC, const Function *Func,
-const CallExpr *CE) {
+const CallExpr *CE, uint32_t BuiltinID) {
   if (S.checkingPotentialConstantExpression())
   

[clang] [clang][bytecode] Implement using operator new/operator delete (PR #107679)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Reuse the __builtin_operator_{new,delete} implementations.

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


7 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+21-10) 
- (modified) clang/lib/AST/ByteCode/Compiler.h (+1-1) 
- (modified) clang/lib/AST/ByteCode/Interp.cpp (+2-2) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+2-2) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+2-2) 
- (modified) clang/lib/AST/ByteCode/Opcodes.td (+1-1) 
- (modified) clang/test/AST/ByteCode/new-delete.cpp (+14) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index bada8621b9681f..115b0aa7dd29c9 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -4070,18 +4070,18 @@ bool Compiler::visitAPValueInitializer(const 
APValue &Val,
 }
 
 template 
-bool Compiler::VisitBuiltinCallExpr(const CallExpr *E) {
+bool Compiler::VisitBuiltinCallExpr(const CallExpr *E,
+ unsigned BuiltinID) {
   const Function *Func = getFunction(E->getDirectCallee());
   if (!Func)
 return false;
 
   // For these, we're expected to ultimately return an APValue pointing
   // to the CallExpr. This is needed to get the correct codegen.
-  unsigned Builtin = E->getBuiltinCallee();
-  if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
-  Builtin == Builtin::BI__builtin_function_start) {
+  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
+  BuiltinID == Builtin::BI__builtin_function_start) {
 if (std::optional GlobalOffset = P.createGlobal(E)) {
   if (!this->emitGetPtrGlobal(*GlobalOffset, E))
 return false;
@@ -4113,7 +4113,7 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 }
   }
 
-  if (!this->emitCallBI(Func, E, E))
+  if (!this->emitCallBI(Func, E, BuiltinID, E))
 return false;
 
   if (DiscardResult && !ReturnType->isVoidType()) {
@@ -4126,13 +4126,24 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 
 template 
 bool Compiler::VisitCallExpr(const CallExpr *E) {
-  if (E->getBuiltinCallee())
-return VisitBuiltinCallExpr(E);
+  if (unsigned BuiltinID = E->getBuiltinCallee())
+return VisitBuiltinCallExpr(E, BuiltinID);
+
+  const FunctionDecl *FuncDecl = E->getDirectCallee();
+  // Calls to replaceable operator new/operator delete.
+  if (FuncDecl && FuncDecl->isReplaceableGlobalAllocationFunction()) {
+if (FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_New ||
+FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
+} else {
+  assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
+}
+  }
 
   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
   std::optional T = classify(ReturnType);
   bool HasRVO = !ReturnType->isVoidType() && !T;
-  const FunctionDecl *FuncDecl = E->getDirectCallee();
 
   if (HasRVO) {
 if (DiscardResult) {
diff --git a/clang/lib/AST/ByteCode/Compiler.h 
b/clang/lib/AST/ByteCode/Compiler.h
index eb1252fec054bb..39c0736cb4e27e 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -133,7 +133,7 @@ class Compiler : public ConstStmtVisitor, 
bool>,
   bool VisitVectorBinOp(const BinaryOperator *E);
   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E);
   bool VisitCallExpr(const CallExpr *E);
-  bool VisitBuiltinCallExpr(const CallExpr *E);
+  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID);
   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E);
   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 99d01ca52645e0..ac02bd6d033487 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -1178,7 +1178,7 @@ bool CallVirt(InterpState &S, CodePtr OpPC, const 
Function *Func,
 }
 
 bool CallBI(InterpState &S, CodePtr &PC, const Function *Func,
-const CallExpr *CE) {
+const CallExpr *CE, uint32_t BuiltinID) {
   if (S.checkingPotentialConstantExpression())
 return false;
   auto NewFrame = std::make_unique(S, Func, PC);
@@ -1186,7 +1186,7 @@ bool CallBI(InterpState &S, CodePtr &PC, const Function 
*Func,
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get(

[clang] 7d4afba - [clang][bytecode][NFC] Fix Function::getName() for non-decl functions

2024-09-07 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-09-07T10:56:18+02:00
New Revision: 7d4afba831bcf9b3e50ee7b6a3fbc9c0a7c61597

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

LOG: [clang][bytecode][NFC] Fix Function::getName() for non-decl functions

Added: 


Modified: 
clang/lib/AST/ByteCode/Function.h

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Function.h 
b/clang/lib/AST/ByteCode/Function.h
index b21fa8497130ea..640bfa65644f0f 100644
--- a/clang/lib/AST/ByteCode/Function.h
+++ b/clang/lib/AST/ByteCode/Function.h
@@ -103,10 +103,10 @@ class Function final {
   /// Returns the name of the function decl this code
   /// was generated for.
   const std::string getName() const {
-if (!Source)
+if (!Source || !getDecl())
   return "<>";
 
-return Source.get()->getQualifiedNameAsString();
+return getDecl()->getQualifiedNameAsString();
   }
 
   /// Returns a parameter descriptor.



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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-09-07 Thread via cfe-commits


@@ -1917,6 +1929,16 @@ APValue &CallStackFrame::createTemporary(const KeyT 
*Key, QualType T,
   return createLocal(Base, Key, T, Scope);
 }
 
+APValue &
+CallStackFrame::createConstexprUnknownAPValues(const VarDecl *Key,
+   APValue::LValueBase Base) {
+  APValue &Result = ConstexprUnknownAPValues[MapKeyTy(Key, Base.getVersion())];
+  Result = APValue(Base, APValue::ConstexprUnknown{}, CharUnits::One());
+  Result.setConstexprUnknown();

cor3ntin wrote:

Yesm i think it can just be removed

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-09-07 Thread via cfe-commits

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-09-07 Thread via cfe-commits

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread Timm Baeder via cfe-commits


@@ -1267,7 +1268,15 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   auto getElem = [=](unsigned Offset, unsigned Index) {
 if (!this->emitGetLocal(PT_Ptr, Offset, E))
   return false;
-return this->emitArrayElemPop(ElemT, Index, E);
+if (!this->emitArrayElemPop(ElemT, Index, E))
+  return false;
+if (E->isLogicalOp()) {
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), 
E))
+return false;
+}

tbaederr wrote:

I hate the double cast, but I have no better idea either :/

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread Timm Baeder via cfe-commits


@@ -1300,6 +1309,16 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   if (!this->emitGT(ElemT, E))
 return false;
   break;
+case BO_LAnd:
+  // a && b is equivalent to a!=0 & b!=0

tbaederr wrote:

I was trying to prove this wrong but it's really what the current interpreter 
does. Since the vector isn't implicitly convertible to bool, there's no 
short-circuiting: https://godbolt.org/z/aaoTPWcKo

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread Timm Baeder via cfe-commits


@@ -15,6 +15,7 @@
 #include "PrimType.h"
 #include "Program.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/OperationKinds.h"

tbaederr wrote:

What is this needed for? A call to `isLogicalOp()` was already in the file 
before.

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


[clang] [clang] Remove an incorrect assertion in ConstantFoldAttrs (PR #105789)

2024-09-07 Thread Timm Baeder via cfe-commits

tbaederr wrote:

CC @AaronBallman for an opinion about the AST represenation

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


[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/107604

>From 64073399d392b187297a6aeb1c6634c271103330 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Fri, 6 Sep 2024 11:54:59 +
Subject: [PATCH 1/2] Set dllimport on Objective C ivar offsets

This commit ensures that offsets for instance variables are marked with 
`dllimport` if the interface to which they belong have this attribute.
---
 clang/lib/CodeGen/CGObjCGNU.cpp | 11 +--
 clang/test/CodeGenObjC/dllstorage.m |  4 ++--
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index adc7cdbfded880..6280e9465ecba6 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -1699,11 +1699,18 @@ class CGObjCGNUstep2 : public CGObjCGNUstep {
   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
   const ObjCInterfaceDecl *Interface,
   const ObjCIvarDecl *Ivar) override {
-const std::string Name = 
GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
+const ObjCInterfaceDecl *ContainingInterface =
+Ivar->getContainingInterface();
+const std::string Name =
+GetIVarOffsetVariableName(ContainingInterface, Ivar);
 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
-if (!IvarOffsetPointer)
+if (!IvarOffsetPointer) {
   IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
   llvm::GlobalValue::ExternalLinkage, nullptr, Name);
+  if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&
+  Ivar->getAccessControl() != ObjCIvarDecl::Package)
+CGM.setGVProperties(IvarOffsetPointer, ContainingInterface);
+}
 CharUnits Align = CGM.getIntAlign();
 llvm::Value *Offset =
 CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
diff --git a/clang/test/CodeGenObjC/dllstorage.m 
b/clang/test/CodeGenObjC/dllstorage.m
index c94f4c9b5804d0..a6c591b2d79302 100644
--- a/clang/test/CodeGenObjC/dllstorage.m
+++ b/clang/test/CodeGenObjC/dllstorage.m
@@ -112,7 +112,7 @@ @interface M : I {
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
 // CHECK-NF-DAG: @"$_OBJC_REF_CLASS_M" = external dllimport global ptr
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 __declspec(dllexport)
 __attribute__((__objc_exception__))
@@ -151,7 +151,7 @@ id f(Q *q) {
 
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 int g(void) {
   @autoreleasepool {

>From cf93b21734e179144dac34751860b0aa9d2aedaa Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Sat, 7 Sep 2024 03:00:46 -0700
Subject: [PATCH 2/2] Add tests to ensure unmarked instance variables are
 considered protected

---
 clang/test/SemaObjC/ivar-access-tests.m | 10 ++
 1 file changed, 10 insertions(+)

diff --git a/clang/test/SemaObjC/ivar-access-tests.m 
b/clang/test/SemaObjC/ivar-access-tests.m
index cd7e09d406adaa..6060dea5ab0f0e 100644
--- a/clang/test/SemaObjC/ivar-access-tests.m
+++ b/clang/test/SemaObjC/ivar-access-tests.m
@@ -2,6 +2,8 @@
 
 @interface MySuperClass
 {
+  int unmarked;
+
 @private
   int private;
 
@@ -17,6 +19,7 @@ @implementation MySuperClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private;   
 access = s->protected;
 }
@@ -30,9 +33,11 @@ @implementation MyClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -46,9 +51,11 @@ @implementation Deeper
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -61,9 +68,11 @@ @implementation Unrelated
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked; // expected-error {{instance variable 'unmarked' is 
protected}}
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected; // expected-error {{instance variable 'protected' 
is protected}}
 MyClass *m=0;
+access = m->unmarked; // expected-error {{instance v

[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-07 Thread Frederik Carlier via cfe-commits

qmfrederik wrote:

I've added tests to ensure that unmarked ivars are considered protected -- 
which seems to be the case: 
https://github.com/llvm/llvm-project/pull/107604/commits/cf93b21734e179144dac34751860b0aa9d2aedaa
 

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


[clang] 78cf9b8 - [clang][bytecode] Implement using operator new/operator delete (#107679)

2024-09-07 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-09-07T12:17:54+02:00
New Revision: 78cf9b830c78daa5aed51b5ca77bb7db9974d1ec

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

LOG: [clang][bytecode] Implement using operator new/operator delete (#107679)

Reuse the __builtin_operator_{new,delete} implementations.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/lib/AST/ByteCode/Compiler.h
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/lib/AST/ByteCode/Opcodes.td
clang/test/AST/ByteCode/new-delete.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index bada8621b9681f..115b0aa7dd29c9 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -4070,18 +4070,18 @@ bool Compiler::visitAPValueInitializer(const 
APValue &Val,
 }
 
 template 
-bool Compiler::VisitBuiltinCallExpr(const CallExpr *E) {
+bool Compiler::VisitBuiltinCallExpr(const CallExpr *E,
+ unsigned BuiltinID) {
   const Function *Func = getFunction(E->getDirectCallee());
   if (!Func)
 return false;
 
   // For these, we're expected to ultimately return an APValue pointing
   // to the CallExpr. This is needed to get the correct codegen.
-  unsigned Builtin = E->getBuiltinCallee();
-  if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
-  Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
-  Builtin == Builtin::BI__builtin_function_start) {
+  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
+  BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
+  BuiltinID == Builtin::BI__builtin_function_start) {
 if (std::optional GlobalOffset = P.createGlobal(E)) {
   if (!this->emitGetPtrGlobal(*GlobalOffset, E))
 return false;
@@ -4113,7 +4113,7 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 }
   }
 
-  if (!this->emitCallBI(Func, E, E))
+  if (!this->emitCallBI(Func, E, BuiltinID, E))
 return false;
 
   if (DiscardResult && !ReturnType->isVoidType()) {
@@ -4126,13 +4126,24 @@ bool Compiler::VisitBuiltinCallExpr(const 
CallExpr *E) {
 
 template 
 bool Compiler::VisitCallExpr(const CallExpr *E) {
-  if (E->getBuiltinCallee())
-return VisitBuiltinCallExpr(E);
+  if (unsigned BuiltinID = E->getBuiltinCallee())
+return VisitBuiltinCallExpr(E, BuiltinID);
+
+  const FunctionDecl *FuncDecl = E->getDirectCallee();
+  // Calls to replaceable operator new/operator delete.
+  if (FuncDecl && FuncDecl->isReplaceableGlobalAllocationFunction()) {
+if (FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_New ||
+FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
+} else {
+  assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
+  return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
+}
+  }
 
   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
   std::optional T = classify(ReturnType);
   bool HasRVO = !ReturnType->isVoidType() && !T;
-  const FunctionDecl *FuncDecl = E->getDirectCallee();
 
   if (HasRVO) {
 if (DiscardResult) {

diff  --git a/clang/lib/AST/ByteCode/Compiler.h 
b/clang/lib/AST/ByteCode/Compiler.h
index eb1252fec054bb..39c0736cb4e27e 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -133,7 +133,7 @@ class Compiler : public ConstStmtVisitor, 
bool>,
   bool VisitVectorBinOp(const BinaryOperator *E);
   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E);
   bool VisitCallExpr(const CallExpr *E);
-  bool VisitBuiltinCallExpr(const CallExpr *E);
+  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID);
   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E);
   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);

diff  --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 99d01ca52645e0..ac02bd6d033487 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -1178,7 +1178,7 @@ bool CallVirt(InterpState &S, CodePtr OpPC, const 
Function *Func,
 }
 
 bool CallBI(InterpState &S, CodePtr &PC, const Function *Func,
-const CallExpr *CE) {
+const CallExpr *CE, uint32_t BuiltinID) {
   if (S.checkingPotentialConstantExpression())
 return false;
   auto NewFrame

[clang] [clang][bytecode] Implement using operator new/operator delete (PR #107679)

2024-09-07 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Fix two-pointer-style std::initializer_lists (PR #107682)

2024-09-07 Thread Timm Baeder via cfe-commits

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

The first pointer needs to point to the first element of the underlying array. 
This requires some changes to how we handle array expansion

>From 4067ab666b9fbfb05b6a22c14de1eededebcb16f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 6 Sep 2024 12:56:14 +0200
Subject: [PATCH] [clang][bytecode] Fix two-pointer-style
 std::initializer_lists

The first pointer needs to point to the first element of the underlying
array. This requires some changes to how we handle array expansion
---
 clang/lib/AST/ByteCode/Compiler.cpp  |  6 +++
 clang/lib/AST/ByteCode/Interp.h  |  4 +-
 clang/lib/AST/ByteCode/Pointer.h |  5 +-
 clang/test/AST/ByteCode/initializer_list.cpp | 55 
 4 files changed, 67 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/AST/ByteCode/initializer_list.cpp

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index bada8621b9681f..274ad3e5443d11 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3320,6 +3320,10 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->visit(SubExpr))
 return false;
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
 return false;
 
@@ -3334,6 +3338,8 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
 return false;
+  if (!this->emitExpandPtr(E))
+return false;
   if (!this->emitConst(static_cast(ArrayType->getSize()), PT_Uint64, 
E))
 return false;
   if (!this->emitArrayElemPtrPop(PT_Uint64, E))
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 4ca0e05d67c7c3..6d7de8b334fabd 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1993,7 +1993,9 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 template ::T>
 bool AddOffset(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
-  const Pointer &Ptr = S.Stk.pop();
+  Pointer Ptr = S.Stk.pop();
+  if (Ptr.isBlockPointer())
+Ptr = Ptr.expand();
   return OffsetHelper(S, OpPC, Offset, Ptr);
 }
 
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index d05d8e9bc1f388..acbef437752388 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -241,9 +241,8 @@ class Pointer {
 if (asBlockPointer().Base != Offset)
   return *this;
 
-// If at base, point to an array of base types.
 if (isRoot())
-  return Pointer(Pointee, RootPtrMark, 0);
+  return Pointer(Pointee, asBlockPointer().Base, asBlockPointer().Base);
 
 // Step into the containing array, if inside one.
 unsigned Next = asBlockPointer().Base - getInlineDesc()->Offset;
@@ -711,8 +710,10 @@ class Pointer {
 
   /// Returns the embedded descriptor preceding a field.
   InlineDescriptor *getInlineDesc() const {
+assert(isBlockPointer());
 assert(asBlockPointer().Base != sizeof(GlobalInlineDescriptor));
 assert(asBlockPointer().Base <= asBlockPointer().Pointee->getSize());
+assert(asBlockPointer().Base >= sizeof(InlineDescriptor));
 return getDescriptor(asBlockPointer().Base);
   }
 
diff --git a/clang/test/AST/ByteCode/initializer_list.cpp 
b/clang/test/AST/ByteCode/initializer_list.cpp
new file mode 100644
index 00..4e3b8dc9120167
--- /dev/null
+++ b/clang/test/AST/ByteCode/initializer_list.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify=expected,both %s
+// RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref,both %s
+
+// both-no-diagnostics
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+  template 
+  class initializer_list
+  {
+const _E* __begin_;
+size_t__size_;
+
+initializer_list(const _E* __b, size_t __s)
+  : __begin_(__b),
+__size_(__s)
+{}
+
+  public:
+typedef _Evalue_type;
+typedef const _E& reference;
+typedef const _E& const_reference;
+typedef size_tsize_type;
+
+typedef const _E* iterator;
+typedef const _E* const_iterator;
+
+constexpr initializer_list() : __begin_(nullptr), __size_(0) {}
+
+constexpr size_tsize()  const {return __size_;}
+constexpr const _E* begin() const {return __begin_;}
+constexpr const _E* end()   const {return __begin_ + __size_;}
+  };
+}
+
+class Thing {
+public:
+  int m = 12;
+  constexpr Thing(int m) : m(m) {}
+  constexpr bool operator==(const Thing& that) const {
+return this->m == that.m;
+  }
+};
+
+constexpr bool is_contained(std::initializer_list Set, const Thing 
&Element) {
+   return (*Set.begin() == Element);
+}
+
+constexpr int foo() {
+  const Thing a{1

[clang] [clang][bytecode] Fix two-pointer-style std::initializer_lists (PR #107682)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

The first pointer needs to point to the first element of the underlying array. 
This requires some changes to how we handle array expansion

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


4 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+6) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+3-1) 
- (modified) clang/lib/AST/ByteCode/Pointer.h (+3-2) 
- (added) clang/test/AST/ByteCode/initializer_list.cpp (+55) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index bada8621b9681f..274ad3e5443d11 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3320,6 +3320,10 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->visit(SubExpr))
 return false;
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
 return false;
 
@@ -3334,6 +3338,8 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
 return false;
+  if (!this->emitExpandPtr(E))
+return false;
   if (!this->emitConst(static_cast(ArrayType->getSize()), PT_Uint64, 
E))
 return false;
   if (!this->emitArrayElemPtrPop(PT_Uint64, E))
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 4ca0e05d67c7c3..6d7de8b334fabd 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1993,7 +1993,9 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 template ::T>
 bool AddOffset(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
-  const Pointer &Ptr = S.Stk.pop();
+  Pointer Ptr = S.Stk.pop();
+  if (Ptr.isBlockPointer())
+Ptr = Ptr.expand();
   return OffsetHelper(S, OpPC, Offset, Ptr);
 }
 
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index d05d8e9bc1f388..acbef437752388 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -241,9 +241,8 @@ class Pointer {
 if (asBlockPointer().Base != Offset)
   return *this;
 
-// If at base, point to an array of base types.
 if (isRoot())
-  return Pointer(Pointee, RootPtrMark, 0);
+  return Pointer(Pointee, asBlockPointer().Base, asBlockPointer().Base);
 
 // Step into the containing array, if inside one.
 unsigned Next = asBlockPointer().Base - getInlineDesc()->Offset;
@@ -711,8 +710,10 @@ class Pointer {
 
   /// Returns the embedded descriptor preceding a field.
   InlineDescriptor *getInlineDesc() const {
+assert(isBlockPointer());
 assert(asBlockPointer().Base != sizeof(GlobalInlineDescriptor));
 assert(asBlockPointer().Base <= asBlockPointer().Pointee->getSize());
+assert(asBlockPointer().Base >= sizeof(InlineDescriptor));
 return getDescriptor(asBlockPointer().Base);
   }
 
diff --git a/clang/test/AST/ByteCode/initializer_list.cpp 
b/clang/test/AST/ByteCode/initializer_list.cpp
new file mode 100644
index 00..4e3b8dc9120167
--- /dev/null
+++ b/clang/test/AST/ByteCode/initializer_list.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify=expected,both %s
+// RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref,both %s
+
+// both-no-diagnostics
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+  template 
+  class initializer_list
+  {
+const _E* __begin_;
+size_t__size_;
+
+initializer_list(const _E* __b, size_t __s)
+  : __begin_(__b),
+__size_(__s)
+{}
+
+  public:
+typedef _Evalue_type;
+typedef const _E& reference;
+typedef const _E& const_reference;
+typedef size_tsize_type;
+
+typedef const _E* iterator;
+typedef const _E* const_iterator;
+
+constexpr initializer_list() : __begin_(nullptr), __size_(0) {}
+
+constexpr size_tsize()  const {return __size_;}
+constexpr const _E* begin() const {return __begin_;}
+constexpr const _E* end()   const {return __begin_ + __size_;}
+  };
+}
+
+class Thing {
+public:
+  int m = 12;
+  constexpr Thing(int m) : m(m) {}
+  constexpr bool operator==(const Thing& that) const {
+return this->m == that.m;
+  }
+};
+
+constexpr bool is_contained(std::initializer_list Set, const Thing 
&Element) {
+   return (*Set.begin() == Element);
+}
+
+constexpr int foo() {
+  const Thing a{12};
+  const Thing b{14};
+  return is_contained({a}, b);
+}
+
+static_assert(foo() == 0);

``




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


[clang] [clang-tools-extra] [mlir] [mlir] Add insert method for ApplyToEachResultList class (PR #107684)

2024-09-07 Thread via cfe-commits

https://github.com/fawdlstty created 
https://github.com/llvm/llvm-project/pull/107684

#94968

>From f169f3c57a0a55c1a0dbb8f965bc17a87ceb98d7 Mon Sep 17 00:00:00 2001
From: fawdlstty 
Date: Fri, 30 Aug 2024 00:23:39 +0800
Subject: [PATCH 1/3] add check for windows platforms api

---
 .../bugprone/NotNullTerminatedResultCheck.cpp |  2 +-
 clang/docs/analyzer/checkers.rst  |  2 +-
 clang/include/clang/Basic/Builtins.td | 22 +++
 .../Checkers/CStringChecker.cpp   |  6 +
 4 files changed, 30 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 977241e91b9a93..e2cf96c88b90bd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -106,7 +106,7 @@ static const CallExpr *getStrlenExpr(const 
MatchFinder::MatchResult &Result) {
 if (const Decl *D = StrlenExpr->getCalleeDecl())
   if (const FunctionDecl *FD = D->getAsFunction())
 if (const IdentifierInfo *II = FD->getIdentifier())
-  if (II->isStr("strlen") || II->isStr("wcslen"))
+  if (II->isStr("strlen") || II->isStr("lstrlen") || 
II->isStr("wcslen"))
 return StrlenExpr;
 
   return nullptr;
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 89a1018e14c0e6..ca675ae37929fe 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1582,7 +1582,7 @@ Check the size argument passed into C string functions 
for common erroneous patt
 unix.cstring.NullArg (C)
 
 Check for null pointers being passed as arguments to C string functions:
-``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, 
strcasecmp, strncasecmp, wcslen, wcsnlen``.
+``strlen, lstrlen, strnlen, strcpy, lstrcpy, strncpy, strcat, lstrcat, 
strncat, strcmp, strncmp, strcasecmp, strncasecmp, wcslen, wcsnlen``.
 
 .. code-block:: c
 
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 8668b25661dec8..cbc5fc52326ad2 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4788,3 +4788,25 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+// Windows - WinBase.h
+def LStrLen : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrlen"];
+  let Attributes = [NoThrow, Constexpr];
+  let Prototype = "int(LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
+
+def LStrCpy : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrcpy"];
+  let Attributes = [NoThrow];
+  let Prototype = "LPCTSTR(LPTSTR, LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
+
+def LStrCat : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrcat"];
+  let Attributes = [NoThrow];
+  let Prototype = "LPTSTR(LPTSTR, LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 8dd08f14b2728b..2adf538486176d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -150,6 +150,8 @@ class CStringChecker : public Checker< eval::Call,
   // FIXME: C23 introduces 'memset_explicit', maybe also model that
   {{CDM::CLibraryMaybeHardened, {"strcpy"}, 2},
&CStringChecker::evalStrcpy},
+  {{CDM::CLibraryMaybeHardened, {"lstrcpy"}, 2},
+   &CStringChecker::evalStrcpy},
   {{CDM::CLibraryMaybeHardened, {"strncpy"}, 3},
&CStringChecker::evalStrncpy},
   {{CDM::CLibraryMaybeHardened, {"stpcpy"}, 2},
@@ -158,12 +160,16 @@ class CStringChecker : public Checker< eval::Call,
&CStringChecker::evalStrlcpy},
   {{CDM::CLibraryMaybeHardened, {"strcat"}, 2},
&CStringChecker::evalStrcat},
+  {{CDM::CLibraryMaybeHardened, {"lstrcat"}, 2},
+   &CStringChecker::evalStrcat},
   {{CDM::CLibraryMaybeHardened, {"strncat"}, 3},
&CStringChecker::evalStrncat},
   {{CDM::CLibraryMaybeHardened, {"strlcat"}, 3},
&CStringChecker::evalStrlcat},
   {{CDM::CLibraryMaybeHardened, {"strlen"}, 1},
&CStringChecker::evalstrLength},
+  {{CDM::CLibraryMaybeHardened, {"lstrlen"}, 1},
+   &CStringChecker::evalstrLength},
   {{CDM::CLibrary, {"wcslen"}, 1}, &CStringChecker::evalstrLength},
   {{CDM::CLibraryMaybeHardened, {"strnlen"}, 2},
&CStringChecker::evalstrnLength},

>From 52d40b558e14948c38c8c5f75245c5ba08bd3fea Mon Sep 17 00:00:00 2001
From: fawdlstty 
Date: Fri, 30 Aug 2024 00:33:22 +0800
Subject: [PATCH 2/3] add to insecureAPI

---
 clang/docs/analyzer/checkers.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/analyzer/check

[clang] [clang-tools-extra] [mlir] [mlir] Add insert method for ApplyToEachResultList class (PR #107684)

2024-09-07 Thread via cfe-commits

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


[clang] [clang-tools-extra] [mlir] [mlir] Add insert method for ApplyToEachResultList class (PR #107684)

2024-09-07 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/107684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [mlir] [mlir] Add insert method for ApplyToEachResultList class (PR #107684)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




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

Author: Fawdlstty (fawdlstty)


Changes

#94968

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


5 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp (+1-1) 
- (modified) clang/docs/analyzer/checkers.rst (+2-2) 
- (modified) clang/include/clang/Basic/Builtins.td (+22) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (+6) 
- (modified) 
mlir/include/mlir/Dialect/Transform/Interfaces/TransformInterfaces.h (+5) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 977241e91b9a93..e2cf96c88b90bd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -106,7 +106,7 @@ static const CallExpr *getStrlenExpr(const 
MatchFinder::MatchResult &Result) {
 if (const Decl *D = StrlenExpr->getCalleeDecl())
   if (const FunctionDecl *FD = D->getAsFunction())
 if (const IdentifierInfo *II = FD->getIdentifier())
-  if (II->isStr("strlen") || II->isStr("wcslen"))
+  if (II->isStr("strlen") || II->isStr("lstrlen") || 
II->isStr("wcslen"))
 return StrlenExpr;
 
   return nullptr;
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 89a1018e14c0e6..7a7b1926da17b4 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1256,7 +1256,7 @@ Warn on uses of inferior random number generating 
functions (only if arc4random
 
 security.insecureAPI.strcpy (C)
 """
-Warn on uses of the ``strcpy`` and ``strcat`` functions.
+Warn on uses of the ``strcpy, lstrcpy, strcat, lstrcat`` functions.
 
 .. code-block:: c
 
@@ -1582,7 +1582,7 @@ Check the size argument passed into C string functions 
for common erroneous patt
 unix.cstring.NullArg (C)
 
 Check for null pointers being passed as arguments to C string functions:
-``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, 
strcasecmp, strncasecmp, wcslen, wcsnlen``.
+``strlen, lstrlen, strnlen, strcpy, lstrcpy, strncpy, strcat, lstrcat, 
strncat, strcmp, strncmp, strcasecmp, strncasecmp, wcslen, wcsnlen``.
 
 .. code-block:: c
 
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 8668b25661dec8..cbc5fc52326ad2 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4788,3 +4788,25 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+// Windows - WinBase.h
+def LStrLen : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrlen"];
+  let Attributes = [NoThrow, Constexpr];
+  let Prototype = "int(LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
+
+def LStrCpy : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrcpy"];
+  let Attributes = [NoThrow];
+  let Prototype = "LPCTSTR(LPTSTR, LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
+
+def LStrCat : LibBuiltin<"WinBase.h"> {
+  let Spellings = ["lstrcat"];
+  let Attributes = [NoThrow];
+  let Prototype = "LPTSTR(LPTSTR, LPCTSTR)";
+  let AddBuiltinPrefixedAlias = 1;
+}
diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 8dd08f14b2728b..2adf538486176d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -150,6 +150,8 @@ class CStringChecker : public Checker< eval::Call,
   // FIXME: C23 introduces 'memset_explicit', maybe also model that
   {{CDM::CLibraryMaybeHardened, {"strcpy"}, 2},
&CStringChecker::evalStrcpy},
+  {{CDM::CLibraryMaybeHardened, {"lstrcpy"}, 2},
+   &CStringChecker::evalStrcpy},
   {{CDM::CLibraryMaybeHardened, {"strncpy"}, 3},
&CStringChecker::evalStrncpy},
   {{CDM::CLibraryMaybeHardened, {"stpcpy"}, 2},
@@ -158,12 +160,16 @@ class CStringChecker : public Checker< eval::Call,
&CStringChecker::evalStrlcpy},
   {{CDM::CLibraryMaybeHardened, {"strcat"}, 2},
&CStringChecker::evalStrcat},
+  {{CDM::CLibraryMaybeHardened, {"lstrcat"}, 2},
+   &CStringChecker::evalStrcat},
   {{CDM::CLibraryMaybeHardened, {"strncat"}, 3},
&CStringChecker::evalStrncat},
   {{CDM::CLibraryMaybeHardened, {"strlcat"}, 3},
&CStringChecker::evalStrlcat},
   {{CDM::CLibraryMaybeHardened, {"strlen"}, 1},
&CStringChecker::evalstrLength},
+  {{CDM::CLibraryMaybeHardened, {"lstrlen"}, 1},
+   &CStringChecker::evalstrLength},
   {{CDM::CLibrary, {"wcslen"}, 1}, &CStringChecker::evalstrLength},
   {{CDM::CLibraryMaybeHardened, {"strnlen"}, 2},
&CStringC

[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-07 Thread Frederik Carlier via cfe-commits


@@ -1699,11 +1699,18 @@ class CGObjCGNUstep2 : public CGObjCGNUstep {
   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
   const ObjCInterfaceDecl *Interface,
   const ObjCIvarDecl *Ivar) override {
-const std::string Name = 
GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
+const ObjCInterfaceDecl *ContainingInterface =
+Ivar->getContainingInterface();
+const std::string Name =
+GetIVarOffsetVariableName(ContainingInterface, Ivar);
 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
-if (!IvarOffsetPointer)
+if (!IvarOffsetPointer) {
   IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
   llvm::GlobalValue::ExternalLinkage, nullptr, Name);
+  if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&
+  Ivar->getAccessControl() != ObjCIvarDecl::Package)

qmfrederik wrote:

I think the added tests demonstrate that unmarked ivars are considered 
protected, so let me know if that resolves this comment?

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


[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-07 Thread Frederik Carlier via cfe-commits

qmfrederik wrote:

Thanks @davidchisnall and @compnerd . Let me know if there's anything else you 
need?

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


[clang] [llvm] [TableGen] Change SetTheory set/vec to use const Record * (PR #107692)

2024-09-07 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/107692

Change SetTheory::RecSet/RecVec to use const Record pointers.

>From 4fc94659b3c245a30902c95be6d9c7bfd1d55f0a Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Sat, 7 Sep 2024 04:33:09 -0700
Subject: [PATCH] [TableGen] Change SetTheory set/vec to use consr Record *

Change SetTheory::RecSet/RecVec to use const Record pointers.
---
 clang/utils/TableGen/NeonEmitter.cpp  |  2 +-
 llvm/include/llvm/TableGen/Record.h   |  6 +--
 llvm/include/llvm/TableGen/SetTheory.h|  4 +-
 llvm/lib/TableGen/Record.cpp  | 10 ++---
 llvm/utils/TableGen/AsmMatcherEmitter.cpp | 38 ++-
 .../TableGen/Common/CodeGenRegisters.cpp  | 29 +++---
 llvm/utils/TableGen/Common/CodeGenRegisters.h | 16 
 .../utils/TableGen/Common/CodeGenSchedule.cpp | 27 ++---
 llvm/utils/TableGen/Common/CodeGenSchedule.h  | 10 +++--
 llvm/utils/TableGen/RegisterInfoEmitter.cpp   | 30 +++
 llvm/utils/TableGen/TableGen.cpp  |  2 +-
 11 files changed, 88 insertions(+), 86 deletions(-)

diff --git a/clang/utils/TableGen/NeonEmitter.cpp 
b/clang/utils/TableGen/NeonEmitter.cpp
index e0d7b0db7f5780..4707ce1ea3b792 100644
--- a/clang/utils/TableGen/NeonEmitter.cpp
+++ b/clang/utils/TableGen/NeonEmitter.cpp
@@ -1636,7 +1636,7 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
   int64_t VectorSize = cast(Expr->getArg(0))->getValue();
   VectorSize /= ElementSize;
 
-  std::vector Revved;
+  std::vector Revved;
   for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
 for (int LI = VectorSize - 1; LI >= 0; --LI) {
   Revved.push_back(Elts2[VI + LI]);
diff --git a/llvm/include/llvm/TableGen/Record.h 
b/llvm/include/llvm/TableGen/Record.h
index 5d36fcf57e23e3..f6c751af6bb836 100644
--- a/llvm/include/llvm/TableGen/Record.h
+++ b/llvm/include/llvm/TableGen/Record.h
@@ -1323,7 +1323,7 @@ class DefInit : public TypedInit {
 return I->getKind() == IK_DefInit;
   }
 
-  static DefInit *get(Record*);
+  static DefInit *get(const Record *);
 
   Init *convertInitializerTo(RecTy *Ty) const override;
 
@@ -1673,7 +1673,7 @@ class Record {
   RecordKeeper &TrackedRecords;
 
   // The DefInit corresponding to this record.
-  DefInit *CorrespondingDefInit = nullptr;
+  mutable DefInit *CorrespondingDefInit = nullptr;
 
   // Unique record ID.
   unsigned ID;
@@ -1740,7 +1740,7 @@ class Record {
   RecordRecTy *getType();
 
   /// get the corresponding DefInit.
-  DefInit *getDefInit();
+  DefInit *getDefInit() const;
 
   bool isClass() const { return Kind == RK_Class; }
 
diff --git a/llvm/include/llvm/TableGen/SetTheory.h 
b/llvm/include/llvm/TableGen/SetTheory.h
index 954453b783d4d8..771dcff2f214c3 100644
--- a/llvm/include/llvm/TableGen/SetTheory.h
+++ b/llvm/include/llvm/TableGen/SetTheory.h
@@ -64,8 +64,8 @@ class Record;
 
 class SetTheory {
 public:
-  using RecVec = std::vector;
-  using RecSet = SmallSetVector;
+  using RecVec = std::vector;
+  using RecSet = SmallSetVector;
 
   /// Operator - A callback representing a DAG operator.
   class Operator {
diff --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp
index 17afa2f7eb1b99..79c5e071e55f23 100644
--- a/llvm/lib/TableGen/Record.cpp
+++ b/llvm/lib/TableGen/Record.cpp
@@ -2235,9 +2235,7 @@ Init *VarBitInit::resolveReferences(Resolver &R) const {
 DefInit::DefInit(Record *D)
 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
 
-DefInit *DefInit::get(Record *R) {
-  return R->getDefInit();
-}
+DefInit *DefInit::get(const Record *R) { return R->getDefInit(); }
 
 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
   if (auto *RRT = dyn_cast(Ty))
@@ -2808,10 +2806,10 @@ RecordRecTy *Record::getType() {
   return RecordRecTy::get(TrackedRecords, DirectSCs);
 }
 
-DefInit *Record::getDefInit() {
+DefInit *Record::getDefInit() const {
   if (!CorrespondingDefInit) {
-CorrespondingDefInit =
-new (TrackedRecords.getImpl().Allocator) DefInit(this);
+CorrespondingDefInit = new (TrackedRecords.getImpl().Allocator)
+DefInit(const_cast(this));
   }
   return CorrespondingDefInit;
 }
diff --git a/llvm/utils/TableGen/AsmMatcherEmitter.cpp 
b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
index f351087ad212f7..574a3344a02f8d 100644
--- a/llvm/utils/TableGen/AsmMatcherEmitter.cpp
+++ b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
@@ -140,7 +140,7 @@ class AsmMatcherInfo;
 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, 
and
 // can even affect compiler output (at least seen in diagnostics produced when
 // all matches fail). So we use a type that sorts them consistently.
-typedef std::set RegisterSet;
+typedef std::set RegisterSet;
 
 class AsmMatcherEmitter {
   RecordKeeper &Records;
@@ -242,7 +242,7 @@ struct ClassInfo {
   if (!isRegisterClass() || !RHS.isRegisterClass())
 return false;
 
-  s

[clang] d6d6070 - [clang][bytecode] Fix two-pointer-style std::initializer_lists (#107682)

2024-09-07 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-09-07T14:27:09+02:00
New Revision: d6d60707ec2b60843c5bfc2c3bc44e4478add17a

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

LOG: [clang][bytecode] Fix two-pointer-style std::initializer_lists (#107682)

The first pointer needs to point to the first element of the underlying
array. This requires some changes to how we handle array expansion

Added: 
clang/test/AST/ByteCode/initializer_list.cpp

Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/Pointer.h

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 115b0aa7dd29c9..46f9c98d59befc 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3320,6 +3320,10 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->visit(SubExpr))
 return false;
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
 return false;
 
@@ -3334,6 +3338,8 @@ bool Compiler::VisitCXXStdInitializerListExpr(
 
   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
 return false;
+  if (!this->emitExpandPtr(E))
+return false;
   if (!this->emitConst(static_cast(ArrayType->getSize()), PT_Uint64, 
E))
 return false;
   if (!this->emitArrayElemPtrPop(PT_Uint64, E))

diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 7a0011b9606976..e345b9ead967ce 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -1993,7 +1993,9 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 template ::T>
 bool AddOffset(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
-  const Pointer &Ptr = S.Stk.pop();
+  Pointer Ptr = S.Stk.pop();
+  if (Ptr.isBlockPointer())
+Ptr = Ptr.expand();
   return OffsetHelper(S, OpPC, Offset, Ptr);
 }
 

diff  --git a/clang/lib/AST/ByteCode/Pointer.h 
b/clang/lib/AST/ByteCode/Pointer.h
index d05d8e9bc1f388..acbef437752388 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -241,9 +241,8 @@ class Pointer {
 if (asBlockPointer().Base != Offset)
   return *this;
 
-// If at base, point to an array of base types.
 if (isRoot())
-  return Pointer(Pointee, RootPtrMark, 0);
+  return Pointer(Pointee, asBlockPointer().Base, asBlockPointer().Base);
 
 // Step into the containing array, if inside one.
 unsigned Next = asBlockPointer().Base - getInlineDesc()->Offset;
@@ -711,8 +710,10 @@ class Pointer {
 
   /// Returns the embedded descriptor preceding a field.
   InlineDescriptor *getInlineDesc() const {
+assert(isBlockPointer());
 assert(asBlockPointer().Base != sizeof(GlobalInlineDescriptor));
 assert(asBlockPointer().Base <= asBlockPointer().Pointee->getSize());
+assert(asBlockPointer().Base >= sizeof(InlineDescriptor));
 return getDescriptor(asBlockPointer().Base);
   }
 

diff  --git a/clang/test/AST/ByteCode/initializer_list.cpp 
b/clang/test/AST/ByteCode/initializer_list.cpp
new file mode 100644
index 00..4e3b8dc9120167
--- /dev/null
+++ b/clang/test/AST/ByteCode/initializer_list.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify=expected,both %s
+// RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref,both %s
+
+// both-no-diagnostics
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+  template 
+  class initializer_list
+  {
+const _E* __begin_;
+size_t__size_;
+
+initializer_list(const _E* __b, size_t __s)
+  : __begin_(__b),
+__size_(__s)
+{}
+
+  public:
+typedef _Evalue_type;
+typedef const _E& reference;
+typedef const _E& const_reference;
+typedef size_tsize_type;
+
+typedef const _E* iterator;
+typedef const _E* const_iterator;
+
+constexpr initializer_list() : __begin_(nullptr), __size_(0) {}
+
+constexpr size_tsize()  const {return __size_;}
+constexpr const _E* begin() const {return __begin_;}
+constexpr const _E* end()   const {return __begin_ + __size_;}
+  };
+}
+
+class Thing {
+public:
+  int m = 12;
+  constexpr Thing(int m) : m(m) {}
+  constexpr bool operator==(const Thing& that) const {
+return this->m == that.m;
+  }
+};
+
+constexpr bool is_contained(std::initializer_list Set, const Thing 
&Element) {
+   return (*Set.begin() == Element);
+}
+
+constexpr int foo() {
+  const Thing a{12};
+  const Thing b{14};
+  return is_contained({a}, b);
+}
+
+static_assert(foo() == 0);




[clang] [clang][bytecode] Fix two-pointer-style std::initializer_lists (PR #107682)

2024-09-07 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Add InitLinkScope for temporary variables (PR #106552)

2024-09-07 Thread Timm Baeder via cfe-commits

tbaederr wrote:

In this code:
```c++
namespace ExplicitThisInTemporary {
 struct B { B *p = this; };
  constexpr bool g(B b) { return &b == b.p; }
  static_assert(g({}), "");
}
```

The AST for the `static_assert` expr is:
```
CallExpr 0x5219ed98 '_Bool'
|-ImplicitCastExpr 0x5219ed78 '_Bool (*)(B)' 
| `-DeclRefExpr 0x521754a0 '_Bool (B)' lvalue Function 0x52175188 'g' 
'_Bool (B)'
`-InitListExpr 0x5219edc8 'B':'struct ExplicitThisInTemporary::B'
  `-CXXDefaultInitExpr 0x5219ee20 'B *' has rewritten init
`-CXXThisExpr 0x52175008 'struct ExplicitThisInTemporary::B *' this
```

the `CXXThisExpr` here doesn't point to the current instance pointer of the 
frame (that doesn't even exist), but to the object created by the 
`InitListExpr` surrounding it (`0x5219edc8`).

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


[clang] [HIP][Clang][CodeGen] Handle hip bin symbols properly. (PR #107458)

2024-09-07 Thread via cfe-commits

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

>From d385e0810bc24dcaf8296501922b50fd88e18415 Mon Sep 17 00:00:00 2001
From: jofernau 
Date: Thu, 5 Sep 2024 23:31:55 -0400
Subject: [PATCH] [HIP][Clang][CodeGen] Handle hip bin symbols properly.

Remove '_' in fatbin symbol suffix when missing TU hash ID. Internalize gpubin 
symbol so that it is not unresolved at link-time.
---
 clang/lib/CodeGen/CGCUDANV.cpp| 18 ++
 clang/test/CodeGenCUDA/device-stub.cu |  1 -
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 59c5927717933d..7988d4ce462caf 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -840,8 +840,10 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
   FatBinStr = new llvm::GlobalVariable(
   CGM.getModule(), CGM.Int8Ty,
   /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
-  "__hip_fatbin_" + CGM.getContext().getCUIDHash(), nullptr,
-  llvm::GlobalVariable::NotThreadLocal);
+  "__hip_fatbin" + (CGM.getLangOpts().CUID.empty()
+? ""
+: "_" + CGM.getContext().getCUIDHash()),
+  nullptr, llvm::GlobalVariable::NotThreadLocal);
   cast(FatBinStr)->setSection(FatbinConstantName);
 }
 
@@ -894,8 +896,8 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
   // thread safety of the loaded program. Therefore we can assume sequential
   // execution of constructor functions here.
   if (IsHIP) {
-auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage
- : llvm::GlobalValue::ExternalLinkage;
+auto Linkage = RelocatableDeviceCode ? llvm::GlobalValue::ExternalLinkage
+ : llvm::GlobalValue::InternalLinkage;
 llvm::BasicBlock *IfBlock =
 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
 llvm::BasicBlock *ExitBlock =
@@ -905,10 +907,10 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() 
{
 GpuBinaryHandle = new llvm::GlobalVariable(
 TheModule, PtrTy, /*isConstant=*/false, Linkage,
 /*Initializer=*/
-CudaGpuBinary ? llvm::ConstantPointerNull::get(PtrTy) : nullptr,
-CudaGpuBinary
-? "__hip_gpubin_handle"
-: "__hip_gpubin_handle_" + CGM.getContext().getCUIDHash());
+llvm::ConstantPointerNull::get(PtrTy),
+"__hip_gpubin_handle" + (CGM.getLangOpts().CUID.empty()
+ ? ""
+ : "_" + CGM.getContext().getCUIDHash()));
 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
 // Prevent the weak symbol in different shared libraries being merged.
 if (Linkage != llvm::GlobalValue::InternalLinkage)
diff --git a/clang/test/CodeGenCUDA/device-stub.cu 
b/clang/test/CodeGenCUDA/device-stub.cu
index 60304647bd4c54..11d1f5a867b09a 100644
--- a/clang/test/CodeGenCUDA/device-stub.cu
+++ b/clang/test/CodeGenCUDA/device-stub.cu
@@ -175,7 +175,6 @@ __device__ void device_use() {
 // HIP-SAME: section ".hipFatBinSegment"
 // * variable to save GPU binary handle after initialization
 // CUDANORDC: @__[[PREFIX]]_gpubin_handle = internal global ptr null
-// HIPNEF: @__[[PREFIX]]_gpubin_handle_{{[0-9a-f]+}} = external hidden global 
ptr, align 8
 // * constant unnamed string with NVModuleID
 // CUDARDC: [[MODULE_ID_GLOBAL:@.*]] = private constant
 // CUDARDC-SAME: c"[[MODULE_ID:.+]]\00", section "__nv_module_id", align 32

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits


@@ -15,6 +15,7 @@
 #include "PrimType.h"
 #include "Program.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/OperationKinds.h"

yronglin wrote:

Hmm, I think it introduced by clangd plugin's IWYU feature, I'll revert this 
change.

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits


@@ -1267,7 +1268,15 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   auto getElem = [=](unsigned Offset, unsigned Index) {
 if (!this->emitGetLocal(PT_Ptr, Offset, E))
   return false;
-return this->emitArrayElemPop(ElemT, Index, E);
+if (!this->emitArrayElemPop(ElemT, Index, E))
+  return false;
+if (E->isLogicalOp()) {
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), 
E))
+return false;
+}

yronglin wrote:

Yes, this approach doesn't looks well. Seems BitAnd/BitOr doesn't support bool 
type, should we extend these two operations to support bool type? Then we can 
avoid these casts.

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


[clang] 3ba0755 - [clang][OpenMP] Simplify handling of implicit DSA/mapping information (#106786)

2024-09-07 Thread via cfe-commits

Author: Krzysztof Parzyszek
Date: 2024-09-07T09:10:21-05:00
New Revision: 3ba0755d3e50c62d27ac9c37a0250f525dcad28d

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

LOG: [clang][OpenMP] Simplify handling of implicit DSA/mapping information 
(#106786)

Create `VariableImplicitInfo` to hold the data. Most of it is used all
at once, so aggregating it seems like a good idea.

Added: 


Modified: 
clang/include/clang/Basic/OpenMPKinds.h
clang/lib/Sema/SemaOpenMP.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/OpenMPKinds.h 
b/clang/include/clang/Basic/OpenMPKinds.h
index 16bb967f89d53e..1acdafa8572211 100644
--- a/clang/include/clang/Basic/OpenMPKinds.h
+++ b/clang/include/clang/Basic/OpenMPKinds.h
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_BASIC_OPENMPKINDS_H
 
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/Sequence.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Frontend/OpenMP/OMPConstants.h"
 
@@ -389,5 +390,9 @@ bool isOpenMPInformationalDirective(OpenMPDirectiveKind 
DKind);
 bool isOpenMPCapturingDirective(OpenMPDirectiveKind DKind);
 }
 
+template <>
+struct llvm::enum_iteration_traits {
+  static constexpr bool is_iterable = true;
+};
 #endif
 

diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 23c4903ec15855..b952ffbd69f5d5 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -42,6 +42,7 @@
 #include "llvm/ADT/PointerEmbeddedInt.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Frontend/OpenMP/OMPAssume.h"
@@ -3707,6 +3708,17 @@ 
getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
 }
 
 namespace {
+struct VariableImplicitInfo {
+  static const unsigned MapKindNum = OMPC_MAP_unknown;
+  static const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_unknown + 1;
+
+  llvm::SetVector Privates;
+  llvm::SetVector Firstprivates;
+  llvm::SetVector Mappings[DefaultmapKindNum][MapKindNum];
+  llvm::SmallVector
+  MapModifiers[DefaultmapKindNum];
+};
+
 class DSAAttrChecker final : public StmtVisitor {
   DSAStackTy *Stack;
   Sema &SemaRef;
@@ -3714,12 +3726,8 @@ class DSAAttrChecker final : public 
StmtVisitor {
   bool ErrorFound = false;
   bool TryCaptureCXXThisMembers = false;
   CapturedStmt *CS = nullptr;
-  const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_unknown + 1;
-  llvm::SmallVector ImplicitFirstprivate;
-  llvm::SmallVector ImplicitPrivate;
-  llvm::SmallVector ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
-  llvm::SmallVector
-  ImplicitMapModifier[DefaultmapKindNum];
+
+  VariableImplicitInfo ImpInfo;
   SemaOpenMP::VarsWithInheritedDSAType VarsWithInheritedDSA;
   llvm::SmallDenseSet ImplicitDeclarations;
 
@@ -3871,9 +3879,9 @@ class DSAAttrChecker final : public 
StmtVisitor {
 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
  OMPC_DEFAULTMAP_MODIFIER_present;
 if (IsModifierPresent) {
-  if (!llvm::is_contained(ImplicitMapModifier[ClauseKind],
+  if (!llvm::is_contained(ImpInfo.MapModifiers[ClauseKind],
   OMPC_MAP_MODIFIER_present)) {
-ImplicitMapModifier[ClauseKind].push_back(
+ImpInfo.MapModifiers[ClauseKind].push_back(
 OMPC_MAP_MODIFIER_present);
   }
 }
@@ -3913,13 +3921,13 @@ class DSAAttrChecker final : public 
StmtVisitor {
   IsFirstprivate =
   IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && 
!Res);
   if (IsFirstprivate) {
-ImplicitFirstprivate.emplace_back(E);
+ImpInfo.Firstprivates.insert(E);
   } else {
 OpenMPDefaultmapClauseModifier M =
 Stack->getDefaultmapModifier(ClauseKind);
 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
-ImplicitMap[ClauseKind][Kind].emplace_back(E);
+ImpInfo.Mappings[ClauseKind][Kind].insert(E);
   }
   return;
 }
@@ -3956,9 +3964,9 @@ class DSAAttrChecker final : public 
StmtVisitor {
 !DVar.RefExpr)) &&
   !Stack->isLoopControlVariable(VD).first) {
 if (Stack->getDefaultDSA() == DSA_private)
-  ImplicitPrivate.push_back(E);
+  ImpInfo.Privates.insert(E);
 else
-  ImplicitFirstprivate.push_back(E);
+  ImpInfo.Firstprivates.insert(E);
 return;
   }
 
@@ -4015,7 +4023,7 @@ class DSAAttrChecker final : public 
StmtVisitor {
 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
   

[clang] [clang][OpenMP] Simplify handling of implicit DSA/mapping information (PR #106786)

2024-09-07 Thread Krzysztof Parzyszek via cfe-commits

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits


@@ -1300,6 +1309,16 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   if (!this->emitGT(ElemT, E))
 return false;
   break;
+case BO_LAnd:
+  // a && b is equivalent to a!=0 & b!=0

yronglin wrote:

Should we follow the behavior of current interpreter or go further to implement 
a short-circuiting here? 
I have go through the Clang issue list, and it seems that no users have 
reported related bugs.

- 
https://github.com/llvm/llvm-project/issues?q=is%3Aissue+is%3Aopen+vector_size+label%3Aclang%3Afrontend
- 
https://github.com/llvm/llvm-project/issues?q=is%3Aissue+is%3Aopen+ext_vector_type+label%3Aclang%3Afrontend

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


[clang] [clang][bytecode] Implement logical operators for vector type (PR #107678)

2024-09-07 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/107678

>From b9da0771d479fe5384f6e83bb1e2b75cd48fd5b4 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 7 Sep 2024 16:53:12 +0800
Subject: [PATCH 1/2] [clang][bytecode] Implement logical operators for vector
 type

Signed-off-by: yronglin 
---
 clang/lib/AST/ByteCode/Compiler.cpp   | 23 -
 clang/test/AST/ByteCode/constexpr-vectors.cpp | 90 +++
 2 files changed, 111 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index eea77c2f0a9bb4..0dd690a69dca71 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -15,6 +15,7 @@
 #include "PrimType.h"
 #include "Program.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/OperationKinds.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -1232,7 +1233,7 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
 
   // FIXME: Current only support comparison binary operator, add support for
   // other binary operator.
-  if (!E->isComparisonOp())
+  if (!E->isComparisonOp() && !E->isLogicalOp())
 return this->emitInvalid(E);
   // Prepare storage for result.
   if (!Initializing) {
@@ -1267,7 +1268,15 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   auto getElem = [=](unsigned Offset, unsigned Index) {
 if (!this->emitGetLocal(PT_Ptr, Offset, E))
   return false;
-return this->emitArrayElemPop(ElemT, Index, E);
+if (!this->emitArrayElemPop(ElemT, Index, E))
+  return false;
+if (E->isLogicalOp()) {
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), 
E))
+return false;
+}
+return true;
   };
 
   for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
@@ -1300,6 +1309,16 @@ bool Compiler::VisitVectorBinOp(const 
BinaryOperator *E) {
   if (!this->emitGT(ElemT, E))
 return false;
   break;
+case BO_LAnd:
+  // a && b is equivalent to a!=0 & b!=0
+  if (!this->emitBitAnd(ResultElemT, E))
+return false;
+  break;
+case BO_LOr:
+  // a || b is equivalent to a!=0 | b!=0
+  if (!this->emitBitOr(ResultElemT, E))
+return false;
+  break;
 default:
   llvm_unreachable("Unsupported binary operator");
 }
diff --git a/clang/test/AST/ByteCode/constexpr-vectors.cpp 
b/clang/test/AST/ByteCode/constexpr-vectors.cpp
index 684c5810702cc3..7a65b263784586 100644
--- a/clang/test/AST/ByteCode/constexpr-vectors.cpp
+++ b/clang/test/AST/ByteCode/constexpr-vectors.cpp
@@ -57,6 +57,20 @@ void CharUsage() {
   constexpr auto H = FourCharsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsVecSize{5, 0, 6, 0} &&
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsVecSize{5, 0, 6, 0} ||
+ FourCharsVecSize{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsVecSize{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsVecSize{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
   constexpr auto H1 = FourCharsVecSize{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -111,6 +125,21 @@ void CharExtVecUsage() {
   constexpr auto H = FourCharsExtVec{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O = FourCharsExtVec{5, 0, 6, 0} &&
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(O[0] == 1 && O[1] == 0 && O[2] == 0 && O[3] == 0, "");
+
+  constexpr auto P = FourCharsExtVec{5, 0, 6, 0} ||
+ FourCharsExtVec{5, 5, 0, 0};
+  static_assert(P[0] == 1 && P[1] == 1 && P[2] == 1 && P[3] == 0, "");
+
+  constexpr auto Q = FourCharsExtVec{5, 0, 6, 0} && 3;
+  static_assert(Q[0] == 1 && Q[1] == 0 && Q[2] == 1 && Q[3] == 0, "");
+
+  constexpr auto R = FourCharsExtVec{5, 0, 6, 0} || 3;
+  static_assert(R[0] == 1 && R[1] == 1 && R[2] == 1 && R[3] == 1, "");
+
+
   constexpr auto H1 = FourCharsExtVec{-1, -1, 0, -1};
   constexpr auto InvH = -H1;
   static_assert(InvH[0] == 1 && InvH[1] == 1 && InvH[2] == 0 && InvH[3] == 1, 
"");
@@ -165,10 +194,33 @@ void FloatUsage() {
   constexpr auto H = FourFloatsVecSize{1, 2, 3, 4} != 3;
   static_assert(H[0] == -1 && H[1] == -1 && H[2] == 0 && H[3] == -1, "");
 
+  constexpr auto O1 = FourFloatsVecSize{5, 0, 6, 0} &&
+ FourFloatsVecSize{5, 5, 0, 0};
+  static_assert(O1[0] == 1 && O1[1] == 0 && O1[2] == 0

[clang] [clang-format] Introduce "ReflowComments: IndentOnly" to re-indent comments without breaking internal structure (think Doxygen). (PR #96804)

2024-09-07 Thread Ivan Jager via cfe-commits

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


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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits


@@ -1555,6 +1499,11 @@ DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
   return TemplateDeductionResult::Success;
 }
 
+static PartialOrderingKind
+degradeCallPartialOrderingKind(PartialOrderingKind POK) {
+  return std::min(POK, PartialOrderingKind::NonCall);
+}
+

cor3ntin wrote:

Can we get a comment here?

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits

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

Only nits at this point.
Sorry the review took this long, it was a pretty large PR.
Thanks for working on it!

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits


@@ -6753,16 +6758,41 @@ ASTContext::getNameForTemplate(TemplateName Name,
   case TemplateName::UsingTemplate:
 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
NameLoc);
+  case TemplateName::DeducedTemplate: {
+DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
+return getNameForTemplate(DTS->getUnderlying(), NameLoc);
+  }
   }
 
   llvm_unreachable("bad template name kind!");
 }
 
-TemplateName
-ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
+static const TemplateArgument *
+getDefaultTemplateArgumentOrNone(const NamedDecl *P) {
+  auto handleParam = [](auto *TP) -> const TemplateArgument * {
+if (!TP->hasDefaultArgument())
+  return nullptr;
+return &TP->getDefaultArgument().getArgument();
+  };
+  switch (P->getKind()) {
+  case NamedDecl::TemplateTypeParm:
+return handleParam(cast(P));
+  case NamedDecl::NonTypeTemplateParm:
+return handleParam(cast(P));
+  case NamedDecl::TemplateTemplateParm:
+return handleParam(cast(P));
+  default:
+llvm_unreachable("Unexpected template parameter kind");
+  }
+}

cor3ntin wrote:

Not in this PR, but i wonder if we should have a base class for all these types

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits


@@ -2304,6 +2306,15 @@ class ASTContext : public RefCountedBase {
 unsigned Index,
 bool Final) const;
 
+  /// Represents a TemplateName which had some of it's default arguments

cor3ntin wrote:

```suggestion
  /// Represents a TemplateName which had some of its default arguments
```

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread via cfe-commits


@@ -645,6 +645,9 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
  // It is sufficient to check value of getAsTemplateDecl.
  break;
 
+   case TemplateName::DeducedTemplate:
+ // FIXME: We can't reach here.
+ llvm_unreachable("unimplemented");

cor3ntin wrote:

Hum, fair enough. It's hard to me to understand how we could ever get there 
though

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


[clang] [NFC][rtsan] Docs of how to disable rtsan (PR #107707)

2024-09-07 Thread Chris Apple via cfe-commits

https://github.com/cjappl created 
https://github.com/llvm/llvm-project/pull/107707

None

>From e3e211f65afbc923299c0f413d2c50c7b00884b6 Mon Sep 17 00:00:00 2001
From: Chris Apple 
Date: Sat, 7 Sep 2024 08:38:06 -0700
Subject: [PATCH] [NFC][rtsan] Docs of how to disable rtsan

---
 clang/docs/RealtimeSanitizer.rst | 50 
 1 file changed, 50 insertions(+)

diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 799cd43509c6e6..7854cd3c0331a4 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -83,3 +83,53 @@ non-zero exit code.
 #13 0x00010230dd64 in main main.cpp:9
 #14 0x0001958960dc  ()
 #15 0x2f557ffc  ()
+
+Disabling
+-
+
+In some circumstances, you may want to suppress RealtimeSanitizer violations 
in a specific scope.
+
+In C++, this is achieved via  ``__rtsan::ScopedDisabler``. Within the scope 
where the ``ScopedDisabler`` object is instantiated, all sanitizer-reported 
violations are suppressed. This suppression applies to the current scope as 
well as all invoked functions, including any functions called transitively. 
+
+.. code-block:: c++
+
+#include 
+
+void process(const std::vector& buffer) [[clang::nonblocking]] {
+{
+__rtsan::ScopedDisabler d;
+...
+}
+}
+
+If RealtimeSanitizer is not enabled at compile time (i.e., the code is not 
compiled with the ``-fsanitize=realtime`` flag), the ``ScopedDisabler`` is 
compiled as a no-op.
+
+In C, you can use the ``__rtsan_disable()`` and ``rtsan_enable()`` functions 
to manually disable and re-enable RealtimeSanitizer checks. 
+
+.. code-block:: c++
+
+#include 
+
+int process(const float* buffer) [[clang::nonblocking]]
+{
+{
+__rtsan_disable();
+
+...
+
+__rtsan_enable();
+}
+}
+
+Each call to ``__rtsan_disable()`` must be paired with a subsequent call to 
``__rtsan_enable()`` to restore normal sanitizer functionality. If a 
corresponding ``rtsan_enable()`` call is not made, undefined behavior may 
result, potentially leaving the sanitizer permanently disabled for the rest of 
the program's execution.
+
+Compile-time sanitizer detection
+
+
+Clang provides the pre-processor macro ``__has_feature`` which may be used to 
detect if RealtimeSanitizer is enabled at compile-time.
+
+.. code-block:: c++
+
+#if defined(__has_feature) && __has_feature(realtime_sanitizer)
+...
+#endif

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


[clang] [NFC][rtsan] Docs of how to disable rtsan (PR #107707)

2024-09-07 Thread Chris Apple via cfe-commits

cjappl wrote:

CC for review @davidtrevelyan 

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


[clang] [NFC][rtsan] Docs of how to disable rtsan (PR #107707)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Chris Apple (cjappl)


Changes



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


1 Files Affected:

- (modified) clang/docs/RealtimeSanitizer.rst (+50) 


``diff
diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 799cd43509c6e6..7854cd3c0331a4 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -83,3 +83,53 @@ non-zero exit code.
 #13 0x00010230dd64 in main main.cpp:9
 #14 0x0001958960dc  ()
 #15 0x2f557ffc  ()
+
+Disabling
+-
+
+In some circumstances, you may want to suppress RealtimeSanitizer violations 
in a specific scope.
+
+In C++, this is achieved via  ``__rtsan::ScopedDisabler``. Within the scope 
where the ``ScopedDisabler`` object is instantiated, all sanitizer-reported 
violations are suppressed. This suppression applies to the current scope as 
well as all invoked functions, including any functions called transitively. 
+
+.. code-block:: c++
+
+#include 
+
+void process(const std::vector& buffer) [[clang::nonblocking]] {
+{
+__rtsan::ScopedDisabler d;
+...
+}
+}
+
+If RealtimeSanitizer is not enabled at compile time (i.e., the code is not 
compiled with the ``-fsanitize=realtime`` flag), the ``ScopedDisabler`` is 
compiled as a no-op.
+
+In C, you can use the ``__rtsan_disable()`` and ``rtsan_enable()`` functions 
to manually disable and re-enable RealtimeSanitizer checks. 
+
+.. code-block:: c++
+
+#include 
+
+int process(const float* buffer) [[clang::nonblocking]]
+{
+{
+__rtsan_disable();
+
+...
+
+__rtsan_enable();
+}
+}
+
+Each call to ``__rtsan_disable()`` must be paired with a subsequent call to 
``__rtsan_enable()`` to restore normal sanitizer functionality. If a 
corresponding ``rtsan_enable()`` call is not made, undefined behavior may 
result, potentially leaving the sanitizer permanently disabled for the rest of 
the program's execution.
+
+Compile-time sanitizer detection
+
+
+Clang provides the pre-processor macro ``__has_feature`` which may be used to 
detect if RealtimeSanitizer is enabled at compile-time.
+
+.. code-block:: c++
+
+#if defined(__has_feature) && __has_feature(realtime_sanitizer)
+...
+#endif

``




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


[clang] [AST] Avoid repeated hash lookups (NFC) (PR #107709)

2024-09-07 Thread Kazu Hirata via cfe-commits

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

While I am at it, I'm renaming Cache to UniqueDecls and removing
TotalNum in favor of UniqueDecls.size().


>From ab2bdf3bcaa18d6c1acaf47724a22dcd4254dd7b Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 7 Sep 2024 08:58:59 -0700
Subject: [PATCH] [AST] Avoid repeated hash lookups (NFC)

While I am at it, I'm renaming Cache to UniqueDecls and removing
TotalNum in favor of UniqueDecls.size().
---
 clang/lib/AST/OpenMPClause.cpp | 10 +++---
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/clang/lib/AST/OpenMPClause.cpp b/clang/lib/AST/OpenMPClause.cpp
index 7e73c076239410..eb15aa84406901 100644
--- a/clang/lib/AST/OpenMPClause.cpp
+++ b/clang/lib/AST/OpenMPClause.cpp
@@ -1125,16 +1125,12 @@ unsigned 
OMPClauseMappableExprCommon::getComponentsTotalNumber(
 
 unsigned OMPClauseMappableExprCommon::getUniqueDeclarationsTotalNumber(
 ArrayRef Declarations) {
-  unsigned TotalNum = 0u;
-  llvm::SmallPtrSet Cache;
+  llvm::SmallPtrSet UniqueDecls;
   for (const ValueDecl *D : Declarations) {
 const ValueDecl *VD = D ? cast(D->getCanonicalDecl()) : nullptr;
-if (Cache.count(VD))
-  continue;
-++TotalNum;
-Cache.insert(VD);
+UniqueDecls.insert(VD);
   }
-  return TotalNum;
+  return UniqueDecls.size();
 }
 
 OMPMapClause *OMPMapClause::Create(

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


[clang] [AST] Avoid repeated hash lookups (NFC) (PR #107709)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes

While I am at it, I'm renaming Cache to UniqueDecls and removing
TotalNum in favor of UniqueDecls.size().


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


1 Files Affected:

- (modified) clang/lib/AST/OpenMPClause.cpp (+3-7) 


``diff
diff --git a/clang/lib/AST/OpenMPClause.cpp b/clang/lib/AST/OpenMPClause.cpp
index 7e73c076239410..eb15aa84406901 100644
--- a/clang/lib/AST/OpenMPClause.cpp
+++ b/clang/lib/AST/OpenMPClause.cpp
@@ -1125,16 +1125,12 @@ unsigned 
OMPClauseMappableExprCommon::getComponentsTotalNumber(
 
 unsigned OMPClauseMappableExprCommon::getUniqueDeclarationsTotalNumber(
 ArrayRef Declarations) {
-  unsigned TotalNum = 0u;
-  llvm::SmallPtrSet Cache;
+  llvm::SmallPtrSet UniqueDecls;
   for (const ValueDecl *D : Declarations) {
 const ValueDecl *VD = D ? cast(D->getCanonicalDecl()) : nullptr;
-if (Cache.count(VD))
-  continue;
-++TotalNum;
-Cache.insert(VD);
+UniqueDecls.insert(VD);
   }
-  return TotalNum;
+  return UniqueDecls.size();
 }
 
 OMPMapClause *OMPMapClause::Create(

``




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


[clang-tools-extra] Add `std::span` to default `bugprone-dangling-handle.HandleClasses` (PR #107711)

2024-09-07 Thread Afonso Faria via cfe-commits

https://github.com/oracle-9 created 
https://github.com/llvm/llvm-project/pull/107711

`std::span` suffers from the same dangling issues as `std::string_view`. This 
patch adds `std::span` to the default list of handle classes in 
`bugprone-dangling-handle`, allowing clang-tidy to catch e.g. the following:
```cpp
span f() {
  // All these return values will dangle.
  array A;
  return {A};

  vector Array;
  return {Array};
}
```

>From 8528404715b4ca6dec7e251548870aba0c64bb04 Mon Sep 17 00:00:00 2001
From: Afonso Faria 
Date: Sat, 7 Sep 2024 18:03:48 +0100
Subject: [PATCH] Add std::span to default
 bugprone-dangling-handle.HandleClasses

---
 clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index d55df3a6d7b741..e13b1ceacc5395 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -97,8 +97,8 @@ DanglingHandleCheck::DanglingHandleCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   HandleClasses(utils::options::parseStringList(Options.get(
-  "HandleClasses",
-  "std::basic_string_view;std::experimental::basic_string_view"))),
+  "HandleClasses", "std::basic_string_view;std::experimental::basic_"
+   "string_view;std::span"))),
   IsAHandle(cxxRecordDecl(hasAnyName(HandleClasses)).bind("handle")) {}
 
 void DanglingHandleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {

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


[clang-tools-extra] Add `std::span` to default `bugprone-dangling-handle.HandleClasses` (PR #107711)

2024-09-07 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/107711
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] Add `std::span` to default `bugprone-dangling-handle.HandleClasses` (PR #107711)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




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

Author: Afonso Faria (oracle-9)


Changes

`std::span` suffers from the same dangling issues as `std::string_view`. This 
patch adds `std::span` to the default list of handle classes in 
`bugprone-dangling-handle`, allowing clang-tidy to catch e.g. the following:
```cpp
span f() {
  // All these return values will dangle.
  array A;
  return {A};

  vector Array;
  return {Array};
}
```

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


1 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
(+2-2) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index d55df3a6d7b741..e13b1ceacc5395 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -97,8 +97,8 @@ DanglingHandleCheck::DanglingHandleCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   HandleClasses(utils::options::parseStringList(Options.get(
-  "HandleClasses",
-  "std::basic_string_view;std::experimental::basic_string_view"))),
+  "HandleClasses", "std::basic_string_view;std::experimental::basic_"
+   "string_view;std::span"))),
   IsAHandle(cxxRecordDecl(hasAnyName(HandleClasses)).bind("handle")) {}
 
 void DanglingHandleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {

``




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


[clang-tools-extra] Add `std::span` to default `bugprone-dangling-handle.HandleClasses` (PR #107711)

2024-09-07 Thread Afonso Faria via cfe-commits

https://github.com/oracle-9 updated 
https://github.com/llvm/llvm-project/pull/107711

>From 8528404715b4ca6dec7e251548870aba0c64bb04 Mon Sep 17 00:00:00 2001
From: Afonso Faria 
Date: Sat, 7 Sep 2024 18:03:48 +0100
Subject: [PATCH 1/2] Add std::span to default
 bugprone-dangling-handle.HandleClasses

---
 clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index d55df3a6d7b741..e13b1ceacc5395 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -97,8 +97,8 @@ DanglingHandleCheck::DanglingHandleCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   HandleClasses(utils::options::parseStringList(Options.get(
-  "HandleClasses",
-  "std::basic_string_view;std::experimental::basic_string_view"))),
+  "HandleClasses", "std::basic_string_view;std::experimental::basic_"
+   "string_view;std::span"))),
   IsAHandle(cxxRecordDecl(hasAnyName(HandleClasses)).bind("handle")) {}
 
 void DanglingHandleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {

>From ffbb34269627c4afe01bae908dc886e756e73254 Mon Sep 17 00:00:00 2001
From: Afonso Faria 
Date: Sat, 7 Sep 2024 18:28:24 +0100
Subject: [PATCH 2/2] Update ReleaseNotes.rst

---
 clang-tools-extra/docs/ReleaseNotes.rst | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 8d028f8863cb7a..eec4f73459a229 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -108,6 +108,10 @@ Changes in existing checks
   ` check to suggest replacing
   the offending code with ``reinterpret_cast``, to more clearly express intent.
 
+- Improved :doc:`bugprone-dangling-handle
+  ` check to treat `std::span` as a
+  handle class.
+
 - Improved :doc:`modernize-use-std-format
   ` check to support replacing
   member function calls too.

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


[clang-tools-extra] [clang-tidy] Add `std::span` to default `bugprone-dangling-handle.HandleClasses` (PR #107711)

2024-09-07 Thread Afonso Faria via cfe-commits

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread Matheus Izvekov via cfe-commits


@@ -6753,16 +6758,41 @@ ASTContext::getNameForTemplate(TemplateName Name,
   case TemplateName::UsingTemplate:
 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
NameLoc);
+  case TemplateName::DeducedTemplate: {
+DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
+return getNameForTemplate(DTS->getUnderlying(), NameLoc);
+  }
   }
 
   llvm_unreachable("bad template name kind!");
 }
 
-TemplateName
-ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
+static const TemplateArgument *
+getDefaultTemplateArgumentOrNone(const NamedDecl *P) {
+  auto handleParam = [](auto *TP) -> const TemplateArgument * {
+if (!TP->hasDefaultArgument())
+  return nullptr;
+return &TP->getDefaultArgument().getArgument();
+  };
+  switch (P->getKind()) {
+  case NamedDecl::TemplateTypeParm:
+return handleParam(cast(P));
+  case NamedDecl::NonTypeTemplateParm:
+return handleParam(cast(P));
+  case NamedDecl::TemplateTemplateParm:
+return handleParam(cast(P));
+  default:
+llvm_unreachable("Unexpected template parameter kind");
+  }
+}

mizvekov wrote:

We'd have to break TypeDecl, DeclaratorDecl, TemplateDecl, etc into mixins.

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


[clang] [AST] Avoid repeated hash lookups (NFC) (PR #107709)

2024-09-07 Thread Nikita Popov via cfe-commits

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


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


[clang] 9c86a7e - [AST] Avoid repeated hash lookups (NFC) (#107709)

2024-09-07 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-09-07T11:23:26-07:00
New Revision: 9c86a7e9ec716fb54a0b74e13af12cb655723e53

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

LOG: [AST] Avoid repeated hash lookups (NFC) (#107709)

While I am at it, I'm renaming Cache to UniqueDecls and removing
TotalNum in favor of UniqueDecls.size().

Added: 


Modified: 
clang/lib/AST/OpenMPClause.cpp

Removed: 




diff  --git a/clang/lib/AST/OpenMPClause.cpp b/clang/lib/AST/OpenMPClause.cpp
index 7e73c076239410..eb15aa84406901 100644
--- a/clang/lib/AST/OpenMPClause.cpp
+++ b/clang/lib/AST/OpenMPClause.cpp
@@ -1125,16 +1125,12 @@ unsigned 
OMPClauseMappableExprCommon::getComponentsTotalNumber(
 
 unsigned OMPClauseMappableExprCommon::getUniqueDeclarationsTotalNumber(
 ArrayRef Declarations) {
-  unsigned TotalNum = 0u;
-  llvm::SmallPtrSet Cache;
+  llvm::SmallPtrSet UniqueDecls;
   for (const ValueDecl *D : Declarations) {
 const ValueDecl *VD = D ? cast(D->getCanonicalDecl()) : nullptr;
-if (Cache.count(VD))
-  continue;
-++TotalNum;
-Cache.insert(VD);
+UniqueDecls.insert(VD);
   }
-  return TotalNum;
+  return UniqueDecls.size();
 }
 
 OMPMapClause *OMPMapClause::Create(



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


[clang] [AST] Avoid repeated hash lookups (NFC) (PR #107709)

2024-09-07 Thread Kazu Hirata via cfe-commits

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


[clang] [llvm] [NFCI]Remove EntryCount from FunctionSummary and clean up surrounding synthetic count passes. (PR #107471)

2024-09-07 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lld-x86_64-win` running on 
`as-worker-93` while building `clang,llvm` at step 7 
"test-build-unified-tree-check-all".

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


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

```
Step 7 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/43/86' 
FAILED 
Script(shard):
--
GTEST_OUTPUT=json:C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-24332-43-86.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=86 GTEST_SHARD_INDEX=43 
C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe
--

Script:
--
C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe 
--gtest_filter=ProgramEnvTest.CreateProcessLongPath
--
C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(160): 
error: Expected equality of these values:
  0
  RC
Which is: -2

C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(163): 
error: fs::remove(Twine(LongPath)): did not return errc::success.
error number: 13
error message: permission denied



C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:160
Expected equality of these values:
  0
  RC
Which is: -2

C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:163
fs::remove(Twine(LongPath)): did not return errc::success.
error number: 13
error message: permission denied







```



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


[clang] [Clang][AST] {CXXDefaultArgExpr, CXXDefaultInitExpr}::hasRewrittenInit return true iff the init expression was really rebuild (PR #99748)

2024-09-07 Thread via cfe-commits


@@ -1013,15 +1013,15 @@ CXXDefaultArgExpr *CXXDefaultArgExpr::CreateEmpty(const 
ASTContext &C,
   return new (Mem) CXXDefaultArgExpr(EmptyShell(), HasRewrittenInit);
 }
 
-CXXDefaultArgExpr *CXXDefaultArgExpr::Create(const ASTContext &C,
- SourceLocation Loc,
- ParmVarDecl *Param,
- Expr *RewrittenExpr,
- DeclContext *UsedContext) {
+CXXDefaultArgExpr *
+CXXDefaultArgExpr::Create(const ASTContext &C, SourceLocation Loc,
+  ParmVarDecl *Param, DeclContext *UsedContext,
+  Expr *RewrittenExpr, bool HasRewrittenInit) {
   size_t Size = totalSizeToAlloc(RewrittenExpr != nullptr);

cor3ntin wrote:

I have the same question!
In particular in the test change, I think the expression _is_ rewritten.

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


[clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-09-07 Thread Matheus Izvekov via cfe-commits

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


[clang] [clang-tools-extra] [clang] Finish implementation of P0522 (PR #96023)

2024-09-07 Thread Matheus Izvekov via cfe-commits

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


[clang] [clang] Finish implementation of P0522 (PR #96023)

2024-09-07 Thread Matheus Izvekov via cfe-commits

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

>From b29e3d3285a414df74a75404c6fe4a39f4a0725d Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |  10 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 160 +++-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  26 +-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  82 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 17 files changed, 652 insertions(+), 266 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f4e54a0470d862..4c715967c6fde2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,10 @@ C++23 Feature Support
 C++20 Feature Support
 ^
 
+C++17 Feature Support
+^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 Resolutions to C++ Defect Reports
 ^
@@ -270,6 +274,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
 - Improved diagnostic when trying to befriend a concept. (#GH45182).
@@ -355,6 +363,8 @@ Bug Fixes to C++ Support
 - Correctly check constraints of explicit instantiations of member functions. 
(#GH46029)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 - Fixed an assertion failure about a constraint of a friend function template 
references to a value with greater
   template depth than the friend function template. (#GH98

[clang] [clang-format] Fix a bug in annotating CastRParen (PR #107675)

2024-09-07 Thread Björn Schäpers via cfe-commits

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


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


[clang] Reapply "[Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer" (PR #97308)

2024-09-07 Thread via cfe-commits


@@ -750,8 +750,22 @@ void InitListChecker::FillInEmptyInitForField(unsigned 
Init, FieldDecl *Field,
 if (Field->hasInClassInitializer()) {
   if (VerifyOnly)
 return;
-
-  ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
+  ExprResult DIE;
+  {
+// Enter a default initializer rebuild context, then we can support
+// lifetime extension of temporary created by aggregate initialization
+// using a default member initializer.
+// CWG1815 (https://wg21.link/CWG1815).
+EnterExpressionEvaluationContext RebuildDefaultInit(
+SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+/*LambdaContextDecl=*/nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other, true);

cor3ntin wrote:

```suggestion
EnterExpressionEvaluationContext RebuildDefaultInit(
SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
```

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


[clang] Reapply "[Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer" (PR #97308)

2024-09-07 Thread via cfe-commits


@@ -7849,13 +7854,17 @@ class Sema final : public SemaBase {
   /// keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext
   /// flag from previous context.
   void keepInLifetimeExtendingContext() {
-if (ExprEvalContexts.size() > 2 &&
-parentEvaluationContext().InLifetimeExtendingContext) {
-  auto &LastRecord = ExprEvalContexts.back();
-  auto &PrevRecord = parentEvaluationContext();
-  LastRecord.InLifetimeExtendingContext =
-  PrevRecord.InLifetimeExtendingContext;
-}
+if (ExprEvalContexts.size() > 2)
+  currentEvaluationContext().InLifetimeExtendingContext =
+  parentEvaluationContext().InLifetimeExtendingContext;
+  }
+
+  /// keepInRebuildDefaultArgInitContext - Pull down
+  /// RebuildDefaultArgOrDefaultInit flag from previous context.
+  void keepInRebuildDefaultArgOrInitContext() {
+if (ExprEvalContexts.size() > 2)
+  currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
+  parentEvaluationContext().RebuildDefaultArgOrDefaultInit;

cor3ntin wrote:

Ditto

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


[clang] Reapply "[Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer" (PR #97308)

2024-09-07 Thread via cfe-commits


@@ -5479,6 +5479,7 @@ void Sema::InstantiateVariableInitializer(
 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
 
 keepInLifetimeExtendingContext();
+keepInRebuildDefaultArgOrInitContext();

cor3ntin wrote:

I am not sure that setting the flag in a one line function is better than doing 
it directly there

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


[clang] The real option name and not the alias used is displayed in msgs when using a config file (PR #107613)

2024-09-07 Thread Sean Perry via cfe-commits

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

>From 27f31954976948e4e0d194db5da6bc550b4c2200 Mon Sep 17 00:00:00 2001
From: Sean Perry 
Date: Fri, 6 Sep 2024 10:54:07 -0500
Subject: [PATCH 1/2] clone the alias option too

---
 clang/lib/Driver/Driver.cpp  | 11 +++
 clang/test/Driver/arm-execute-only.c |  3 +++
 2 files changed, 14 insertions(+)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 5b3783e20eabba..e4604f4e3ea753 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -998,6 +998,17 @@ static void appendOneArg(InputArgList &Args, const Arg 
*Opt,
   Copy->setOwnsValues(Opt->getOwnsValues());
   Opt->setOwnsValues(false);
   Args.append(Copy);
+  if (Opt->getAlias()) {
+const Arg *Alias = Opt->getAlias();
+unsigned Index = Args.MakeIndex(Alias->getSpelling());
+auto AliasCopy = std::make_unique(Alias->getOption(), 
Args.getArgString(Index),
+ Index, BaseArg);
+AliasCopy->getValues() = Alias->getValues();
+AliasCopy->setOwnsValues(false);
+if (Alias->isClaimed())
+  AliasCopy->claim();
+Copy->setAlias(std::move(AliasCopy));
+  }
 }
 
 bool Driver::readConfigFile(StringRef FileName,
diff --git a/clang/test/Driver/arm-execute-only.c 
b/clang/test/Driver/arm-execute-only.c
index a9bf1656fd27e5..d654ec364a87f5 100644
--- a/clang/test/Driver/arm-execute-only.c
+++ b/clang/test/Driver/arm-execute-only.c
@@ -19,6 +19,9 @@
 
 // RUN: not %clang -### --target=arm-arm-none-eabi -march=armv8-m.main 
-mpure-code -mno-movt %s 2>&1 \
 // RUN:| FileCheck %s -check-prefix CHECK-PURE-CODE-NO-MOVT
+// RUN: echo "-DABC"  > %t.cfg
+// RUN: not %clang -### --target=arm-arm-none-eabi -march=armv8-m.main 
-mpure-code -mno-movt --config %t.cfg %s 2>&1 \
+// RUN:| FileCheck %s -check-prefix CHECK-PURE-CODE-NO-MOVT
 // CHECK-PURE-CODE-NO-MOVT: error: option '-mpure-code' cannot be specified 
with '-mno-movt'
 
 // RUN: not %clang -### --target=arm-arm-none-eabi -march=armv6-m 
-mexecute-only -fropi %s 2>&1 \

>From 261e525859295294075bb77a1aa3bd6778d87d68 Mon Sep 17 00:00:00 2001
From: Sean Perry 
Date: Fri, 6 Sep 2024 12:37:51 -0500
Subject: [PATCH 2/2] fix formatting

---
 clang/lib/Driver/Driver.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index e4604f4e3ea753..5e2675db6535f1 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1001,8 +1001,8 @@ static void appendOneArg(InputArgList &Args, const Arg 
*Opt,
   if (Opt->getAlias()) {
 const Arg *Alias = Opt->getAlias();
 unsigned Index = Args.MakeIndex(Alias->getSpelling());
-auto AliasCopy = std::make_unique(Alias->getOption(), 
Args.getArgString(Index),
- Index, BaseArg);
+auto AliasCopy = std::make_unique(
+Alias->getOption(), Args.getArgString(Index), Index, BaseArg);
 AliasCopy->getValues() = Alias->getValues();
 AliasCopy->setOwnsValues(false);
 if (Alias->isClaimed())

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


[clang] Reapply "[Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer" (PR #97308)

2024-09-07 Thread via cfe-commits


@@ -7849,13 +7854,17 @@ class Sema final : public SemaBase {
   /// keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext
   /// flag from previous context.
   void keepInLifetimeExtendingContext() {
-if (ExprEvalContexts.size() > 2 &&
-parentEvaluationContext().InLifetimeExtendingContext) {
-  auto &LastRecord = ExprEvalContexts.back();
-  auto &PrevRecord = parentEvaluationContext();
-  LastRecord.InLifetimeExtendingContext =
-  PrevRecord.InLifetimeExtendingContext;
-}
+if (ExprEvalContexts.size() > 2)

cor3ntin wrote:

I wonder if this `2` is correct. Pre-existing but it should probably be `1` 
(ie, if there are more than 1 context, there is a parent. Maybe we should just 
assert >1 actually
(there is always going a context bot the default init + 1 for the translation 
unit)

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


[clang] [clang] Finish implementation of P0522 (PR #96023)

2024-09-07 Thread via cfe-commits

cor3ntin wrote:

My concern here is that there is an ongoing lively discussion in CWG. And while 
I think most solutions considered will end up being isomorphic in outcome, I 
don't know that we want to go experimenting too much before the dust settles a 
bit (there is wild variation between implementations both pre and post P0522)

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


[clang-tools-extra] [NFC][clang-tidy] document fix to bugprone-return-const-ref-from-parameter (PR #107641)

2024-09-07 Thread Danny Mösch via cfe-commits

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


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


[clang-tools-extra] [clang-tidy] fix false positive in modernize-min-max-use-initializer-list (PR #107649)

2024-09-07 Thread Danny Mösch via cfe-commits


@@ -168,9 +170,11 @@ generateReplacements(const MatchFinder::MatchResult &Match,
   CharSourceRange::getTokenRange(InnerResult.First->getEndLoc(;
 }
 
-const SmallVector InnerReplacements = generateReplacements(
+const auto [FoundNestedCallInner, InnerReplacements] = 
generateReplacements(
 Match, InnerCall, InnerResult, IgnoreNonTrivialTypes,
-IgnoreTrivialTypesOfSizeAbove);
+IgnoreTrivialTypesOfSizeAbove, false);
+
+FoundNestedCall |= FoundNestedCallInner;

SimplyDanny wrote:

Isn't the result always `true` with the value being reset to `true` in line 149 
and having an `|=` here?

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


[clang-tools-extra] [clang-tidy] fix false positive in modernize-min-max-use-initializer-list (PR #107649)

2024-09-07 Thread Danny Mösch via cfe-commits


@@ -72,11 +72,10 @@ static FindArgsResult findArgs(const CallExpr *Call) {
   return Result;
 }
 
-static SmallVector
-generateReplacements(const MatchFinder::MatchResult &Match,
- const CallExpr *TopCall, const FindArgsResult &Result,
- const bool IgnoreNonTrivialTypes,
- const std::uint64_t IgnoreTrivialTypesOfSizeAbove) {
+static std::pair> generateReplacements(
+const MatchFinder::MatchResult &Match, const CallExpr *TopCall,
+const FindArgsResult &Result, const bool IgnoreNonTrivialTypes,
+const std::uint64_t IgnoreTrivialTypesOfSizeAbove, bool FoundNestedCall) {

SimplyDanny wrote:

All callers use `false` as the last argument. Is the new argument needed at all?

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


[clang] [clang][docs] Add clang-tutor to ExternalClangExamples. (PR #107665)

2024-09-07 Thread Danny Mösch via cfe-commits


@@ -98,3 +98,6 @@ List of projects and tools
uses of reserved identifiers to ensuring that code adheres to lifecycle
protocols for certain LibreOffice-specific classes.  They may serve as
examples for writing RecursiveASTVisitor-based plugins."
+
+``_
+   "A collection of out-of-tree Clang plugins for teaching and learning"

SimplyDanny wrote:

```suggestion
   "A collection of out-of-tree Clang plugins for teaching and learning."
```


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


[clang] [clang] Finish implementation of P0522 (PR #96023)

2024-09-07 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

I believe we have achieved consensus on getting rid of the fallback rules, and 
this patch does not do much beyond that, if anything.

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


[clang-tools-extra] [clang-tidy] only diagnose definitions in readability-enum-initial-value (PR #107652)

2024-09-07 Thread Danny Mösch via cfe-commits

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


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


[clang-tools-extra] [NFC][clang-tidy] reword diagnostic note in definitions-in-headers (PR #106862)

2024-09-07 Thread Danny Mösch via cfe-commits

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


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


[clang] [clang-tools-extra] [clangd] show lambda name instead of operator() in signature help (PR #101857)

2024-09-07 Thread Timothy Akintilo via cfe-commits

https://github.com/tilobyte updated 
https://github.com/llvm/llvm-project/pull/101857

>From c1afe853ccacae1605fecfe552bb9a263c6b8c1d Mon Sep 17 00:00:00 2001
From: Timothy Akintilo 
Date: Sat, 27 Jul 2024 16:17:46 -0500
Subject: [PATCH 1/3] use lambda name instead of operator()

---
 clang-tools-extra/clangd/CodeComplete.cpp |  2 ++
 .../clangd/unittests/CodeCompleteTests.cpp|  9 +++
 .../include/clang/Sema/CodeCompleteConsumer.h | 18 ++
 clang/include/clang/Sema/Overload.h   |  5 
 clang/include/clang/Sema/Sema.h   | 22 -
 clang/lib/Sema/CodeCompleteConsumer.cpp   | 10 +++-
 clang/lib/Sema/SemaCodeComplete.cpp   | 17 ++---
 clang/lib/Sema/SemaLookup.cpp |  3 ++-
 clang/lib/Sema/SemaOverload.cpp   | 24 +--
 9 files changed, 82 insertions(+), 28 deletions(-)

diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 89eee392837af4..4f8a53aa7aae7e 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1139,6 +1139,8 @@ class SignatureHelpCollector final : public 
CodeCompleteConsumer {
   switch (K) {
   case OC::CK_Aggregate:
 return 0;
+  case OC::CK_Lambda:
+[[fallthrough]];
   case OC::CK_Function:
 return 1;
   case OC::CK_FunctionType:
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 96d1ee1f0add73..4f748168d75aa7 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1437,6 +1437,15 @@ TEST(SignatureHelpTest, Overloads) {
   EXPECT_EQ(0, Results.activeParameter);
 }
 
+TEST(SignatureHelpTest, ShowLambdaNameInsteadOfOperatorParens) {
+  auto const Results = signatures(R"cpp(
+auto foo = [](int x, int y){};
+int main() { foo(^); }
+  )cpp");
+  EXPECT_THAT(Results.signatures,
+  UnorderedElementsAre(sig("foo([[int x]], [[int y]]) -> void")));
+}
+
 TEST(SignatureHelpTest, FunctionPointers) {
   llvm::StringLiteral Tests[] = {
   // Variable of function pointer type
diff --git a/clang/include/clang/Sema/CodeCompleteConsumer.h 
b/clang/include/clang/Sema/CodeCompleteConsumer.h
index 0924dc27af82b5..a6530c3c93d912 100644
--- a/clang/include/clang/Sema/CodeCompleteConsumer.h
+++ b/clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -1028,6 +1028,9 @@ class CodeCompleteConsumer {
   /// The candidate is a function declaration.
   CK_Function,
 
+  // The candidate is a lambda operator().
+  CK_Lambda,
+
   /// The candidate is a function template, arguments are being completed.
   CK_FunctionTemplate,
 
@@ -1055,6 +1058,13 @@ class CodeCompleteConsumer {
   /// Kind == CK_Function.
   FunctionDecl *Function;
 
+  /// The lambda operator() candidate paired with the
+  /// lambda variable, available when Kind == CK_Lambda.
+  struct {
+FunctionDecl *OperatorParens;
+VarDecl *Var;
+  } Lambda;
+
   /// The function template overload candidate, available when
   /// Kind == CK_FunctionTemplate.
   FunctionTemplateDecl *FunctionTemplate;
@@ -1082,6 +1092,12 @@ class CodeCompleteConsumer {
   assert(Function != nullptr);
 }
 
+OverloadCandidate(FunctionDecl *LambdaOperatorParens, VarDecl *LambdaVar)
+: Kind(CK_Lambda), Lambda{LambdaOperatorParens, LambdaVar} {
+  assert(Lambda.OperatorParens != nullptr);
+  assert(Lambda.Var != nullptr);
+}
+
 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) {
   assert(FunctionTemplateDecl != nullptr);
@@ -1112,6 +1128,8 @@ class CodeCompleteConsumer {
 /// function declaration for a function template.
 FunctionDecl *getFunction() const;
 
+VarDecl *getLambdaVarDecl() const;
+
 /// Retrieve the function template overload candidate.
 FunctionTemplateDecl *getFunctionTemplate() const {
   assert(getKind() == CK_FunctionTemplate && "Not a function template");
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index d6a6cee62a7528..7c4e82f07de02e 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -876,6 +876,11 @@ class Sema;
 /// function pointer or reference (C++ [over.call.object]).
 FunctionDecl *Function;
 
+/// LambdaName - When the OverloadCandidate is for a
+/// lambda's operator(), points to the declaration of
+/// the lambda variable.
+VarDecl *LambdaName{nullptr};
+
 /// FoundDecl - The original declaration that was looked up /
 /// invented / otherwise found, together with its access.
 /// Might be a UsingShadowDecl or a FunctionTemplateDec

[clang] [llvm] [TableGen] Change SetTheory set/vec to use const Record * (PR #107692)

2024-09-07 Thread Rahul Joshi via cfe-commits


@@ -2808,10 +2806,10 @@ RecordRecTy *Record::getType() {
   return RecordRecTy::get(TrackedRecords, DirectSCs);
 }
 
-DefInit *Record::getDefInit() {
+DefInit *Record::getDefInit() const {
   if (!CorrespondingDefInit) {
-CorrespondingDefInit =
-new (TrackedRecords.getImpl().Allocator) DefInit(this);
+CorrespondingDefInit = new (TrackedRecords.getImpl().Allocator)

jurahul wrote:

The only issue is here, where 

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


[clang] [llvm] [TableGen] Change SetTheory set/vec to use const Record * (PR #107692)

2024-09-07 Thread Rahul Joshi via cfe-commits

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


[clang] [llvm] [TableGen] Change SetTheory set/vec to use const Record * (PR #107692)

2024-09-07 Thread Rahul Joshi via cfe-commits

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


[clang] [llvm] [TableGen] Change SetTheory set/vec to use const Record * (PR #107692)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Rahul Joshi (jurahul)


Changes

Change SetTheory::RecSet/RecVec to use const Record pointers.

---

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


11 Files Affected:

- (modified) clang/utils/TableGen/NeonEmitter.cpp (+1-1) 
- (modified) llvm/include/llvm/TableGen/Record.h (+3-3) 
- (modified) llvm/include/llvm/TableGen/SetTheory.h (+2-2) 
- (modified) llvm/lib/TableGen/Record.cpp (+4-6) 
- (modified) llvm/utils/TableGen/AsmMatcherEmitter.cpp (+20-18) 
- (modified) llvm/utils/TableGen/Common/CodeGenRegisters.cpp (+13-16) 
- (modified) llvm/utils/TableGen/Common/CodeGenRegisters.h (+9-7) 
- (modified) llvm/utils/TableGen/Common/CodeGenSchedule.cpp (+14-13) 
- (modified) llvm/utils/TableGen/Common/CodeGenSchedule.h (+6-4) 
- (modified) llvm/utils/TableGen/RegisterInfoEmitter.cpp (+15-15) 
- (modified) llvm/utils/TableGen/TableGen.cpp (+1-1) 


``diff
diff --git a/clang/utils/TableGen/NeonEmitter.cpp 
b/clang/utils/TableGen/NeonEmitter.cpp
index e0d7b0db7f5780..4707ce1ea3b792 100644
--- a/clang/utils/TableGen/NeonEmitter.cpp
+++ b/clang/utils/TableGen/NeonEmitter.cpp
@@ -1636,7 +1636,7 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
   int64_t VectorSize = cast(Expr->getArg(0))->getValue();
   VectorSize /= ElementSize;
 
-  std::vector Revved;
+  std::vector Revved;
   for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
 for (int LI = VectorSize - 1; LI >= 0; --LI) {
   Revved.push_back(Elts2[VI + LI]);
diff --git a/llvm/include/llvm/TableGen/Record.h 
b/llvm/include/llvm/TableGen/Record.h
index 5d36fcf57e23e3..f6c751af6bb836 100644
--- a/llvm/include/llvm/TableGen/Record.h
+++ b/llvm/include/llvm/TableGen/Record.h
@@ -1323,7 +1323,7 @@ class DefInit : public TypedInit {
 return I->getKind() == IK_DefInit;
   }
 
-  static DefInit *get(Record*);
+  static DefInit *get(const Record *);
 
   Init *convertInitializerTo(RecTy *Ty) const override;
 
@@ -1673,7 +1673,7 @@ class Record {
   RecordKeeper &TrackedRecords;
 
   // The DefInit corresponding to this record.
-  DefInit *CorrespondingDefInit = nullptr;
+  mutable DefInit *CorrespondingDefInit = nullptr;
 
   // Unique record ID.
   unsigned ID;
@@ -1740,7 +1740,7 @@ class Record {
   RecordRecTy *getType();
 
   /// get the corresponding DefInit.
-  DefInit *getDefInit();
+  DefInit *getDefInit() const;
 
   bool isClass() const { return Kind == RK_Class; }
 
diff --git a/llvm/include/llvm/TableGen/SetTheory.h 
b/llvm/include/llvm/TableGen/SetTheory.h
index 954453b783d4d8..771dcff2f214c3 100644
--- a/llvm/include/llvm/TableGen/SetTheory.h
+++ b/llvm/include/llvm/TableGen/SetTheory.h
@@ -64,8 +64,8 @@ class Record;
 
 class SetTheory {
 public:
-  using RecVec = std::vector;
-  using RecSet = SmallSetVector;
+  using RecVec = std::vector;
+  using RecSet = SmallSetVector;
 
   /// Operator - A callback representing a DAG operator.
   class Operator {
diff --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp
index 17afa2f7eb1b99..79c5e071e55f23 100644
--- a/llvm/lib/TableGen/Record.cpp
+++ b/llvm/lib/TableGen/Record.cpp
@@ -2235,9 +2235,7 @@ Init *VarBitInit::resolveReferences(Resolver &R) const {
 DefInit::DefInit(Record *D)
 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
 
-DefInit *DefInit::get(Record *R) {
-  return R->getDefInit();
-}
+DefInit *DefInit::get(const Record *R) { return R->getDefInit(); }
 
 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
   if (auto *RRT = dyn_cast(Ty))
@@ -2808,10 +2806,10 @@ RecordRecTy *Record::getType() {
   return RecordRecTy::get(TrackedRecords, DirectSCs);
 }
 
-DefInit *Record::getDefInit() {
+DefInit *Record::getDefInit() const {
   if (!CorrespondingDefInit) {
-CorrespondingDefInit =
-new (TrackedRecords.getImpl().Allocator) DefInit(this);
+CorrespondingDefInit = new (TrackedRecords.getImpl().Allocator)
+DefInit(const_cast(this));
   }
   return CorrespondingDefInit;
 }
diff --git a/llvm/utils/TableGen/AsmMatcherEmitter.cpp 
b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
index f351087ad212f7..574a3344a02f8d 100644
--- a/llvm/utils/TableGen/AsmMatcherEmitter.cpp
+++ b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
@@ -140,7 +140,7 @@ class AsmMatcherInfo;
 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, 
and
 // can even affect compiler output (at least seen in diagnostics produced when
 // all matches fail). So we use a type that sorts them consistently.
-typedef std::set RegisterSet;
+typedef std::set RegisterSet;
 
 class AsmMatcherEmitter {
   RecordKeeper &Records;
@@ -242,7 +242,7 @@ struct ClassInfo {
   if (!isRegisterClass() || !RHS.isRegisterClass())
 return false;
 
-  std::vector Tmp;
+  std::vector Tmp;
   std::set_intersection(Registers.begin(), Registers.end(),
 RHS.Registe

[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #107728)

2024-09-07 Thread Kazu Hirata via cfe-commits

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

None

>From ddde00b62ef1acc5532ea24c2fa15a8c67e69ac9 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 7 Sep 2024 11:39:50 -0700
Subject: [PATCH] [Frontend] Avoid repeated hash lookups (NFC)

---
 clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp | 16 
 1 file changed, 4 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp 
b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
index f618c536b5f3c6..31ec86e2e4f096 100644
--- a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -4340,17 +4340,13 @@ void 
RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
   ValueDecl *VD = Exp->getDecl();
   BlockDeclRefs.push_back(Exp);
   if (!VD->hasAttr()) {
-if (!BlockByCopyDeclsPtrSet.count(VD)) {
-  BlockByCopyDeclsPtrSet.insert(VD);
+if (BlockByCopyDeclsPtrSet.insert(VD).second)
   BlockByCopyDecls.push_back(VD);
-}
 continue;
   }
 
-  if (!BlockByRefDeclsPtrSet.count(VD)) {
-BlockByRefDeclsPtrSet.insert(VD);
+  if (BlockByRefDeclsPtrSet.insert(VD).second)
 BlockByRefDecls.push_back(VD);
-  }
 
   // imported objects in the inner blocks not used in the outer
   // blocks must be copied/disposed in the outer block as well.
@@ -5161,18 +5157,14 @@ void 
RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
 // Unique all "by copy" declarations.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
   if (!BlockDeclRefs[i]->getDecl()->hasAttr()) {
-if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
-  BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
+if (BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()).second)
   BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
-}
   }
 // Unique all "by ref" declarations.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
   if (BlockDeclRefs[i]->getDecl()->hasAttr()) {
-if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
-  BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
+if (BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()).second)
   BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
-}
   }
 // Find any imported blocks...they will need special attention.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)

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


[clang] [Frontend] Avoid repeated hash lookups (NFC) (PR #107728)

2024-09-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes



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


1 Files Affected:

- (modified) clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp (+4-12) 


``diff
diff --git a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp 
b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
index f618c536b5f3c6..31ec86e2e4f096 100644
--- a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -4340,17 +4340,13 @@ void 
RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
   ValueDecl *VD = Exp->getDecl();
   BlockDeclRefs.push_back(Exp);
   if (!VD->hasAttr()) {
-if (!BlockByCopyDeclsPtrSet.count(VD)) {
-  BlockByCopyDeclsPtrSet.insert(VD);
+if (BlockByCopyDeclsPtrSet.insert(VD).second)
   BlockByCopyDecls.push_back(VD);
-}
 continue;
   }
 
-  if (!BlockByRefDeclsPtrSet.count(VD)) {
-BlockByRefDeclsPtrSet.insert(VD);
+  if (BlockByRefDeclsPtrSet.insert(VD).second)
 BlockByRefDecls.push_back(VD);
-  }
 
   // imported objects in the inner blocks not used in the outer
   // blocks must be copied/disposed in the outer block as well.
@@ -5161,18 +5157,14 @@ void 
RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
 // Unique all "by copy" declarations.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
   if (!BlockDeclRefs[i]->getDecl()->hasAttr()) {
-if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
-  BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
+if (BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()).second)
   BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
-}
   }
 // Unique all "by ref" declarations.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
   if (BlockDeclRefs[i]->getDecl()->hasAttr()) {
-if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
-  BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
+if (BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()).second)
   BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
-}
   }
 // Find any imported blocks...they will need special attention.
 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)

``




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


[clang] [clang-format] Fix a regression on BAS_AlwaysBreak (PR #107506)

2024-09-07 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/107506

>From bd7da6ec9afabd829010db4c33d088590ab68b5a Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 5 Sep 2024 19:44:46 -0700
Subject: [PATCH 1/2] [clang-format] Fix a regression on BAS_AlwaysBreak

Fixes #107401.
---
 clang/lib/Format/ContinuationIndenter.cpp | 2 +-
 clang/unittests/Format/FormatTestJS.cpp   | 8 
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 5843571718b3a2..f65c1640a8765a 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -861,7 +861,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   //  or
   //  cal(
   //   new SomethingElseee());
-  !IsSimpleFunction(Current)) {
+  Current.isNot(tok::comment) && !IsSimpleFunction(Current)) {
 CurrentState.NoLineBreak = true;
   }
 
diff --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 4b29ba720f6823..a0b663170c7b33 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -2850,5 +2850,13 @@ TEST_F(FormatTestJS, DontBreakFieldsAsGoToLabels) {
"};");
 }
 
+TEST_F(FormatTestJS, BreakAfterOpenBracket) {
+  auto Style = getGoogleStyle(FormatStyle::LK_JavaScript);
+  EXPECT_EQ(Style.AlignAfterOpenBracket, FormatStyle::BAS_AlwaysBreak);
+  verifyFormat("ctrl.onCopy(/** @type {!WizEvent}*/ (\n"
+   "{event, targetElement: {el: () => selectedElement}}));",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang

>From 920e26dcd9c5d7f78a4f8b572451ecae73dd9201 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 7 Sep 2024 16:40:04 -0700
Subject: [PATCH 2/2] Rename `InSimpleFunction` to `StartsSimpleOneArgList` and
 skip to the next token if the argument is a comment.

---
 clang/lib/Format/ContinuationIndenter.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index f65c1640a8765a..58e6b78ce578e4 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -815,7 +815,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
 return Tok.is(tok::l_paren) && Tok.ParameterCount > 0 && Tok.Previous &&
Tok.Previous->is(tok::identifier);
   };
-  const auto IsInTemplateString = [this](const FormatToken &Tok) {
+  auto IsInTemplateString = [this](const FormatToken &Tok) {
 if (!Style.isJavaScript())
   return false;
 for (const auto *Prev = &Tok; Prev; Prev = Prev->Previous) {
@@ -827,7 +827,10 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
 return false;
   };
   // Identifies simple (no expression) one-argument function calls.
-  const auto IsSimpleFunction = [&](const FormatToken &Tok) {
+  auto StartsSimpleOneArgList = [&](const FormatToken &TokAfterLParen) {
+assert(TokAfterLParen.isNot(tok::comment) || TokAfterLParen.Next);
+const auto &Tok =
+TokAfterLParen.is(tok::comment) ? *TokAfterLParen.Next : 
TokAfterLParen;
 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
   return false;
 // Nested calls that involve `new` expressions also look like simple
@@ -861,7 +864,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   //  or
   //  cal(
   //   new SomethingElseee());
-  Current.isNot(tok::comment) && !IsSimpleFunction(Current)) {
+  !StartsSimpleOneArgList(Current)) {
 CurrentState.NoLineBreak = true;
   }
 

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


[clang] [clang-format] Fix a regression on BAS_AlwaysBreak (PR #107506)

2024-09-07 Thread Owen Pan via cfe-commits


@@ -861,7 +861,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   //  or
   //  cal(
   //   new SomethingElseee());
-  !IsSimpleFunction(Current)) {
+  Current.isNot(tok::comment) && !IsSimpleFunction(Current)) {

owenca wrote:

> would it make sense to introduce this into `IsSimpleFunction` ? similar to 
> handling of `new` keyword in there?

I did that at first but thought it would be confusing to say that a comment is 
a simple function (or function call).

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


[clang] [clang-format] Fix a regression on BAS_AlwaysBreak (PR #107506)

2024-09-07 Thread Owen Pan via cfe-commits

owenca wrote:

> i've also found 3 more cases that point back to same patch in #107574, in 
> case you want to address all of them with this change

I'd rather make incremental changes. Maybe you or @gedare can give them a try.

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


  1   2   >