[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

steakhal wrote:

Could you also add this test case?
```c++
namespace std {
struct __mutex_base {
  void lock();
};
struct mutex : __mutex_base {
  void unlock();
  bool try_lock();
};
template  struct scoped_lock {
  explicit scoped_lock(MutexTypes&... m);
  ~scoped_lock();
};
template  class scoped_lock {
public:
  explicit scoped_lock(MutexType& m) : m(m) { m.lock(); }
  ~scoped_lock() { m.unlock(); }
private:
  MutexType& m;
};
} // namespace std

extern "C" unsigned int sleep(unsigned int seconds);

int magic_number;
std::mutex m;

void fixed() {
  int current;
  for (int items_processed = 0; items_processed < 100; ++items_processed) {
{
  std::scoped_lock guard(m);
  current = magic_number;
}
sleep(current); // expected no warning
  }
}
```
Or is it already implied by other tests?

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


[clang] 3dbb6be - [NFC] Comment fix: "does specify state that" -> "does specify that" (#106338)

2024-08-28 Thread via cfe-commits

Author: Michael Park
Date: 2024-08-28T09:05:43+02:00
New Revision: 3dbb6befa837c5daa07de1e0daa45e5943ee9520

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

LOG: [NFC] Comment fix: "does specify state that" -> "does specify that" 
(#106338)

Added: 


Modified: 
clang/lib/AST/ComputeDependence.cpp

Removed: 




diff  --git a/clang/lib/AST/ComputeDependence.cpp 
b/clang/lib/AST/ComputeDependence.cpp
index 62ca15ea398f5c..6ef49790481aca 100644
--- a/clang/lib/AST/ComputeDependence.cpp
+++ b/clang/lib/AST/ComputeDependence.cpp
@@ -164,7 +164,7 @@ ExprDependence clang::computeDependence(BinaryOperator *E) {
 ExprDependence clang::computeDependence(ConditionalOperator *E) {
   // The type of the conditional operator depends on the type of the 
conditional
   // to support the GCC vector conditional extension. Additionally,
-  // [temp.dep.expr] does specify state that this should be dependent on ALL 
sub
+  // [temp.dep.expr] does specify that this should be dependent on ALL sub
   // expressions.
   return E->getCond()->getDependence() | E->getLHS()->getDependence() |
  E->getRHS()->getDependence();



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


[clang] [NFC] Comment fix: "does specify state that" -> "does specify that" (PR #106338)

2024-08-28 Thread Timm Baeder via cfe-commits

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/106240

>From 0c86e46516466f9513652a04ba87aa2a018ff6b8 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 27 Aug 2024 17:52:25 +0200
Subject: [PATCH 1/6] [analyzer] Fix false positive for mutexes inheriting
 mutex_base

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This possibly fixes #104241

CPP-5541
---
 .../Checkers/BlockInCriticalSectionChecker.cpp |  6 --
 .../Analysis/block-in-critical-section-inheritance.cpp | 10 ++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..52ff639c6b8022 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -245,8 +245,10 @@ static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+if (const MemRegion *Reg = Descr.getRegion(Call, IsLock))
+  return Reg->getBaseRegion();
+return nullptr;
   },
   Descriptor);
 }
diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index db20df8c60a5c9..c60ba2632cee25 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -29,3 +29,13 @@ void gh_99628() {
   // expected-note@-2 {{Call to blocking function 'sleep' inside of critical 
section}}
   m.unlock();
 }
+
+void no_false_positive_gh_104241() {
+  std::mutex m;
+  m.lock();
+  // If inheritance not handled properly, this unlock might not match the lock
+  // above because technically they act on different memory regions:
+  // __mutex_base and mutex.
+  m.unlock();
+  sleep(10); // no-warning
+}

>From 013a6d138b38c51c64860a99b95591491f86c223 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:27:50 +0200
Subject: [PATCH 2/6] Record a false negative associated with the new mutex
 canonicalization

---
 .../block-in-critical-section-inheritance.cpp  | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index c60ba2632cee25..5f6fa565f42fb9 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -39,3 +39,17 @@ void no_false_positive_gh_104241() {
   m.unlock();
   sleep(10); // no-warning
 }
+
+struct TwoMutexes {
+  std::mutex m1;
+  std::mutex m2;
+};
+
+void two_mutexes_false_negative(TwoMutexes &tm) {
+  tm.m1.lock();
+  tm.m2.unlock();
+  // Critical section is associated with tm now so tm.m1 and tm.m2 are
+  // undistinguishiable
+  sleep(10); // False-negative
+  tm.m1.unlock();
+}

>From 744272e0f1ccd5217c0d456a7c499a9bcae84679 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:33:02 +0200
Subject: [PATCH 3/6] Fix false negative for field regions

---
 .../Checkers/BlockInCriticalSectionChecker.cpp   | 9 -
 .../Analysis/block-in-critical-section-inheritance.cpp   | 9 +
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 52ff639c6b8022..fd8700902c1835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -241,13 +241,20 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
+  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
   [&Call, IsLock]

[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

necto wrote:

> Could you also add this test case?
> 
> ```c++
> ```
> 
> Or is it already implied by other tests?

My first test

``` C++
void no_false_positive_gh_104241() {
  std::mutex m;
  m.lock();
  // If inheritance not handled properly, this unlock might not match the lock
  // above because technically they act on different memory regions:
  // __mutex_base and mutex.
  m.unlock();
  sleep(10); // no-warning
}
```

Was derived from your example, so I guess it is implied, but I added your 
example as is with 0d95583 to make it extra clear.

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

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

Thanks, I'm lovin it!

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/106240

>From 0c86e46516466f9513652a04ba87aa2a018ff6b8 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 27 Aug 2024 17:52:25 +0200
Subject: [PATCH 1/7] [analyzer] Fix false positive for mutexes inheriting
 mutex_base

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This possibly fixes #104241

CPP-5541
---
 .../Checkers/BlockInCriticalSectionChecker.cpp |  6 --
 .../Analysis/block-in-critical-section-inheritance.cpp | 10 ++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..52ff639c6b8022 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -245,8 +245,10 @@ static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+if (const MemRegion *Reg = Descr.getRegion(Call, IsLock))
+  return Reg->getBaseRegion();
+return nullptr;
   },
   Descriptor);
 }
diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index db20df8c60a5c9..c60ba2632cee25 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -29,3 +29,13 @@ void gh_99628() {
   // expected-note@-2 {{Call to blocking function 'sleep' inside of critical 
section}}
   m.unlock();
 }
+
+void no_false_positive_gh_104241() {
+  std::mutex m;
+  m.lock();
+  // If inheritance not handled properly, this unlock might not match the lock
+  // above because technically they act on different memory regions:
+  // __mutex_base and mutex.
+  m.unlock();
+  sleep(10); // no-warning
+}

>From 013a6d138b38c51c64860a99b95591491f86c223 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:27:50 +0200
Subject: [PATCH 2/7] Record a false negative associated with the new mutex
 canonicalization

---
 .../block-in-critical-section-inheritance.cpp  | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index c60ba2632cee25..5f6fa565f42fb9 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -39,3 +39,17 @@ void no_false_positive_gh_104241() {
   m.unlock();
   sleep(10); // no-warning
 }
+
+struct TwoMutexes {
+  std::mutex m1;
+  std::mutex m2;
+};
+
+void two_mutexes_false_negative(TwoMutexes &tm) {
+  tm.m1.lock();
+  tm.m2.unlock();
+  // Critical section is associated with tm now so tm.m1 and tm.m2 are
+  // undistinguishiable
+  sleep(10); // False-negative
+  tm.m1.unlock();
+}

>From 744272e0f1ccd5217c0d456a7c499a9bcae84679 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:33:02 +0200
Subject: [PATCH 3/7] Fix false negative for field regions

---
 .../Checkers/BlockInCriticalSectionChecker.cpp   | 9 -
 .../Analysis/block-in-critical-section-inheritance.cpp   | 9 +
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 52ff639c6b8022..fd8700902c1835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -241,13 +241,20 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
+  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
   [&Call, IsLock]

[clang] [Clang][Interp] Implement constexpr vector unary operators +, -, ~, ! (PR #105996)

2024-08-28 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr commented:

Are these the only unary operators supported on vectors or are more to come? 
Since all (except for `+`, which doesn't do anything) cases call 
`prepareResult()` and `createTemp()` unconditionally, it would probably be 
cleaner to reject the unhandled cases via `emitInvalid` first, then do the 
`prepareResult()` + `createTemp()`(which don't even need to be lambdas 
anymore), then handle the actual operation.

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


[clang] [Clang][Interp] Implement constexpr vector unary operators +, -, ~, ! (PR #105996)

2024-08-28 Thread Timm Baeder via cfe-commits

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


[clang] [Clang][Interp] Implement constexpr vector unary operators +, -, ~, ! (PR #105996)

2024-08-28 Thread Timm Baeder via cfe-commits


@@ -5312,6 +5314,120 @@ bool Compiler::VisitComplexUnaryOperator(const 
UnaryOperator *E) {
   return true;
 }
 
+template 
+bool Compiler::VisitVectorUnaryOperator(const UnaryOperator *E) {
+  const Expr *SubExpr = E->getSubExpr();
+  assert(SubExpr->getType()->isVectorType());
+
+  if (DiscardResult)
+return this->discard(SubExpr);
+
+  auto prepareResult = [=]() -> bool {
+if (!Initializing) {
+  std::optional LocalIndex = allocateLocal(SubExpr);
+  if (!LocalIndex)
+return false;
+  return this->emitGetPtrLocal(*LocalIndex, E);
+}
+return true;
+  };
+
+  // The offset of the temporary, if we created one.
+  unsigned SubExprOffset = ~0u;
+  auto createTemp = [=, &SubExprOffset]() -> bool {
+SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
+if (!this->visit(SubExpr))
+  return false;
+return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
+  };
+
+  const auto *VecTy = SubExpr->getType()->getAs();
+  PrimType ElemT = classifyVectorElementType(SubExpr->getType());
+  auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
+if (!this->emitGetLocal(PT_Ptr, Offset, E))
+  return false;
+return this->emitArrayElemPop(ElemT, Index, E);
+  };
+
+  switch (E->getOpcode()) {
+  case UO_Plus: // +x
+return this->delegate(SubExpr);
+  case UO_Minus:
+if (!prepareResult())
+  return false;
+if (!createTemp())
+  return false;
+for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
+  if (!getElem(SubExprOffset, I))
+return false;
+  if (!this->emitNeg(ElemT, E))
+return false;
+  if (!this->emitInitElem(ElemT, I, E))
+return false;
+}
+break;
+  case UO_LNot: { // !x
+if (!prepareResult())
+  return false;
+if (!createTemp())
+  return false;
+
+// In C++, the logic operators !, &&, || are available for vectors. !v is
+// equivalent to v == 0.
+//
+// The result of the comparison is a vector of the same width and number of
+// elements as the comparison operands with a signed integral element type.
+//
+// https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
+QualType SignedVecTy = E->getType();
+PrimType SignedElemT =
+classifyPrim(SignedVecTy->getAs()->getElementType());
+for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
+  if (!getElem(SubExprOffset, I))
+return false;
+  // operator ! on vectors returns -1 for 'truth', so negate it.
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;
+  if (!this->emitInv(E))
+return false;
+  if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
+return false;
+  if (!this->emitNeg(ElemT, E))
+return false;
+  if (ElemT != SignedElemT &&

tbaederr wrote:

The name `SignedElemT` doesn't make much sense anymore, it's more like the 
"result type".

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


[clang] [Clang][Interp] Implement constexpr vector unary operators +, -, ~, ! (PR #105996)

2024-08-28 Thread Timm Baeder via cfe-commits


@@ -5312,6 +5314,120 @@ bool Compiler::VisitComplexUnaryOperator(const 
UnaryOperator *E) {
   return true;
 }
 
+template 
+bool Compiler::VisitVectorUnaryOperator(const UnaryOperator *E) {
+  const Expr *SubExpr = E->getSubExpr();
+  assert(SubExpr->getType()->isVectorType());
+
+  if (DiscardResult)
+return this->discard(SubExpr);
+
+  auto prepareResult = [=]() -> bool {
+if (!Initializing) {
+  std::optional LocalIndex = allocateLocal(SubExpr);
+  if (!LocalIndex)
+return false;
+  return this->emitGetPtrLocal(*LocalIndex, E);
+}
+return true;
+  };
+
+  // The offset of the temporary, if we created one.
+  unsigned SubExprOffset = ~0u;
+  auto createTemp = [=, &SubExprOffset]() -> bool {
+SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
+if (!this->visit(SubExpr))
+  return false;
+return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
+  };
+
+  const auto *VecTy = SubExpr->getType()->getAs();
+  PrimType ElemT = classifyVectorElementType(SubExpr->getType());
+  auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
+if (!this->emitGetLocal(PT_Ptr, Offset, E))
+  return false;
+return this->emitArrayElemPop(ElemT, Index, E);
+  };
+
+  switch (E->getOpcode()) {
+  case UO_Plus: // +x
+return this->delegate(SubExpr);
+  case UO_Minus:
+if (!prepareResult())
+  return false;
+if (!createTemp())
+  return false;
+for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
+  if (!getElem(SubExprOffset, I))
+return false;
+  if (!this->emitNeg(ElemT, E))
+return false;
+  if (!this->emitInitElem(ElemT, I, E))
+return false;
+}
+break;
+  case UO_LNot: { // !x
+if (!prepareResult())
+  return false;
+if (!createTemp())
+  return false;
+
+// In C++, the logic operators !, &&, || are available for vectors. !v is
+// equivalent to v == 0.
+//
+// The result of the comparison is a vector of the same width and number of
+// elements as the comparison operands with a signed integral element type.
+//
+// https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
+QualType SignedVecTy = E->getType();
+PrimType SignedElemT =
+classifyPrim(SignedVecTy->getAs()->getElementType());
+for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
+  if (!getElem(SubExprOffset, I))
+return false;
+  // operator ! on vectors returns -1 for 'truth', so negate it.
+  if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
+return false;

tbaederr wrote:

I think this can just be a `emitCast(ElemT, PT_Bool, E)`

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/106240

>From 0c86e46516466f9513652a04ba87aa2a018ff6b8 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 27 Aug 2024 17:52:25 +0200
Subject: [PATCH 1/8] [analyzer] Fix false positive for mutexes inheriting
 mutex_base

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This possibly fixes #104241

CPP-5541
---
 .../Checkers/BlockInCriticalSectionChecker.cpp |  6 --
 .../Analysis/block-in-critical-section-inheritance.cpp | 10 ++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..52ff639c6b8022 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -245,8 +245,10 @@ static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+if (const MemRegion *Reg = Descr.getRegion(Call, IsLock))
+  return Reg->getBaseRegion();
+return nullptr;
   },
   Descriptor);
 }
diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index db20df8c60a5c9..c60ba2632cee25 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -29,3 +29,13 @@ void gh_99628() {
   // expected-note@-2 {{Call to blocking function 'sleep' inside of critical 
section}}
   m.unlock();
 }
+
+void no_false_positive_gh_104241() {
+  std::mutex m;
+  m.lock();
+  // If inheritance not handled properly, this unlock might not match the lock
+  // above because technically they act on different memory regions:
+  // __mutex_base and mutex.
+  m.unlock();
+  sleep(10); // no-warning
+}

>From 013a6d138b38c51c64860a99b95591491f86c223 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:27:50 +0200
Subject: [PATCH 2/8] Record a false negative associated with the new mutex
 canonicalization

---
 .../block-in-critical-section-inheritance.cpp  | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index c60ba2632cee25..5f6fa565f42fb9 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -39,3 +39,17 @@ void no_false_positive_gh_104241() {
   m.unlock();
   sleep(10); // no-warning
 }
+
+struct TwoMutexes {
+  std::mutex m1;
+  std::mutex m2;
+};
+
+void two_mutexes_false_negative(TwoMutexes &tm) {
+  tm.m1.lock();
+  tm.m2.unlock();
+  // Critical section is associated with tm now so tm.m1 and tm.m2 are
+  // undistinguishiable
+  sleep(10); // False-negative
+  tm.m1.unlock();
+}

>From 744272e0f1ccd5217c0d456a7c499a9bcae84679 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:33:02 +0200
Subject: [PATCH 3/8] Fix false negative for field regions

---
 .../Checkers/BlockInCriticalSectionChecker.cpp   | 9 -
 .../Analysis/block-in-critical-section-inheritance.cpp   | 9 +
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 52ff639c6b8022..fd8700902c1835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -241,13 +241,20 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
+  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
   [&Call, IsLock]

[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

necto wrote:

@steakhal I added a fix for multiple-inheritance fn, please take another look

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/106240

>From 0c86e46516466f9513652a04ba87aa2a018ff6b8 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 27 Aug 2024 17:52:25 +0200
Subject: [PATCH 1/9] [analyzer] Fix false positive for mutexes inheriting
 mutex_base

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This possibly fixes #104241

CPP-5541
---
 .../Checkers/BlockInCriticalSectionChecker.cpp |  6 --
 .../Analysis/block-in-critical-section-inheritance.cpp | 10 ++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..52ff639c6b8022 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -245,8 +245,10 @@ static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+if (const MemRegion *Reg = Descr.getRegion(Call, IsLock))
+  return Reg->getBaseRegion();
+return nullptr;
   },
   Descriptor);
 }
diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index db20df8c60a5c9..c60ba2632cee25 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -29,3 +29,13 @@ void gh_99628() {
   // expected-note@-2 {{Call to blocking function 'sleep' inside of critical 
section}}
   m.unlock();
 }
+
+void no_false_positive_gh_104241() {
+  std::mutex m;
+  m.lock();
+  // If inheritance not handled properly, this unlock might not match the lock
+  // above because technically they act on different memory regions:
+  // __mutex_base and mutex.
+  m.unlock();
+  sleep(10); // no-warning
+}

>From 013a6d138b38c51c64860a99b95591491f86c223 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:27:50 +0200
Subject: [PATCH 2/9] Record a false negative associated with the new mutex
 canonicalization

---
 .../block-in-critical-section-inheritance.cpp  | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index c60ba2632cee25..5f6fa565f42fb9 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -39,3 +39,17 @@ void no_false_positive_gh_104241() {
   m.unlock();
   sleep(10); // no-warning
 }
+
+struct TwoMutexes {
+  std::mutex m1;
+  std::mutex m2;
+};
+
+void two_mutexes_false_negative(TwoMutexes &tm) {
+  tm.m1.lock();
+  tm.m2.unlock();
+  // Critical section is associated with tm now so tm.m1 and tm.m2 are
+  // undistinguishiable
+  sleep(10); // False-negative
+  tm.m1.unlock();
+}

>From 744272e0f1ccd5217c0d456a7c499a9bcae84679 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:33:02 +0200
Subject: [PATCH 3/9] Fix false negative for field regions

---
 .../Checkers/BlockInCriticalSectionChecker.cpp   | 9 -
 .../Analysis/block-in-critical-section-inheritance.cpp   | 9 +
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 52ff639c6b8022..fd8700902c1835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -241,13 +241,20 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
+  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
   [&Call, IsLock]

[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

This patch breaks:
https://lab.llvm.org/buildbot/#/builders/25/builds/1952
https://lab.llvm.org/buildbot/#/builders/52/builds/1775

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


[clang] Revert "[clang] Add nuw attribute to GEPs" (PR #106343)

2024-08-28 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-powerpc

@llvm/pr-subscribers-clang

Author: Vitaly Buka (vitalybuka)


Changes

Reverts llvm/llvm-project#105496

This patch breaks:
https://lab.llvm.org/buildbot/#/builders/25/builds/1952
https://lab.llvm.org/buildbot/#/builders/52/builds/1775

Somehow output is different with sanitizers.
Maybe non-determinism in the code?

---

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


91 Files Affected:

- (modified) clang/lib/CodeGen/CGBuilder.h (+2-4) 
- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+3-14) 
- (modified) clang/test/CodeGen/2005-01-02-ConstantInits.c (+2-2) 
- (modified) clang/test/CodeGen/PowerPC/ppc-emmintrin.c (+6-6) 
- (modified) clang/test/CodeGen/PowerPC/ppc-xmmintrin.c (+8-8) 
- (modified) clang/test/CodeGen/attr-counted-by.c (+8-8) 
- (modified) 
clang/test/CodeGen/catch-nullptr-and-nonzero-offset-when-nullptr-is-defined.c 
(+1-1) 
- (modified) clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c (+32-32) 
- (modified) clang/test/CodeGen/catch-pointer-overflow-volatile.c (+1-1) 
- (modified) clang/test/CodeGen/catch-pointer-overflow.c (+3-3) 
- (modified) clang/test/CodeGen/ext-int.c (+1-1) 
- (modified) clang/test/CodeGen/hexagon-brev-ld-ptr-incdec.c (+3-3) 
- (modified) clang/test/CodeGen/integer-overflow.c (+3-3) 
- (modified) clang/test/CodeGen/ms-intrinsics.c (+6-6) 
- (modified) clang/test/CodeGen/ubsan-pointer-overflow.m (+1-1) 
- (modified) clang/test/CodeGen/vla.c (+1-1) 
- (modified) clang/test/CodeGenCXX/attr-likelihood-iteration-stmt.cpp (+18-18) 
- (modified) clang/test/CodeGenCXX/for-range.cpp (+6-6) 
- (modified) clang/test/CodeGenCXX/pr45964-decomp-transform.cpp (+1-1) 
- (modified) clang/test/CodeGenCXX/vla.cpp (+2-2) 
- (modified) clang/test/CodeGenHLSL/buffer-array-operator.hlsl (+2-2) 
- (modified) clang/test/CodeGenSYCL/address-space-deduction.cpp (+24-24) 
- (modified) clang/test/Headers/__clang_hip_math.hip (+27-27) 
- (modified) clang/test/OpenMP/bug60602.cpp (+4-4) 
- (modified) clang/test/OpenMP/declare_mapper_codegen.cpp (+2-2) 
- (modified) clang/test/OpenMP/distribute_codegen.cpp (+16-16) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_reduction_task_codegen.cpp (+12-12) 
- (modified) clang/test/OpenMP/distribute_simd_codegen.cpp (+48-48) 
- (modified) clang/test/OpenMP/for_linear_codegen.cpp (+1-1) 
- (modified) clang/test/OpenMP/for_reduction_codegen.cpp (+32-32) 
- (modified) clang/test/OpenMP/for_reduction_codegen_UDR.cpp (+16-16) 
- (modified) clang/test/OpenMP/for_reduction_task_codegen.cpp (+12-12) 
- (modified) clang/test/OpenMP/for_scan_codegen.cpp (+20-20) 
- (modified) clang/test/OpenMP/for_simd_scan_codegen.cpp (+20-20) 
- (modified) clang/test/OpenMP/irbuilder_for_iterator.cpp (+3-3) 
- (modified) clang/test/OpenMP/irbuilder_for_rangefor.cpp (+3-3) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned.c (+4-4) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_auto.c (+4-4) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_down.c (+1-1) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_dynamic.c (+4-4) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_dynamic_chunked.c (+4-4) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_runtime.c (+4-4) 
- (modified) clang/test/OpenMP/irbuilder_for_unsigned_static_chunked.c (+4-4) 
- (modified) clang/test/OpenMP/map_struct_ordering.cpp (+1-1) 
- (modified) clang/test/OpenMP/master_taskloop_in_reduction_codegen.cpp (+5-5) 
- (modified) clang/test/OpenMP/master_taskloop_reduction_codegen.cpp (+6-6) 
- (modified) clang/test/OpenMP/master_taskloop_simd_in_reduction_codegen.cpp 
(+5-5) 
- (modified) clang/test/OpenMP/master_taskloop_simd_reduction_codegen.cpp 
(+6-6) 
- (modified) clang/test/OpenMP/ordered_codegen.cpp (+40-40) 
- (modified) clang/test/OpenMP/parallel_for_codegen.cpp (+72-72) 
- (modified) clang/test/OpenMP/parallel_for_linear_codegen.cpp (+1-1) 
- (modified) clang/test/OpenMP/parallel_for_reduction_task_codegen.cpp (+12-12) 
- (modified) clang/test/OpenMP/parallel_for_scan_codegen.cpp (+22-22) 
- (modified) clang/test/OpenMP/parallel_for_simd_scan_codegen.cpp (+20-20) 
- (modified) clang/test/OpenMP/parallel_master_reduction_task_codegen.cpp 
(+12-12) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_reduction_codegen.cpp 
(+6-6) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_simd_reduction_codegen.cpp (+6-6) 
- (modified) clang/test/OpenMP/parallel_reduction_codegen.cpp (+6-6) 
- (modified) clang/test/OpenMP/parallel_reduction_task_codegen.cpp (+12-12) 
- (modified) clang/test/OpenMP/parallel_sections_reduction_task_codegen.cpp 
(+12-12) 
- (modified) clang/test/OpenMP/reduction_implicit_map.cpp (+25-25) 
- (modified) clang/test/OpenMP/sections_reduction_task_codegen.cpp (+12-12) 
- (modified) clang/test/OpenMP/target_data_use_device_addr_codegen.cpp (+5-5) 
- (modified) clang/test/OpenMP/target_data_use_device_ptr_codegen.

[clang] Revert "[clang] Add nuw attribute to GEPs" (PR #106343)

2024-08-28 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Please let me know if you have a fix for that.
I'll land revert in the morning by PDT.

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

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

Still looks good.

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits


@@ -241,10 +241,14 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
-static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
-  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+static const MemRegion *skipStdBaseClassRegion(const MemRegion *Reg) {
+  do {
+assert(Reg);
+const auto *BaseClassRegion = dyn_cast(Reg);
+if (!BaseClassRegion || !BaseClassRegion->getDecl()->isInStdNamespace())

steakhal wrote:

FYI `isInStdNamespace` only works if the decl is exactly within std. Any nested 
namespaces beyond std, or class scopes are rejected even if their parents 
reside within std.
Have a look at `CallEvent.cpp:isWithinStdNamespace()`. If you think it's what 
we should use here, we could hoist that function into some utility header and 
use it.

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


[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread David Sherwood via cfe-commits

david-arm wrote:

> This patch breaks: https://lab.llvm.org/buildbot/#/builders/25/builds/1952 
> https://lab.llvm.org/buildbot/#/builders/52/builds/1775

>From the buildbot run I can see 12 or 13 changes in the build that failed. 
>Just out of curiosity how did you find out it was this patch that caused it?

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


[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> > This patch breaks: https://lab.llvm.org/buildbot/#/builders/25/builds/1952 
> > https://lab.llvm.org/buildbot/#/builders/52/builds/1775
> 
> From the buildbot run I can see 12 or 13 changes in the build that failed. 
> Just out of curiosity how did you find out it was this patch that caused it?

Bisected and reverted locally.

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


[clang] [clang] mangle placeholder for deduced type as a template-prefix (PR #106335)

2024-08-28 Thread via cfe-commits


@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++20 %s -triple %itanium_abi_triple -emit-llvm -o - | 
FileCheck %s
+
+template  class S>
+void create_unique()
+  requires (S{0}, true) {}
+
+template  struct A {
+  constexpr A(Fn) {};
+};
+
+template void create_unique();
+// CHECK: @_Z13create_uniqueI1AEvvQcmtlT_Li0EELb1E(

cor3ntin wrote:

There is a difference compared to GCC
https://compiler-explorer.com/z/1EvTrecvh

```
_Z13create_uniqueI1AEvvQcmtl1SLi0EELb1E
 => void create_unique() requires T{0}, true

_Z13create_uniqueI1AEvvQcmtlT_Li0EELb1E
 => void create_unique() requires S{0}, true
```
Which i guess is because of the improper canonicalisation

Given that this changes looks correct we should land it, and because main is 
crashing, we should backport it.
So, we should remove the changelog entry and instead add a changelog entry to 
19x explaining the breaking mangling change.

We probably want to make sure this is on GCC's radar.
How hard would it be to get back the older behavior? If at all possible we 
might want to consider putting the new mangling under an ABI flag.

@AaronBallman @zygoloid @rjmccall 


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


[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg updated 
https://github.com/llvm/llvm-project/pull/106242

>From 32e94bde5a8ed401a9fb1255d8394c552da82dd7 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Tue, 27 Aug 2024 16:08:07 +
Subject: [PATCH 1/3] [clang-format] js handle anonymous classes

Addresses a regression in JavaScript when formatting anonymous classes.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 6 +-
 clang/unittests/Format/FormatTestJS.cpp  | 9 +
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5f1a88d4bcd729..7591eaeae461a7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3992,6 +3992,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   auto IsNonMacroIdentifier = [](const FormatToken *Tok) {
 return Tok->is(tok::identifier) && Tok->TokenText != 
Tok->TokenText.upper();
   };
+  // JavaScript/TypeScript supports anonymous classes like:
+  // a = class extends foo { }
+  bool JSPastExtendsOrImplements = false;
   // The actual identifier can be a nested name specifier, and in macros
   // it is often token-pasted.
   // An [[attribute]] can be before the identifier.
@@ -4002,6 +4005,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   FormatTok->isOneOf(tok::period, tok::comma))) {
 if (Style.isJavaScript() &&
 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
+  JSPastExtendsOrImplements = true;
   // JavaScript/TypeScript supports inline object types in
   // extends/implements positions:
   // class Foo implements {bar: number} { }
@@ -4027,7 +4031,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 case tok::coloncolon:
   break;
 default:
-  if (!ClassName && Previous->is(tok::identifier) &&
+  if (!JSPastExtendsOrImplements && !ClassName && 
Previous->is(tok::identifier) &&
   Previous->isNot(TT_AttributeMacro)) {
 ClassName = Previous;
   }
diff --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index b910ce620de7a9..734c1590c41ddb 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -579,6 +579,15 @@ TEST_F(FormatTestJS, GoogScopes) {
"});");
 }
 
+TEST_F(FormatTestJS, GoogAnonymousClass) {
+  verifyFormat("a = class extends goog.structs.a {\n"
+   "  a() {\n"
+   "return 0;\n"
+   "  }\n"
+   "};");
+}
+
+
 TEST_F(FormatTestJS, IIFEs) {
   // Internal calling parens; no semi.
   verifyFormat("(function() {\n"

>From f42f5d46ba41dc679e42fc50850aa8a6b46c9459 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Tue, 27 Aug 2024 16:58:48 +
Subject: [PATCH 2/3] fix formatting

---
 clang/lib/Format/UnwrappedLineParser.cpp | 4 ++--
 clang/unittests/Format/FormatTestJS.cpp  | 1 -
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7591eaeae461a7..506386526bd15f 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -4031,8 +4031,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 case tok::coloncolon:
   break;
 default:
-  if (!JSPastExtendsOrImplements && !ClassName && 
Previous->is(tok::identifier) &&
-  Previous->isNot(TT_AttributeMacro)) {
+  if (!JSPastExtendsOrImplements && !ClassName &&
+  Previous->is(tok::identifier) && Previous->isNot(TT_AttributeMacro)) 
{
 ClassName = Previous;
   }
 }
diff --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 734c1590c41ddb..4b29ba720f6823 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -587,7 +587,6 @@ TEST_F(FormatTestJS, GoogAnonymousClass) {
"};");
 }
 
-
 TEST_F(FormatTestJS, IIFEs) {
   // Internal calling parens; no semi.
   verifyFormat("(function() {\n"

>From 8283b7f9bb422c9692ffa83c034dcab8aee41a9a Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Wed, 28 Aug 2024 08:04:46 +
Subject: [PATCH 3/3] add a token annotator test

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index db44d418a84484..04a9fa760ce878 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3238,6 +3238,12 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[8], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[11], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[13], BK_Block);
+
+  Tokens = annotate("a = class extends goog.a {}",
+

[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Krasimir Georgiev via cfe-commits


@@ -579,6 +579,14 @@ TEST_F(FormatTestJS, GoogScopes) {
"});");
 }
 
+TEST_F(FormatTestJS, GoogAnonymousClass) {

krasimirgg wrote:

Thanks! Added one.

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


[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread David Sherwood via cfe-commits

david-arm wrote:

> > > This patch breaks: 
> > > https://lab.llvm.org/buildbot/#/builders/25/builds/1952 
> > > https://lab.llvm.org/buildbot/#/builders/52/builds/1775
> > 
> > 
> > From the buildbot run I can see 12 or 13 changes in the build that failed. 
> > Just out of curiosity how did you find out it was this patch that caused it?
> 
> Bisected and reverted locally.

Thanks! I was just wondering if it was something obvious from the patch or 
whether there was a bisecting tool to use in github. But bisecting and 
reverting locally is the same thing I'd do.

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


[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Maybe the patch introduced some miscompile?
The patch affects only clang, but failing tests are LLVM, but tools compiled 
with patched clang with UBSAN enabled.

Also there are branches checking sanitizers.

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


[clang] Revert "[clang] Add nuw attribute to GEPs" (PR #106343)

2024-08-28 Thread Hari Limaye via cfe-commits

hazzlim wrote:

> Please let me know if you have a fix for that. I'll land revert in the 
> morning by PDT.

Thank you for flagging this up and opening this @vitalybuka - I'm taking a look 
now to see if there's an easy enough fix to save reverting.

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


[clang] [clang] Add lifetimebound attr to std::span/std::string_view constructor (PR #103716)

2024-08-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/103716

>From 24a84b35dba03ca80027efcc87b4628c378991ff Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 14 Aug 2024 10:18:09 +0200
Subject: [PATCH] [clang] Add lifetimebound attr to std::span/std::string_view
 constructor

With this patch, clang now automatically adds ``[[clang::lifetimebound]]``
to the parameters of ``std::span, std::string_view`` constructors, this
enables Clang to capture more cases where the returned reference outlives the 
object.
---
 clang/docs/ReleaseNotes.rst   |  5 +++
 clang/include/clang/Sema/Sema.h   |  3 ++
 clang/lib/Sema/SemaAttr.cpp   | 53 +++
 clang/lib/Sema/SemaDecl.cpp   | 20 +
 clang/test/SemaCXX/attr-lifetimebound.cpp | 21 +
 5 files changed, 83 insertions(+), 19 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9fa068c2910f4..4289b3374a810b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -220,6 +220,11 @@ Attribute Changes in Clang
 - ``[[clang::lifetimebound]]`` is now explicitly disallowed on explicit object 
member functions
   where they were previously silently ignored.
 
+- Clang now automatically adds ``[[clang::lifetimebound]]`` to the parameters 
of
+  ``std::span, std::string_view`` constructors, this enables Clang to capture
+  more cases where the returned reference outlives the object.
+  (#GH100567)
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..ed1c279fefe29c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1806,6 +1806,9 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
 
+  /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
+  void inferLifetimeBoundAttribute(FunctionDecl *FD);
+
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index a1724820472b59..fb594e6f13c0b3 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -216,6 +216,59 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
   inferGslPointerAttribute(Record, Record);
 }
 
+void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
+  if (FD->getNumParams() == 0)
+return;
+
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:
+case Builtin::BIforward:
+case Builtin::BIforward_like:
+case Builtin::BImove:
+case Builtin::BImove_if_noexcept:
+  if (ParmVarDecl *P = FD->getParamDecl(0u);
+  !P->hasAttr())
+P->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  break;
+default:
+  break;
+}
+return;
+  }
+  if (auto *CMD = dyn_cast(FD)) {
+const auto *CRD = CMD->getParent();
+if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
+  return;
+
+if (isa(CMD)) {
+  auto *Param = CMD->getParamDecl(0);
+  if (Param->hasAttr())
+return;
+  if (CRD->getName() == "basic_string_view" &&
+  Param->getType()->isPointerType()) {
+// construct from a char array pointed by a pointer.
+//   basic_string_view(const CharT* s);
+//   basic_string_view(const CharT* s, size_type count);
+Param->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  } else if (CRD->getName() == "span") {
+// construct from a reference of array.
+//   span(std::type_identity_t (&arr)[N]);
+const auto *LRT = Param->getType()->getAs();
+if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
+  Param->addAttr(
+  LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  }
+}
+  }
+}
+
 void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
   static const llvm::StringSet<> Nullable{
   "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b0ccbbe34b70c3..4efa80778e71b9 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16608,27 +16608,9 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 default:
   break;
 }
-
-// Add lifetime attribute to std::move, std::fowrard et al.
-switch (BuiltinID) {
-case Builtin::BIaddressof:
-case Builtin::BI__address

[clang] [clang] Add lifetimebound attr to std::span/std::string_view constructor (PR #103716)

2024-08-28 Thread Haojian Wu via cfe-commits


@@ -216,6 +216,59 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
   inferGslPointerAttribute(Record, Record);
 }
 
+void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
+  if (FD->getNumParams() == 0)
+return;
+
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:

hokein wrote:

(The latter two cases are identical, we could potentially abstract a common 
function.)

I think this should be handled on a case-by-case basis, depending on the 
specific logic involved.  It seems fine to me have this small amount of 
duplication.

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


[clang] Revert "[clang] Add nuw attribute to GEPs" (PR #106343)

2024-08-28 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> > Please let me know if you have a fix for that. I'll land revert in the 
> > morning by PDT.
> 
> Thank you for flagging this up and opening this @vitalybuka - I'm taking a 
> look now to see if there's an easy enough fix to save reverting.

Thanks. Please merge the revert if you give up on the easy fix.

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


[clang] [clang] Cleanup IncludeLocMap (PR #106241)

2024-08-28 Thread Ilya Biryukov via cfe-commits

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


[clang] [clang] Cleanup IncludeLocMap (PR #106241)

2024-08-28 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov requested changes to this pull request.

This looks good, but I wanted to explore if we could write a unit test for 
this...

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


[clang] [clang] Cleanup IncludeLocMap (PR #106241)

2024-08-28 Thread Ilya Biryukov via cfe-commits


@@ -350,6 +350,7 @@ void SourceManager::clearIDTables() {
   LastLineNoContentCache = nullptr;
   LastFileIDLookup = FileID();
 
+  IncludedLocMap.clear();

ilya-biryukov wrote:

Is there a way to write a unit test checking this behavior?

SourceManager should be relatively easy to mock, I think it'd be useful to 
write one.

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


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

2024-08-28 Thread Dan Liew via cfe-commits


@@ -2099,6 +2099,70 @@ class Sema final : public SemaBase {
   bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
  bool OrNull);
 
+  // AssignmentAction - This is used by all the assignment diagnostic functions
+  // to represent what is actually causing the operation
+  enum AssignmentAction {

delcypher wrote:

@Endilll Any opinions on where `AssignmentAction` should go? Unfortunately I 
had to move it because the enum needs to be defined before I can use it as a 
parameter type.

This wasn't a problem in the original version of my patch but when I rebased on 
latest `next` it appears a recent refactor 
(9f1dc01e0ab4f91c4052a712ce590d2e86b81dc3) moved where the `BoundsSafety*` 
methods are declared so that they are now **before** where `AssignmentAction`'s 
declaration. Previously the methods were declared after `AssignmentActions`'s 
declaration.

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


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

2024-08-28 Thread Dan Liew via cfe-commits

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


[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits


@@ -67,19 +67,6 @@ void testGlobalNoThrowPlacementExprNewBeforeOverload() {
   int *p = new(std::nothrow) int;
 } // leak-warning{{Potential leak of memory pointed to by 'p'}}
 
-//- Standard pointer placement operators
-void testGlobalPointerPlacementNew() {

pskrgag wrote:

Sure! This tests checks that CSA looks into `new` implementation and sees that 
it just returns some constant pointer. Since PR changes this behavior, test no 
longer works and CSA reports memory leaks

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


[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits


@@ -1736,6 +1816,25 @@ MallocChecker::MallocMemReturnsAttr(CheckerContext &C, 
const CallEvent &Call,
   return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, Family);
 }
 
+ProgramStateRef MallocChecker::MallocBindRetval(CheckerContext &C,
+const CallEvent &Call,
+ProgramStateRef State,
+bool isAlloca) const {
+  const Expr *CE = Call.getOriginExpr();
+
+  // We expect the allocation functions to return a pointer.
+  if (!Loc::isLocType(CE->getType()))
+return nullptr;
+
+  unsigned Count = C.blockCount();
+  SValBuilder &SVB = C.getSValBuilder();
+  const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
+  DefinedSVal RetVal = (isAlloca ? SVB.getAllocaRegionVal(CE, LCtx, Count)
+ : SVB.getConjuredHeapSymbolVal(CE, LCtx, 
Count)
+   .castAs());

pskrgag wrote:

`getConjuredHeapSymbolVal` always returns `DefinedSVal` as far as I can see, 
but there is a problem with `SValBuilder::makeZeroVal` which may return 
`UnknownVal` in case of fp numbers.

So, I guess, it could be fixed on type level if we add API like 
`makeZeroValNoFP`

https://github.com/llvm/llvm-project/pull/106081
___
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 user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits

https://github.com/Discookie created 
https://github.com/llvm/llvm-project/pull/106350

Adds the check options `bugprone-unsafe-functions.CustomNormalFunctions` and 
`CustomAnnexKFunctions` to be able to match user-defined functions as part of 
the checker.
Adds the option `bugprone-unsafe-functions.ReportDefaultFunctions` to disable 
reporting the default set of functions as well.

The functions names are matched using the same mechanism as the 
`matchesAnyListedName` tidy matcher, documented in the [check 
docs](https://github.com/Discookie/llvm-project/blob/unsafe-expand/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst).

>From 4cdba3f6c77aa9af5f9e248c6ad8aa2de89eac0e Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Thu, 15 Aug 2024 08:41:00 +
Subject: [PATCH 1/3] [clang-tidy] Add user-defined functions to
 bugprone-unsafe-functions check

---
 .../bugprone/UnsafeFunctionsCheck.cpp | 215 +++---
 .../bugprone/UnsafeFunctionsCheck.h   |  12 +
 .../checks/bugprone/unsafe-functions.rst  |  49 
 .../bugprone/unsafe-functions-custom.c|  38 
 .../checkers/bugprone/unsafe-functions.c  |   6 +
 5 files changed, 288 insertions(+), 32 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index ea7eaa0b0ff811..ac98ebaebed83b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/PPCallbacks.h"
@@ -18,6 +20,12 @@ using namespace llvm;
 
 namespace clang::tidy::bugprone {
 
+static constexpr llvm::StringLiteral OptionNameCustomNormalFunctions =
+"CustomNormalFunctions";
+static constexpr llvm::StringLiteral OptionNameCustomAnnexKFunctions =
+"CustomAnnexKFunctions";
+static constexpr llvm::StringLiteral OptionNameReportDefaultFunctions =
+"ReportDefaultFunctions";
 static constexpr llvm::StringLiteral OptionNameReportMoreUnsafeFunctions =
 "ReportMoreUnsafeFunctions";
 
@@ -26,6 +34,8 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId = 
"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId = 
"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -127,55 +137,151 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
   return CacheVar.value();
 }
 
+static std::vector
+ParseCheckedFunctions(StringRef Option, StringRef OptionName, 
+  ClangTidyContext *Context) {
+  std::vector Functions = utils::options::parseStringList(Option);
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (StringRef Function : Functions) {
+if (Function.empty()) {
+  continue;
+}
+
+auto [Name, Rest] = Function.split(',');
+auto [Replacement, Reason] = Rest.split(',');
+
+if (Name.trim().empty()) {
+  Context->configurationDiag(
+"invalid configuration value for option '%0'; "
+"expected the name of an unsafe function") << OptionName;
+}
+
+if (Replacement.trim().empty()) {
+  Context->configurationDiag(
+"invalid configuration value '%0' for option '%1'; "
+"expected a replacement function name") << Name.trim() << OptionName;
+}
+
+Result.push_back({ Name.trim().str(), llvm::Regex(Name.trim()),
+   Replacement.trim().str(), Reason.trim().str() });
+  }
+
+  return Result;
+}
+
+static std::string SerializeCheckedFunctions(
+const std::vector &Functions) {
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (const auto &Entry : Functions) {
+if (Entry.Reason.empty())
+  Result.push_back(Entry.Name + "," + Entry.Replacement);
+else
+  Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
+   Entry.Reason);
+  }
+
+  return llvm::join(Result, ";");
+}
+
 UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
+  CustomNormalFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomNormalFunctions, ""),
+  OptionNameCustomNormalFunctions, Context)),
+  CustomAn

[clang-tools-extra] [clang-tidy] Add user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits

llvmbot wrote:




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

Author: Discookie (Discookie)


Changes

Adds the check options `bugprone-unsafe-functions.CustomNormalFunctions` and 
`CustomAnnexKFunctions` to be able to match user-defined functions as part of 
the checker.
Adds the option `bugprone-unsafe-functions.ReportDefaultFunctions` to disable 
reporting the default set of functions as well.

The functions names are matched using the same mechanism as the 
`matchesAnyListedName` tidy matcher, documented in the [check 
docs](https://github.com/Discookie/llvm-project/blob/unsafe-expand/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst).

---

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


7 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
(+184-32) 
- (modified) clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.h (+13) 
- (modified) clang-tools-extra/clang-tidy/utils/Matchers.h (+10-8) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst (+53) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom-regex.cpp
 (+63) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c 
(+35) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions.c (+6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index ea7eaa0b0ff811..8d9ffda04a847a 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/PPCallbacks.h"
@@ -18,6 +20,12 @@ using namespace llvm;
 
 namespace clang::tidy::bugprone {
 
+static constexpr llvm::StringLiteral OptionNameCustomNormalFunctions =
+"CustomNormalFunctions";
+static constexpr llvm::StringLiteral OptionNameCustomAnnexKFunctions =
+"CustomAnnexKFunctions";
+static constexpr llvm::StringLiteral OptionNameReportDefaultFunctions =
+"ReportDefaultFunctions";
 static constexpr llvm::StringLiteral OptionNameReportMoreUnsafeFunctions =
 "ReportMoreUnsafeFunctions";
 
@@ -26,6 +34,8 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId = 
"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId = 
"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -127,55 +137,151 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
   return CacheVar.value();
 }
 
+static std::vector
+ParseCheckedFunctions(StringRef Option, StringRef OptionName, 
+  ClangTidyContext *Context) {
+  std::vector Functions = utils::options::parseStringList(Option);
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (StringRef Function : Functions) {
+if (Function.empty()) {
+  continue;
+}
+
+auto [Name, Rest] = Function.split(',');
+auto [Replacement, Reason] = Rest.split(',');
+
+if (Name.trim().empty()) {
+  Context->configurationDiag(
+"invalid configuration value for option '%0'; "
+"expected the name of an unsafe function") << OptionName;
+}
+
+if (Replacement.trim().empty()) {
+  Context->configurationDiag(
+"invalid configuration value '%0' for option '%1'; "
+"expected a replacement function name") << Name.trim() << OptionName;
+}
+
+Result.push_back({ Name.trim().str(), 
matchers::MatchesAnyListedNameMatcher::NameMatcher(Name.trim()),
+   Replacement.trim().str(), Reason.trim().str() });
+  }
+
+  return Result;
+}
+
+static std::string SerializeCheckedFunctions(
+const std::vector &Functions) {
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (const auto &Entry : Functions) {
+if (Entry.Reason.empty())
+  Result.push_back(Entry.Name + "," + Entry.Replacement);
+else
+  Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
+   Entry.Reason);
+  }
+
+  return llvm::join(Result, ";");
+}
+
 UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
+  CustomNormalFunct

[clang] [clang] Add lifetimebound attr to std::span/std::string_view constructor (PR #103716)

2024-08-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/103716

>From 24a84b35dba03ca80027efcc87b4628c378991ff Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 14 Aug 2024 10:18:09 +0200
Subject: [PATCH 1/2] [clang] Add lifetimebound attr to
 std::span/std::string_view constructor

With this patch, clang now automatically adds ``[[clang::lifetimebound]]``
to the parameters of ``std::span, std::string_view`` constructors, this
enables Clang to capture more cases where the returned reference outlives the 
object.
---
 clang/docs/ReleaseNotes.rst   |  5 +++
 clang/include/clang/Sema/Sema.h   |  3 ++
 clang/lib/Sema/SemaAttr.cpp   | 53 +++
 clang/lib/Sema/SemaDecl.cpp   | 20 +
 clang/test/SemaCXX/attr-lifetimebound.cpp | 21 +
 5 files changed, 83 insertions(+), 19 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9fa068c2910f4..4289b3374a810b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -220,6 +220,11 @@ Attribute Changes in Clang
 - ``[[clang::lifetimebound]]`` is now explicitly disallowed on explicit object 
member functions
   where they were previously silently ignored.
 
+- Clang now automatically adds ``[[clang::lifetimebound]]`` to the parameters 
of
+  ``std::span, std::string_view`` constructors, this enables Clang to capture
+  more cases where the returned reference outlives the object.
+  (#GH100567)
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..ed1c279fefe29c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1806,6 +1806,9 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
 
+  /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
+  void inferLifetimeBoundAttribute(FunctionDecl *FD);
+
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index a1724820472b59..fb594e6f13c0b3 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -216,6 +216,59 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
   inferGslPointerAttribute(Record, Record);
 }
 
+void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
+  if (FD->getNumParams() == 0)
+return;
+
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:
+case Builtin::BIforward:
+case Builtin::BIforward_like:
+case Builtin::BImove:
+case Builtin::BImove_if_noexcept:
+  if (ParmVarDecl *P = FD->getParamDecl(0u);
+  !P->hasAttr())
+P->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  break;
+default:
+  break;
+}
+return;
+  }
+  if (auto *CMD = dyn_cast(FD)) {
+const auto *CRD = CMD->getParent();
+if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
+  return;
+
+if (isa(CMD)) {
+  auto *Param = CMD->getParamDecl(0);
+  if (Param->hasAttr())
+return;
+  if (CRD->getName() == "basic_string_view" &&
+  Param->getType()->isPointerType()) {
+// construct from a char array pointed by a pointer.
+//   basic_string_view(const CharT* s);
+//   basic_string_view(const CharT* s, size_type count);
+Param->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  } else if (CRD->getName() == "span") {
+// construct from a reference of array.
+//   span(std::type_identity_t (&arr)[N]);
+const auto *LRT = Param->getType()->getAs();
+if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
+  Param->addAttr(
+  LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  }
+}
+  }
+}
+
 void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
   static const llvm::StringSet<> Nullable{
   "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b0ccbbe34b70c3..4efa80778e71b9 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16608,27 +16608,9 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 default:
   break;
 }
-
-// Add lifetime attribute to std::move, std::fowrard et al.
-switch (BuiltinID) {
-case Builtin::BIaddressof:
-case Builtin::BI__add

[clang] [llvm] [Clang] C++20 Coroutines: Introduce Frontend Attribute [[clang::coro_await_elidable]] (PR #99282)

2024-08-28 Thread Chuanqi Xu via cfe-commits


@@ -523,6 +523,12 @@ void CodeGenFunction::FinishFunction(SourceLocation 
EndLoc) {
 NormalCleanupDest = Address::invalid();
   }
 
+  if (getLangOpts().Coroutines && isCoroutine()) {
+auto *Record = FnRetTy->getAsCXXRecordDecl();
+if (Record && Record->hasAttr())
+  CurFn->addFnAttr(llvm::Attribute::CoroGenNoallocRamp);
+  }

ChuanqiXu9 wrote:

I don't like this. It will add this attribute to all the coroutines with the 
attribute 
`[[[clang::coro_await_elidable]]](https://github.com/llvm/llvm-project/pull/99282/files#top)`.
 In practice it may always cause the CoroSplit pass to generate additional 
codes.

What I thought is, in CoroSplit pass, we can visit every user of the function, 
and if any user of the function is a call with the elide attribute, we can 
generate .noalloc variant for the current coroutine. 

https://github.com/llvm/llvm-project/pull/99282
___
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 new `bugprone-suspicious-pointer-arithmetics-using-sizeof` (`cert-arr39-c`) check (PR #106061)

2024-08-28 Thread via cfe-commits


@@ -0,0 +1,50 @@
+.. title:: clang-tidy - bugprone-suspicious-pointer-arithmetics-using-sizeof
+
+bugprone-suspicious-pointer-arithmetics-using-sizeof
+
+
+Finds suspicious pointer arithmetic calculations where the pointer is offset by
+an ``alignof()``, ``offsetof()``, or ``sizeof()`` expression.
+
+Pointer arithmetic expressions implicitly scale the offset added to or
+subtracted from the address by the size of the pointee type.
+Using an offset expression that is already scaled by the size of the underlying
+type effectively results in a squared offset, which is likely an invalid
+pointer that points beyond the end of the intended array.
+
+.. code-block:: c
+
+  void printEveryEvenIndexElement(int *Array, size_t N) {
+int *P = Array;
+while (P <= Array + N * sizeof(int)) { // Suspicious pointer arithmetics 
using sizeof()!
+  printf("%d ", *P);
+
+  P += 2 * sizeof(int); // Suspicious pointer arithmetics using sizeof()!
+}
+  }
+
+The above example should be in the following, correct form:
+
+.. code-block:: c
+
+  void printEveryEvenIndexElement(int *Array, size_t N) {
+int *P = Array;
+while (P <= Array + N) {
+  printf("%d ", *P);
+
+  P += 2;
+}
+  }
+
+`cert-arr39-c` redirects here as an alias of this check.
+
+This check corresponds to the CERT C Coding Standard rule
+`ARR39-C. Do not add or subtract a scaled integer to a pointer
+`_.
+
+Limitations
+---
+
+While incorrect from a technically rigorous point of view, the check does not
+warn for pointer arithmetics where the pointee type is ``char``
+(``sizeof(char) == 1``, by definition) on purpose.

whisperity wrote:

When we evaluated the check on OSS projects, it was found to be noisy, yes. 
There were some cases where the ˋPtr + sizeof(*Ptr)ˋ, or ˋPtr + sizeof(T)ˋ 
expanded from a macro.

https://github.com/llvm/llvm-project/pull/106061
___
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 user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 5f15c1776a462940464743dbc9e82c46fe7e14aa 
80694ad203d0d37cd8d186d823bb536c921ae9bf --extensions c,cpp,h -- 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom-regex.cpp
 clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c 
clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.h 
clang-tools-extra/clang-tidy/utils/Matchers.h 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions.c
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index 8d9ffda04a..c2f23c309f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -34,8 +34,10 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
-static constexpr llvm::StringLiteral CustomFunctionNamesId = 
"CustomFunctionNames";
-static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId = 
"CustomAnnexKFunctionNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId =
+"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId =
+"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -138,7 +140,7 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
 }
 
 static std::vector
-ParseCheckedFunctions(StringRef Option, StringRef OptionName, 
+ParseCheckedFunctions(StringRef Option, StringRef OptionName,
   ClangTidyContext *Context) {
   std::vector Functions = utils::options::parseStringList(Option);
   std::vector Result;
@@ -153,19 +155,22 @@ ParseCheckedFunctions(StringRef Option, StringRef 
OptionName,
 auto [Replacement, Reason] = Rest.split(',');
 
 if (Name.trim().empty()) {
-  Context->configurationDiag(
-"invalid configuration value for option '%0'; "
-"expected the name of an unsafe function") << OptionName;
+  Context->configurationDiag("invalid configuration value for option '%0'; 
"
+ "expected the name of an unsafe function")
+  << OptionName;
 }
 
 if (Replacement.trim().empty()) {
   Context->configurationDiag(
-"invalid configuration value '%0' for option '%1'; "
-"expected a replacement function name") << Name.trim() << OptionName;
+  "invalid configuration value '%0' for option '%1'; "
+  "expected a replacement function name")
+  << Name.trim() << OptionName;
 }
 
-Result.push_back({ Name.trim().str(), 
matchers::MatchesAnyListedNameMatcher::NameMatcher(Name.trim()),
-   Replacement.trim().str(), Reason.trim().str() });
+Result.push_back(
+{Name.trim().str(),
+ matchers::MatchesAnyListedNameMatcher::NameMatcher(Name.trim()),
+ Replacement.trim().str(), Reason.trim().str()});
   }
 
   return Result;
@@ -196,14 +201,15 @@ UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
   CustomAnnexKFunctions(ParseCheckedFunctions(
   Options.get(OptionNameCustomAnnexKFunctions, ""),
   OptionNameCustomAnnexKFunctions, Context)),
-  ReportDefaultFunctions(Options.get(OptionNameReportDefaultFunctions, 
true)),
+  ReportDefaultFunctions(
+  Options.get(OptionNameReportDefaultFunctions, true)),
   ReportMoreUnsafeFunctions(
   Options.get(OptionNameReportMoreUnsafeFunctions, true)) {}
 
 void UnsafeFunctionsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
-  Options.store(Opts, OptionNameCustomNormalFunctions, 
+  Options.store(Opts, OptionNameCustomNormalFunctions,
 SerializeCheckedFunctions(CustomNormalFunctions));
-  Options.store(Opts, OptionNameCustomAnnexKFunctions, 
+  Options.store(Opts, OptionNameCustomAnnexKFunctions,
 SerializeCheckedFunctions(CustomAnnexKFunctions));
   Options.store(Opts, OptionNameReportDefaultFunctions, 
ReportDefaultFunctions);
   Options.store(Opts, OptionNameReportMoreUnsafeFunctions,
@@ -215,33 +221,34 @@ void UnsafeFunctionsCheck::registerMatchers(MatchFinder 
*Finder) {
 if (getLangOpts().C11) {
   // Matching functions with safe replacements only in Annex K.
   auto FunctionNamesWithAnnexKReplacementMatcher = hasAnyName(
-  "::bsearch", "::ctime", "::fopen", "::fprintf", "::freopen", 
"::fscanf",
-  

[clang] 902b2a2 - [clang] Add lifetimebound attr to std::span/std::string_view constructor (#103716)

2024-08-28 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-08-28T10:50:17+02:00
New Revision: 902b2a26ab9e1e78dfb66b52fba4512c91472e09

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

LOG: [clang] Add lifetimebound attr to std::span/std::string_view constructor 
(#103716)

With this patch, clang now automatically adds
``[[clang::lifetimebound]]`` to the parameters of `std::span,
std::string_view` constructors, this enables Clang to capture more cases
where the returned reference outlives the object.


Fixes #100567

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/SemaCXX/attr-lifetimebound.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9fa068c2910f4..4289b3374a810b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -220,6 +220,11 @@ Attribute Changes in Clang
 - ``[[clang::lifetimebound]]`` is now explicitly disallowed on explicit object 
member functions
   where they were previously silently ignored.
 
+- Clang now automatically adds ``[[clang::lifetimebound]]`` to the parameters 
of
+  ``std::span, std::string_view`` constructors, this enables Clang to capture
+  more cases where the returned reference outlives the object.
+  (#GH100567)
+
 Improvements to Clang's diagnostics
 ---
 

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..ed1c279fefe29c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1806,6 +1806,9 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
 
+  /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
+  void inferLifetimeBoundAttribute(FunctionDecl *FD);
+
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 

diff  --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index a1724820472b59..fb594e6f13c0b3 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -216,6 +216,59 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
   inferGslPointerAttribute(Record, Record);
 }
 
+void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
+  if (FD->getNumParams() == 0)
+return;
+
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:
+case Builtin::BIforward:
+case Builtin::BIforward_like:
+case Builtin::BImove:
+case Builtin::BImove_if_noexcept:
+  if (ParmVarDecl *P = FD->getParamDecl(0u);
+  !P->hasAttr())
+P->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  break;
+default:
+  break;
+}
+return;
+  }
+  if (auto *CMD = dyn_cast(FD)) {
+const auto *CRD = CMD->getParent();
+if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
+  return;
+
+if (isa(CMD)) {
+  auto *Param = CMD->getParamDecl(0);
+  if (Param->hasAttr())
+return;
+  if (CRD->getName() == "basic_string_view" &&
+  Param->getType()->isPointerType()) {
+// construct from a char array pointed by a pointer.
+//   basic_string_view(const CharT* s);
+//   basic_string_view(const CharT* s, size_type count);
+Param->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  } else if (CRD->getName() == "span") {
+// construct from a reference of array.
+//   span(std::type_identity_t (&arr)[N]);
+const auto *LRT = Param->getType()->getAs();
+if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
+  Param->addAttr(
+  LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  }
+}
+  }
+}
+
 void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
   static const llvm::StringSet<> Nullable{
   "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b0ccbbe34b70c3..4efa80778e71b9 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16608,27 +16608,9 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 default:
   break;
 }
-
-// Add lifetime attribute to std::move, std::fowrard et al.
-switch (BuiltinID) {
-c

[clang] [clang] Add lifetimebound attr to std::span/std::string_view constructor (PR #103716)

2024-08-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein closed 
https://github.com/llvm/llvm-project/pull/103716
___
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 new `bugprone-suspicious-pointer-arithmetics-using-sizeof` (`cert-arr39-c`) check (PR #106061)

2024-08-28 Thread via cfe-commits

whisperity wrote:

@nicovank 
> Add check and alias entries to 
> [clang-tools-extra/docs/clang-tidy/checks/list.rst](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/docs/clang-tidy/checks/list.rst).
> 
> Check name: this is not only sizeof. Maybe 
> `bugprone-suspicious-pointer-scaling-arithmetic`? Others may have other ideas.

The new check will be dropped and instead the functionality is going to be 
integrated into **ˋbugprone-sizeof-expressionˋ**, which already checks a lot 
more other cases and then some, related to pointer arithmetics as well.

The check's name would have been fine as-is now (and making it part of 
_ˋbugprone-sizeof-expressionˋ_ will be fine as well), because the vast majority 
of cases will have ˋsizeofˋ as the issue, and both ˋalignof()ˋ and ˋoffsetof()ˋ 
essentially scaled **with** ˋsizeofˋ internally, **AND** lets the user commit 
to the same bogus pattern by doing another scaling with the ˋ+ˋ/ˋ-ˋ operator.

@nicovank
> The two examples in the check documentation would not be matched with the 
> current version of this check as they mutiply the `sizeof` expression with a 
> constant before addition. I feel like this is also a common pattern. Can this 
> check also catch those?

Yes, I have already added some deliberately failing tests for these last night, 
and I am engineering the appropriate matchers for this.

https://github.com/llvm/llvm-project/pull/106061
___
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 user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/106350

>From c4e05bdb36e270cbf0557f38fad7c04edf011905 Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Wed, 28 Aug 2024 08:47:20 +
Subject: [PATCH 1/3] [clang-tidy] Add user-defined functions to
 bugprone-unsafe-functions check

---
 .../bugprone/UnsafeFunctionsCheck.cpp | 225 +++---
 .../bugprone/UnsafeFunctionsCheck.h   |  12 +
 .../checks/bugprone/unsafe-functions.rst  |  49 
 .../bugprone/unsafe-functions-custom.c|  38 +++
 .../checkers/bugprone/unsafe-functions.c  |   6 +
 5 files changed, 295 insertions(+), 35 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index ea7eaa0b0ff811..05c2063402b080 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/PPCallbacks.h"
@@ -18,6 +20,12 @@ using namespace llvm;
 
 namespace clang::tidy::bugprone {
 
+static constexpr llvm::StringLiteral OptionNameCustomNormalFunctions =
+"CustomNormalFunctions";
+static constexpr llvm::StringLiteral OptionNameCustomAnnexKFunctions =
+"CustomAnnexKFunctions";
+static constexpr llvm::StringLiteral OptionNameReportDefaultFunctions =
+"ReportDefaultFunctions";
 static constexpr llvm::StringLiteral OptionNameReportMoreUnsafeFunctions =
 "ReportMoreUnsafeFunctions";
 
@@ -26,6 +34,10 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId =
+"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId =
+"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -127,57 +139,155 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
   return CacheVar.value();
 }
 
+static std::vector
+ParseCheckedFunctions(StringRef Option, StringRef OptionName,
+  ClangTidyContext *Context) {
+  std::vector Functions = utils::options::parseStringList(Option);
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (StringRef Function : Functions) {
+if (Function.empty()) {
+  continue;
+}
+
+auto [Name, Rest] = Function.split(',');
+auto [Replacement, Reason] = Rest.split(',');
+
+if (Name.trim().empty()) {
+  Context->configurationDiag("invalid configuration value for option '%0'; 
"
+ "expected the name of an unsafe function")
+  << OptionName;
+}
+
+if (Replacement.trim().empty()) {
+  Context->configurationDiag(
+  "invalid configuration value '%0' for option '%1'; "
+  "expected a replacement function name")
+  << Name.trim() << OptionName;
+}
+
+Result.push_back({Name.trim().str(), llvm::Regex(Name.trim()),
+  Replacement.trim().str(), Reason.trim().str()});
+  }
+
+  return Result;
+}
+
+static std::string SerializeCheckedFunctions(
+const std::vector &Functions) {
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (const auto &Entry : Functions) {
+if (Entry.Reason.empty())
+  Result.push_back(Entry.Name + "," + Entry.Replacement);
+else
+  Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
+   Entry.Reason);
+  }
+
+  return llvm::join(Result, ";");
+}
+
 UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
+  CustomNormalFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomNormalFunctions, ""),
+  OptionNameCustomNormalFunctions, Context)),
+  CustomAnnexKFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomAnnexKFunctions, ""),
+  OptionNameCustomAnnexKFunctions, Context)),
+  ReportDefaultFunctions(
+  Options.get(OptionNameReportDefaultFunctions, true)),
   ReportMoreUnsafeFunctions(
   Options.get(OptionNameReportMoreUnsafeFunctions, true)) {}
 
 void UnsafeFunctionsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, OptionNameCustomNormalFunctions,
+SerializeChecke

[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits


@@ -1736,6 +1816,25 @@ MallocChecker::MallocMemReturnsAttr(CheckerContext &C, 
const CallEvent &Call,
   return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, Family);
 }
 
+ProgramStateRef MallocChecker::MallocBindRetval(CheckerContext &C,
+const CallEvent &Call,
+ProgramStateRef State,
+bool isAlloca) const {
+  const Expr *CE = Call.getOriginExpr();
+
+  // We expect the allocation functions to return a pointer.
+  if (!Loc::isLocType(CE->getType()))
+return nullptr;
+
+  unsigned Count = C.blockCount();
+  SValBuilder &SVB = C.getSValBuilder();
+  const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
+  DefinedSVal RetVal = (isAlloca ? SVB.getAllocaRegionVal(CE, LCtx, Count)
+ : SVB.getConjuredHeapSymbolVal(CE, LCtx, 
Count)
+   .castAs());

pskrgag wrote:

Ignore previous comment... We can just cast `DefinedOrUnknownSVal` to 
`DefinedSVal` inside `getConjuredHeapSymbolVal`, since we sure there won't be 
FP number.


Will update the PR, thanks!

https://github.com/llvm/llvm-project/pull/106081
___
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 user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits

Discookie wrote:

Note: I copied over the header from the test `unsafe-functions.c` about the 
tests not working on some targets into my new tests. How could I test these 
files on the targets? (Other than just pushing this branch I suppose.)

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


[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Owen Pan via cfe-commits


@@ -3238,6 +3238,12 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[8], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[11], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[13], BK_Block);
+
+  Tokens = annotate("a = class extends goog.a {}",
+getGoogleStyle(FormatStyle::LanguageKind::LK_JavaScript));
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;

owenca wrote:

```suggestion
  Tokens = annotate("a = class extends goog.a {};",
getGoogleStyle(FormatStyle::LK_JavaScript));
  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
```

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


[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Owen Pan via cfe-commits

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

LG except some nits.

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


[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Owen Pan via cfe-commits

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Donát Nagy via cfe-commits


@@ -241,10 +241,14 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
-static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
-  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+static const MemRegion *skipStdBaseClassRegion(const MemRegion *Reg) {
+  do {
+assert(Reg);
+const auto *BaseClassRegion = dyn_cast(Reg);
+if (!BaseClassRegion || !BaseClassRegion->getDecl()->isInStdNamespace())

NagyDonat wrote:

``
> isInStdNamespace only works if the decl is exactly within std. Any nested 
> namespaces beyond std, or class scopes are rejected even if their parents 
> reside within std.
IIRC `isInStdNamespace` also accepts anonymous subnamespaces of `std` (so that 
kind of implementation detail won't cause problems at least).
``

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Donát Nagy via cfe-commits

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/106240

>From 0c86e46516466f9513652a04ba87aa2a018ff6b8 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 27 Aug 2024 17:52:25 +0200
Subject: [PATCH 01/10] [analyzer] Fix false positive for mutexes inheriting
 mutex_base

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This possibly fixes #104241

CPP-5541
---
 .../Checkers/BlockInCriticalSectionChecker.cpp |  6 --
 .../Analysis/block-in-critical-section-inheritance.cpp | 10 ++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..52ff639c6b8022 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -245,8 +245,10 @@ static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+if (const MemRegion *Reg = Descr.getRegion(Call, IsLock))
+  return Reg->getBaseRegion();
+return nullptr;
   },
   Descriptor);
 }
diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index db20df8c60a5c9..c60ba2632cee25 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -29,3 +29,13 @@ void gh_99628() {
   // expected-note@-2 {{Call to blocking function 'sleep' inside of critical 
section}}
   m.unlock();
 }
+
+void no_false_positive_gh_104241() {
+  std::mutex m;
+  m.lock();
+  // If inheritance not handled properly, this unlock might not match the lock
+  // above because technically they act on different memory regions:
+  // __mutex_base and mutex.
+  m.unlock();
+  sleep(10); // no-warning
+}

>From 013a6d138b38c51c64860a99b95591491f86c223 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:27:50 +0200
Subject: [PATCH 02/10] Record a false negative associated with the new mutex
 canonicalization

---
 .../block-in-critical-section-inheritance.cpp  | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Analysis/block-in-critical-section-inheritance.cpp 
b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
index c60ba2632cee25..5f6fa565f42fb9 100644
--- a/clang/test/Analysis/block-in-critical-section-inheritance.cpp
+++ b/clang/test/Analysis/block-in-critical-section-inheritance.cpp
@@ -39,3 +39,17 @@ void no_false_positive_gh_104241() {
   m.unlock();
   sleep(10); // no-warning
 }
+
+struct TwoMutexes {
+  std::mutex m1;
+  std::mutex m2;
+};
+
+void two_mutexes_false_negative(TwoMutexes &tm) {
+  tm.m1.lock();
+  tm.m2.unlock();
+  // Critical section is associated with tm now so tm.m1 and tm.m2 are
+  // undistinguishiable
+  sleep(10); // False-negative
+  tm.m1.unlock();
+}

>From 744272e0f1ccd5217c0d456a7c499a9bcae84679 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Wed, 28 Aug 2024 08:33:02 +0200
Subject: [PATCH 03/10] Fix false negative for field regions

---
 .../Checkers/BlockInCriticalSectionChecker.cpp   | 9 -
 .../Analysis/block-in-critical-section-inheritance.cpp   | 9 +
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 52ff639c6b8022..fd8700902c1835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -241,13 +241,20 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
+  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
   [&Call, I

[clang] [clang-format] js handle anonymous classes (PR #106242)

2024-08-28 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg updated 
https://github.com/llvm/llvm-project/pull/106242

>From 32e94bde5a8ed401a9fb1255d8394c552da82dd7 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Tue, 27 Aug 2024 16:08:07 +
Subject: [PATCH 1/4] [clang-format] js handle anonymous classes

Addresses a regression in JavaScript when formatting anonymous classes.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 6 +-
 clang/unittests/Format/FormatTestJS.cpp  | 9 +
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5f1a88d4bcd729..7591eaeae461a7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3992,6 +3992,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   auto IsNonMacroIdentifier = [](const FormatToken *Tok) {
 return Tok->is(tok::identifier) && Tok->TokenText != 
Tok->TokenText.upper();
   };
+  // JavaScript/TypeScript supports anonymous classes like:
+  // a = class extends foo { }
+  bool JSPastExtendsOrImplements = false;
   // The actual identifier can be a nested name specifier, and in macros
   // it is often token-pasted.
   // An [[attribute]] can be before the identifier.
@@ -4002,6 +4005,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   FormatTok->isOneOf(tok::period, tok::comma))) {
 if (Style.isJavaScript() &&
 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
+  JSPastExtendsOrImplements = true;
   // JavaScript/TypeScript supports inline object types in
   // extends/implements positions:
   // class Foo implements {bar: number} { }
@@ -4027,7 +4031,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 case tok::coloncolon:
   break;
 default:
-  if (!ClassName && Previous->is(tok::identifier) &&
+  if (!JSPastExtendsOrImplements && !ClassName && 
Previous->is(tok::identifier) &&
   Previous->isNot(TT_AttributeMacro)) {
 ClassName = Previous;
   }
diff --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index b910ce620de7a9..734c1590c41ddb 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -579,6 +579,15 @@ TEST_F(FormatTestJS, GoogScopes) {
"});");
 }
 
+TEST_F(FormatTestJS, GoogAnonymousClass) {
+  verifyFormat("a = class extends goog.structs.a {\n"
+   "  a() {\n"
+   "return 0;\n"
+   "  }\n"
+   "};");
+}
+
+
 TEST_F(FormatTestJS, IIFEs) {
   // Internal calling parens; no semi.
   verifyFormat("(function() {\n"

>From f42f5d46ba41dc679e42fc50850aa8a6b46c9459 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Tue, 27 Aug 2024 16:58:48 +
Subject: [PATCH 2/4] fix formatting

---
 clang/lib/Format/UnwrappedLineParser.cpp | 4 ++--
 clang/unittests/Format/FormatTestJS.cpp  | 1 -
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7591eaeae461a7..506386526bd15f 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -4031,8 +4031,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 case tok::coloncolon:
   break;
 default:
-  if (!JSPastExtendsOrImplements && !ClassName && 
Previous->is(tok::identifier) &&
-  Previous->isNot(TT_AttributeMacro)) {
+  if (!JSPastExtendsOrImplements && !ClassName &&
+  Previous->is(tok::identifier) && Previous->isNot(TT_AttributeMacro)) 
{
 ClassName = Previous;
   }
 }
diff --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 734c1590c41ddb..4b29ba720f6823 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -587,7 +587,6 @@ TEST_F(FormatTestJS, GoogAnonymousClass) {
"};");
 }
 
-
 TEST_F(FormatTestJS, IIFEs) {
   // Internal calling parens; no semi.
   verifyFormat("(function() {\n"

>From 8283b7f9bb422c9692ffa83c034dcab8aee41a9a Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Wed, 28 Aug 2024 08:04:46 +
Subject: [PATCH 3/4] add a token annotator test

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index db44d418a84484..04a9fa760ce878 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3238,6 +3238,12 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[8], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[11], BK_BracedInit);
   EXPECT_BRACE_KIND(Tokens[13], BK_Block);
+
+  Tokens = annotate("a = class extends goog.a {}",
+

[clang] [clang-format] Add new option: WrapNamespaceBodyWithNewlines (PR #106145)

2024-08-28 Thread via cfe-commits


@@ -5057,6 +5057,21 @@ struct FormatStyle {
   /// \version 11
   std::vector WhitespaceSensitiveMacros;
 
+  /// Insert a newline at the begging and at the end of namespace definition
+  /// \code
+  ///   false:   vs.  true:
+  ///
+  ///   namespace a { namespace a {
+  ///   namespace b { namespace b {
+  /// function();
+  ///   } function();
+  ///   }
+  /// }
+  /// }
+  /// \endcode
+  /// \version 19
+  bool WrapNamespaceBodyWithNewlines;

dmasloff wrote:

Could you confirm my guess about behavior of this options?
- Always: fixes all namespaces with 1 additional newline at the begging and at 
the end of namespace
- Never:   removes all newlines at the begging and at the end of namespace
- Leave:   doesn't affect this aspect of user code

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


[clang] [clang-format] Add new option: WrapNamespaceBodyWithNewlines (PR #106145)

2024-08-28 Thread via cfe-commits

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


[clang] 07514fa - [Coroutines] Salvage the debug information for coroutine frames within optimizations

2024-08-28 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-08-28T17:02:12+08:00
New Revision: 07514fa9b607fd80a72a80270d714e22d842fa39

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

LOG: [Coroutines] Salvage the debug information for coroutine frames within 
optimizations

This patch tries to salvage the debug information for the coroutine
frames within optimizations by creating the help alloca varaibles with
optimizations too. We didn't do this when I implement it initially. I
roughtly remember the reason was, we feel the additional help alloca
variable may pessimize the performance, which is almost the most
important thing under optimizations. But now, it looks like the new
inserted help alloca variables can be optimized out by the following
optimizations. So it looks like the time to make it available within
optimizations.

And also, it looks like the following optimizations will convert the
generated dbg.declare instrinsic into dbg.value intrinsic within
optimizations.

In LLVM's test, there is a slightly regression
that a dbg.declare for the promise object failed to be remained after
this change. But it looks like we won't have a chance to see dbg.declare
for the promise object when we split the coroutine as that dbg.declare
will be converted into a dbg.value in early stage.

So everything looks fine.

Added: 
clang/test/CodeGenCoroutines/coro-dwarf-O2.cpp

Modified: 
llvm/lib/Transforms/Coroutines/CoroFrame.cpp
llvm/lib/Transforms/Coroutines/CoroInternal.h
llvm/lib/Transforms/Coroutines/CoroSplit.cpp
llvm/test/Transforms/Coroutines/coro-debug-O2.ll

Removed: 




diff  --git a/clang/test/CodeGenCoroutines/coro-dwarf-O2.cpp 
b/clang/test/CodeGenCoroutines/coro-dwarf-O2.cpp
new file mode 100644
index 00..53f4a07982e427
--- /dev/null
+++ b/clang/test/CodeGenCoroutines/coro-dwarf-O2.cpp
@@ -0,0 +1,39 @@
+// Check that we can still observe the value of the coroutine frame
+// with optimizations.
+//
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++20 \
+// RUN:   -emit-llvm %s -debug-info-kind=limited -dwarf-version=5 \
+// RUN:   -O2 -o - | FileCheck %s
+
+#include "Inputs/coroutine.h"
+
+template <>
+struct std::coroutine_traits {
+  struct promise_type {
+void get_return_object();
+std::suspend_always initial_suspend();
+std::suspend_always final_suspend() noexcept;
+void return_void();
+void unhandled_exception();
+  };
+};
+
+struct ScalarAwaiter {
+  template  void await_suspend(F);
+  bool await_ready();
+  int await_resume();
+};
+
+extern "C" void UseScalar(int);
+
+extern "C" void f() {
+  UseScalar(co_await ScalarAwaiter{});
+
+  int Val = co_await ScalarAwaiter{};
+
+  co_await ScalarAwaiter{};
+}
+
+// CHECK: define {{.*}}@f.resume({{.*}} %[[ARG:.*]])
+// CHECK:  #dbg_value(ptr %[[ARG]], ![[CORO_NUM:[0-9]+]], 
!DIExpression(DW_OP_deref)
+// CHECK: ![[CORO_NUM]] = !DILocalVariable(name: "__coro_frame"

diff  --git a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp 
b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
index 740ae661359445..f76cfe01b58cfd 100644
--- a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
@@ -1947,8 +1947,7 @@ static void insertSpills(const FrameDataInfo &FrameData, 
coro::Shape &Shape) {
   }
   // This dbg.declare is for the main function entry point.  It
   // will be deleted in all coro-split functions.
-  coro::salvageDebugInfo(ArgToAllocaMap, *DDI, Shape.OptimizeFrame,
- false /*UseEntryValue*/);
+  coro::salvageDebugInfo(ArgToAllocaMap, *DDI, false 
/*UseEntryValue*/);
 };
 for_each(DIs, SalvageOne);
 for_each(DVRs, SalvageOne);
@@ -2885,9 +2884,8 @@ static void collectFrameAlloca(AllocaInst *AI, 
coro::Shape &Shape,
 
 static std::optional>
 salvageDebugInfoImpl(SmallDenseMap 
&ArgToAllocaMap,
- bool OptimizeFrame, bool UseEntryValue, Function *F,
- Value *Storage, DIExpression *Expr,
- bool SkipOutermostLoad) {
+ bool UseEntryValue, Function *F, Value *Storage,
+ DIExpression *Expr, bool SkipOutermostLoad) {
   IRBuilder<> Builder(F->getContext());
   auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
   while (isa(InsertPt))
@@ -2939,10 +2937,9 @@ salvageDebugInfoImpl(SmallDenseMap &ArgToAllocaMap,
 
   // If the coroutine frame is an Argument, store it in an alloca to improve
   // its availability (e.g. registers may be clobbered).
-  // Avoid this if optimizations are enabled (they would remove the alloca) or
-  // if the value is guaranteed to be available through other means (e.g. swift
-  // ABI guarantees).
-  if (StorageAsArg && !OptimizeFrame && !IsSwiftAs

[clang] [clang-format] Add new option: WrapNamespaceBodyWithNewlines (PR #106145)

2024-08-28 Thread via cfe-commits


@@ -1493,6 +1511,18 @@ static auto computeNewlines(const AnnotatedLine &Line,
 Newlines = 1;
   }
 
+  // Insert empty line after "{" that opens namespace scope
+  if (Style.WrapNamespaceBodyWithNewlines &&
+  LineStartsNamespaceScope(&Line, PreviousLine, PrevPrevLine)) {
+Newlines = 2;

dmasloff wrote:

I have not tested it yet, probably will add test about this in pr update, but 
since it's going later then all usings of `Style.MaxEmptyLinesToKeep` it 
overrides behavior of this option in namespaces, which seems reasonable. Could 
change it to `Newlines = std::min(2, Style.MaxEmptyLinesToKeep)` in `Leave` 
option if moving to proposed enum and existing`Newlines = 2` can be used for 
`Always`?

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


[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits


@@ -2815,7 +2906,7 @@ MallocChecker::ReallocMemAux(CheckerContext &C, const 
CallEvent &Call,
 
 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, 
size).
 SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
-SVal RetVal = C.getSVal(CE);
+SVal RetVal = stateRealloc->getSVal(CE, C.getLocationContext());
 SymbolRef ToPtr = RetVal.getAsSymbol();
 assert(FromPtr && ToPtr &&
"By this point, FreeMemAux and MallocMemAux should have checked "

pskrgag wrote:

Based on code inspection and basic tests (like passing undefined values to 
realloc) this assertation still holds

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


[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits

https://github.com/pskrgag updated 
https://github.com/llvm/llvm-project/pull/106081

>From 82e3d871766b132d0ce0b9e8e74371d8598d2431 Mon Sep 17 00:00:00 2001
From: Pavel Skripkin 
Date: Tue, 6 Aug 2024 19:12:01 +0300
Subject: [PATCH 1/4] wip

---
 .../Core/PathSensitive/DynamicExtent.h|   2 +-
 .../StaticAnalyzer/Checkers/MallocChecker.cpp | 355 +++---
 .../Checkers/VLASizeChecker.cpp   |   3 +-
 .../lib/StaticAnalyzer/Core/DynamicExtent.cpp |   2 +-
 .../Core/ExprEngineCallAndReturn.cpp  |   3 +-
 .../test/Analysis/NewDelete-checker-test.cpp  |  13 -
 .../test/Analysis/NewDelete-intersections.mm  |   6 +-
 clang/test/Analysis/malloc-interprocedural.c  |  35 --
 8 files changed, 233 insertions(+), 186 deletions(-)

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
index 50d5d254415af3..1a9bef06b15a44 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
@@ -36,7 +36,7 @@ DefinedOrUnknownSVal getDynamicElementCount(ProgramStateRef 
State,
 
 /// Set the dynamic extent \p Extent of the region \p MR.
 ProgramStateRef setDynamicExtent(ProgramStateRef State, const MemRegion *MR,
- DefinedOrUnknownSVal Extent, SValBuilder 
&SVB);
+ DefinedOrUnknownSVal Extent);
 
 /// Get the dynamic extent for a symbolic value that represents a buffer. If
 /// there is an offsetting to the underlying buffer we consider that too.
diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 3ddcb7e94ae5d6..1f524481049fa4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -315,13 +315,24 @@ struct ReallocPair {
 
 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
 
-/// Tells if the callee is one of the builtin new/delete operators, including
-/// placement operators and other standard overloads.
-static bool isStandardNewDelete(const FunctionDecl *FD);
-static bool isStandardNewDelete(const CallEvent &Call) {
+static bool isStandardNew(const FunctionDecl *FD);
+static bool isStandardNew(const CallEvent &Call) {
+  if (!Call.getDecl() || !isa(Call.getDecl()))
+return false;
+  return isStandardNew(cast(Call.getDecl()));
+}
+
+static bool isStandardDelete(const FunctionDecl *FD);
+static bool isStandardDelete(const CallEvent &Call) {
   if (!Call.getDecl() || !isa(Call.getDecl()))
 return false;
-  return isStandardNewDelete(cast(Call.getDecl()));
+  return isStandardDelete(cast(Call.getDecl()));
+}
+
+/// Tells if the callee is one of the builtin new/delete operators, including
+/// placement operators and other standard overloads.
+template  static bool isStandardNewDelete(const T &FD) {
+  return isStandardDelete(FD) || isStandardNew(FD);
 }
 
 
//===--===//
@@ -334,8 +345,9 @@ class MallocChecker
 : public Checker,
  check::EndFunction, check::PreCall, check::PostCall,
- check::NewAllocator, check::PostStmt,
- check::PostObjCMessage, check::Location, eval::Assume> {
+ eval::Call, check::NewAllocator,
+ check::PostStmt, check::PostObjCMessage,
+ check::Location, eval::Assume> {
 public:
   /// In pessimistic mode, the checker assumes that it does not know which
   /// functions might free the memory.
@@ -367,6 +379,7 @@ class MallocChecker
 
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
   void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) 
const;
   void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) 
const;
   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
@@ -403,7 +416,8 @@ class MallocChecker
   mutable std::unique_ptr BT_TaintedAlloc;
 
 #define CHECK_FN(NAME) 
\
-  void NAME(const CallEvent &Call, CheckerContext &C) const;
+  void NAME(ProgramStateRef State, const CallEvent &Call, CheckerContext &C)   
\
+  const;
 
   CHECK_FN(checkFree)
   CHECK_FN(checkIfNameIndex)
@@ -423,11 +437,12 @@ class MallocChecker
   CHECK_FN(checkReallocN)
   CHECK_FN(checkOwnershipAttr)
 
-  void checkRealloc(const CallEvent &Call, CheckerContext &C,
-bool ShouldFreeOnFail) const;
+  void checkRealloc(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C, bool ShouldFreeOnFail) const;
 
-  using CheckFn = std::function;
+  using CheckFn =
+  std::f

[clang] [WIP] [analyzer] Refactor MallocChecker to use `BindExpr` in `evalCall` (PR #106081)

2024-08-28 Thread Pavel Skripkin via cfe-commits

pskrgag wrote:

Thank you so much for review! After invalidating location in `FreeMemAux` 
everything started working as it should. Also changed 
`getConjuredHeapSymbolVal` to return `DefinedSVal`.

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread Rainer Orth via cfe-commits

https://github.com/rorth created 
https://github.com/llvm/llvm-project/pull/106353

Recently, Solaris bootstrap got broken because Solaris uses a non-standard 
mangling of `std::tm` and a few others.  This was fixed with a hack in PR 
Solaris ABI requirements, mangling `std::tm` as `tm` and similarly for 
`std::div_t`, `std::ldiv_t`, and `std::lconv`.

Tested on `amd64-pc-solaris2.11`, `sparcv9-sun-solaris2.11`, and 
`x86_64-pc-linux-gnu`.

Unfortunately, this patch is almost there, but not quite yet: while the new 
testcase works as expected, the original trigger in 
`clang/lib/Lex/PPMacroExpansion.cpp` is now mangled into 
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSA_`
 (`std::time_put> 
>::put(std::ostreambuf_iterator >,std::ios_base&, 
char, tm const*, char const*, char const) const`) instead of the expected
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSB_`
 (`std::time_put> 
>::put(std::ostreambuf_iterator >,std::ios_base&, 
char, tm const*, char const*, char const*) const`), i.e. `char const` for the 
final arg instead of `char const*`.  I don't have the slightest idea why, 
unfortunately.

>From 646c6ad032fe9c15faee03246496958f7592ea75 Mon Sep 17 00:00:00 2001
From: Rainer Orth 
Date: Wed, 28 Aug 2024 11:24:29 +0200
Subject: [PATCH] [WIP][clang] Fix std::tm etc. mangling on Solaris

Recently, Solaris bootstrap got broken because Solaris uses a non-standard
mangling of `std::tm` and a few others.  This was fixed with a hack in PR
Solaris ABI requirements, mangling `std::tm` as `tm` and similarly for
`std::div_t`, `std::ldiv_t`, and `std::lconv`.

Tested on `amd64-pc-solaris2.11`, `sparcv9-sun-solaris2.11`, and
`x86_64-pc-linux-gnu`.

Unfortunately, this patch is almost there, but not quite yet: while the new
testcase works as expected, the original trigger in
`clang/lib/Lex/PPMacroExpansion.cpp` is now mangled into
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSA_`
(`std::time_put
> >::put(std::ostreambuf_iterator >,
std::ios_base&, char, tm const*, char const*, char const) const`) instead
of the expected
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSB_`
(`std::time_put
> >::put(std::ostreambuf_iterator >,
std::ios_base&, char, tm const*, char const*, char const*) const`),
i.e. `char const` for the final arg instead of `char const*`.  I don't have
the slightest idea why, unfortunately.
---
 clang/lib/AST/ItaniumMangle.cpp| 22 ++
 clang/lib/Lex/PPMacroExpansion.cpp |  6 --
 clang/test/AST/solaris-tm.cpp  | 27 +++
 3 files changed, 53 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/AST/solaris-tm.cpp

diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 976670d1efa561..12c926d589b3dc 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -38,6 +38,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/TargetParser/RISCVTargetParser.h"
 #include 
+#include 
 
 using namespace clang;
 
@@ -6953,6 +6954,27 @@ bool CXXNameMangler::mangleStandardSubstitution(const 
NamedDecl *ND) {
 return false;
   }
 
+  if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
+if (const RecordDecl *RD = dyn_cast(ND)) {
+  if (!isStdNamespace(Context.getEffectiveDeclContext(RD)))
+return false;
+
+  // Issue #33114: Need non-standard mangling of std::tm etc. for
+  // Solaris ABI compatibility.
+  static std::set types{"div_t", "ldiv_t", "lconv", "tm"};
+
+  //  ::= tm # ::std::tm, same for the others
+  if (const IdentifierInfo *II = RD->getIdentifier()) {
+StringRef type = II->getName();
+if (types.count(type)) {
+  Out << type.size() << type;
+  return true;
+}
+  }
+  return false;
+}
+  }
+
   return false;
 }
 
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index 1d671ab72b0c03..a8991c28f0261f 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1604,10 +1604,12 @@ static bool isTargetVariantEnvironment(const TargetInfo 
&TI,
   return false;
 }
 
-#if defined(__sun__) && defined(__svr4__)
+#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && 
\
+__clang__ < 20
 // GCC mangles std::tm as tm for binary compatibility on Solaris (Issue
 // #33114).  We need to match this to allow the std::put_time calls to link
-// (PR #99075).
+// (PR #99075).  clang 20 contains a fix, but the workaround is still needed
+// with older versions.
 asm("_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
 "RSt8ios_basecPKSt2tmPKcSB_ = "
 "_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
diff --git a/clang/test/AST/solaris-tm.cpp b/clang/test/AST/solaris-tm.cpp

[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Rainer Orth (rorth)


Changes

Recently, Solaris bootstrap got broken because Solaris uses a non-standard 
mangling of `std::tm` and a few others.  This was fixed with a hack in PR 
Solaris ABI requirements, mangling `std::tm` as `tm` and similarly for 
`std::div_t`, `std::ldiv_t`, and `std::lconv`.

Tested on `amd64-pc-solaris2.11`, `sparcv9-sun-solaris2.11`, and 
`x86_64-pc-linux-gnu`.

Unfortunately, this patch is almost there, but not quite yet: while the new 
testcase works as expected, the original trigger in 
`clang/lib/Lex/PPMacroExpansion.cpp` is now mangled into 
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSA_`
 (`std::time_put> 
>::put(std::ostreambuf_iterator 
>,std::ios_base&, char, tm const*, char const*, char const) const`) 
instead of the expected
`_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_RSt8ios_basecPK2tmPKcSB_`
 (`std::time_put> 
>::put(std::ostreambuf_iterator 
>,std::ios_base&, char, tm const*, char const*, char const*) const`), 
i.e. `char const` for the final arg instead of `char const*`.  I don't have the 
slightest idea why, unfortunately.

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


3 Files Affected:

- (modified) clang/lib/AST/ItaniumMangle.cpp (+22) 
- (modified) clang/lib/Lex/PPMacroExpansion.cpp (+4-2) 
- (added) clang/test/AST/solaris-tm.cpp (+27) 


``diff
diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 976670d1efa561..12c926d589b3dc 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -38,6 +38,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/TargetParser/RISCVTargetParser.h"
 #include 
+#include 
 
 using namespace clang;
 
@@ -6953,6 +6954,27 @@ bool CXXNameMangler::mangleStandardSubstitution(const 
NamedDecl *ND) {
 return false;
   }
 
+  if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
+if (const RecordDecl *RD = dyn_cast(ND)) {
+  if (!isStdNamespace(Context.getEffectiveDeclContext(RD)))
+return false;
+
+  // Issue #33114: Need non-standard mangling of std::tm etc. for
+  // Solaris ABI compatibility.
+  static std::set types{"div_t", "ldiv_t", "lconv", "tm"};
+
+  //  ::= tm # ::std::tm, same for the others
+  if (const IdentifierInfo *II = RD->getIdentifier()) {
+StringRef type = II->getName();
+if (types.count(type)) {
+  Out << type.size() << type;
+  return true;
+}
+  }
+  return false;
+}
+  }
+
   return false;
 }
 
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index 1d671ab72b0c03..a8991c28f0261f 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1604,10 +1604,12 @@ static bool isTargetVariantEnvironment(const TargetInfo 
&TI,
   return false;
 }
 
-#if defined(__sun__) && defined(__svr4__)
+#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && 
\
+__clang__ < 20
 // GCC mangles std::tm as tm for binary compatibility on Solaris (Issue
 // #33114).  We need to match this to allow the std::put_time calls to link
-// (PR #99075).
+// (PR #99075).  clang 20 contains a fix, but the workaround is still needed
+// with older versions.
 asm("_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
 "RSt8ios_basecPKSt2tmPKcSB_ = "
 "_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
diff --git a/clang/test/AST/solaris-tm.cpp b/clang/test/AST/solaris-tm.cpp
new file mode 100644
index 00..f3d16b7ba1116f
--- /dev/null
+++ b/clang/test/AST/solaris-tm.cpp
@@ -0,0 +1,27 @@
+/// Check that std::tm and a few others are mangled as tm on Solaris only.
+/// Issue #33114.
+///
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple amd64-pc-solaris2.11 | FileCheck 
--check-prefix=CHECK-SOLARIS %s
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-unknown-linux-gnu  | 
FileCheck --check-prefix=CHECK-LINUX %s
+//
+// REQUIRES: x86-registered-target
+//
+// CHECK-SOLARIS: @_Z6tmfunc2tm
+// CHECK-SOLARIS: @_Z7ldtfunc6ldiv_t
+// CHECK-LINUX:   @_Z6tmfuncSt2tm
+// CHECK-LINUX:   @_Z7ldtfuncSt6ldiv_t
+
+namespace std {
+  extern "C" {
+struct tm {
+  int tm_sec;
+};
+struct ldiv_t {
+  long quot;
+};
+  }
+}
+
+void tmfunc (std::tm tm) {}
+
+void ldtfunc (std::ldiv_t ldt) {}

``




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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits

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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov commented:

Suggestion: could we update the PR title to say something like "Output location 
in separate fields of `-ftime-trace`"?

"properly" is open to interpretation and requires reading the full change 
description.

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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits


@@ -1255,8 +1256,12 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclarationOrFunctionDefinition(
   // Add an enclosing time trace scope for a bunch of small scopes with
   // "EvaluateAsConstExpr".
   llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() 
{
-return Tok.getLocation().printToString(
-Actions.getASTContext().getSourceManager());
+llvm::TimeTraceMetadata M;
+const SourceManager &SM = Actions.getASTContext().getSourceManager();
+auto Loc = SM.getExpansionLoc(Tok.getLocation());
+M.File = SM.getFilename(Loc);

ilya-biryukov wrote:

This is guarded by `isTimeTraceVerbose` in other places, but not here.
The only reason I can see for that is historical accidents, although perhaps 
the parsing events are less frequent too.

That being said, I don't think we should necessarily change it in this patch, 
but could we add a FIXME here saying that other places only log locations in 
verbose mode and an explanation why this one does not?

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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits


@@ -1255,8 +1256,12 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclarationOrFunctionDefinition(
   // Add an enclosing time trace scope for a bunch of small scopes with
   // "EvaluateAsConstExpr".
   llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() 
{
-return Tok.getLocation().printToString(
-Actions.getASTContext().getSourceManager());
+llvm::TimeTraceMetadata M;

ilya-biryukov wrote:

The column might be a little redundant for functions, but may be useful for 
other events to help identify them.
Should we add it now? Are there any downsides to adding it?

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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits


@@ -223,15 +223,15 @@ Frontend (test.cc)
 | | | | EvaluateAsRValue ()
 | | | EvaluateAsBooleanCondition ()
 | | | | EvaluateAsRValue ()
-| ParseDeclarationOrFunctionDefinition (test.cc:16:1)
+| ParseDeclarationOrFunctionDefinition (test.cc:16)
 | | ParseFunctionDefinition (slow_test)
 | | | EvaluateAsInitializer (slow_value)
 | | | EvaluateAsConstantExpr ()

ilya-biryukov wrote:

Is there any reason to keep these locations different?
Why not don't we change them into the structured output for consistency too?

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


[clang] [clang] Properly set file and line info for -ftime-trace (PR #106277)

2024-08-28 Thread Ilya Biryukov via cfe-commits


@@ -1255,8 +1256,12 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclarationOrFunctionDefinition(
   // Add an enclosing time trace scope for a bunch of small scopes with
   // "EvaluateAsConstExpr".
   llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() 
{
-return Tok.getLocation().printToString(
-Actions.getASTContext().getSourceManager());
+llvm::TimeTraceMetadata M;
+const SourceManager &SM = Actions.getASTContext().getSourceManager();
+auto Loc = SM.getExpansionLoc(Tok.getLocation());

ilya-biryukov wrote:

Could we extract the function that fills `SourceLocation` into 
`TimeTraceMetadata`?
This can be done in a follow up, but we are starting to have too many places 
now that do the same thing and should all be changed together (e.g. if we'd 
want to spell filename in some other way or if we'd want to use something other 
than expansionLocation in the future, or we'd want to add a column, etc)

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -241,10 +241,14 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
-static const MemRegion *skipBaseClassRegion(const MemRegion *Reg) {
-  while (const auto *BaseClassRegion = dyn_cast(Reg)) {
+static const MemRegion *skipStdBaseClassRegion(const MemRegion *Reg) {
+  do {
+assert(Reg);
+const auto *BaseClassRegion = dyn_cast(Reg);
+if (!BaseClassRegion || !BaseClassRegion->getDecl()->isInStdNamespace())

necto wrote:

fixed with e94327b

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


[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

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

Let's merge this.

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


[clang] 82e314e - [analyzer] Fix false positive for mutexes inheriting mutex_base (#106240)

2024-08-28 Thread via cfe-commits

Author: Arseniy Zaostrovnykh
Date: 2024-08-28T11:30:18+02:00
New Revision: 82e314e3664d2c8768212e74f751187d51950b87

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

LOG: [analyzer] Fix false positive for mutexes inheriting mutex_base (#106240)

If a mutex interface is split in inheritance chain, e.g. struct mutex
has `unlock` and inherits `lock` from __mutex_base then calls m.lock()
and m.unlock() have different "this" targets: m and the __mutex_base of
m, which used to confuse the `ActiveCritSections` list.

Taking base region canonicalizes the region used to identify a critical
section and enables search in ActiveCritSections list regardless of
which class the callee is the member of.

This likely fixes #104241

CPP-5541

Added: 
clang/test/Analysis/block-in-critical-section-nested-namespace.cpp

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
clang/test/Analysis/block-in-critical-section-inheritance.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
index d053a97189123a..b4afaaeec9a4bd 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
@@ -6,7 +6,7 @@
 //
 
//===--===//
 //
-//  This file defines CheckerVisitor.
+//  This file defines various utilities used by checkers.
 //
 
//===--===//
 
@@ -114,6 +114,10 @@ OperatorKind 
operationKindFromOverloadedOperator(OverloadedOperatorKind OOK,
 
 std::optional getPointeeVal(SVal PtrSVal, ProgramStateRef State);
 
+/// Returns true if declaration \p D is in std namespace or any nested 
namespace
+/// or class scope.
+bool isWithinStdNamespace(const Decl *D);
+
 } // namespace ento
 
 } // namespace clang

diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 4cd2f2802f30cd..7460781799d08a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -20,6 +20,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
@@ -241,12 +242,22 @@ BlockInCriticalSectionChecker::checkDescriptorMatch(const 
CallEvent &Call,
   return std::nullopt;
 }
 
+static const MemRegion *skipStdBaseClassRegion(const MemRegion *Reg) {
+  while (Reg) {
+const auto *BaseClassRegion = dyn_cast(Reg);
+if (!BaseClassRegion || !isWithinStdNamespace(BaseClassRegion->getDecl()))
+  break;
+Reg = BaseClassRegion->getSuperRegion();
+  }
+  return Reg;
+}
+
 static const MemRegion *getRegion(const CallEvent &Call,
   const MutexDescriptor &Descriptor,
   bool IsLock) {
   return std::visit(
-  [&Call, IsLock](auto &&Descriptor) {
-return Descriptor.getRegion(Call, IsLock);
+  [&Call, IsLock](auto &Descr) -> const MemRegion * {
+return skipStdBaseClassRegion(Descr.getRegion(Call, IsLock));
   },
   Descriptor);
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index eba224b8ec01ce..1efac6ac1c57f4 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -38,6 +38,7 @@
 #include "clang/CrossTU/CrossTranslationUnit.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
@@ -923,17 +924,6 @@ SVal AnyCXXConstructorCall::getCXXThisVal() const {
   return UnknownVal();
 }
 
-static bool isWithinStdNamespace(const Decl *

[clang] [analyzer] Fix false positive for mutexes inheriting mutex_base (PR #106240)

2024-08-28 Thread Balazs Benics via cfe-commits

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


[clang-tools-extra] [clangd] Update TidyFastChecks for release/19.x (PR #106354)

2024-08-28 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet created 
https://github.com/llvm/llvm-project/pull/106354

Run for clang-tidy checks available in release/19.x branch.

Some notable findings:
- altera-id-dependent-backward-branch, stays slow with 13%.
- misc-const-correctness become faster, going from 261% to 67%, but still above
  8% threshold.
- misc-header-include-cycle is a new SLOW check with 10% runtime implications
- readability-container-size-empty went from 16% to 13%, still SLOW.


From 38df7489ff2fa15a5bc7fc66d18ef78b489cd9d8 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 28 Aug 2024 11:27:47 +0200
Subject: [PATCH] [clangd] Update TidyFastChecks for release/19.x

---
 clang-tools-extra/clangd/TidyFastChecks.inc | 670 +++-
 1 file changed, 368 insertions(+), 302 deletions(-)

diff --git a/clang-tools-extra/clangd/TidyFastChecks.inc 
b/clang-tools-extra/clangd/TidyFastChecks.inc
index 9050ce16127ff4..b1e1bf05172daa 100644
--- a/clang-tools-extra/clangd/TidyFastChecks.inc
+++ b/clang-tools-extra/clangd/TidyFastChecks.inc
@@ -7,371 +7,437 @@
 #define SLOW(CHECK, DELTA)
 #endif
 
-FAST(abseil-cleanup-ctad, -1.0)
+FAST(abseil-cleanup-ctad, -2.0)
 FAST(abseil-duration-addition, 0.0)
-FAST(abseil-duration-comparison, 1.0)
-FAST(abseil-duration-conversion-cast, 3.0)
-FAST(abseil-duration-division, -0.0)
-FAST(abseil-duration-factory-float, 1.0)
-FAST(abseil-duration-factory-scale, -0.0)
-FAST(abseil-duration-subtraction, 1.0)
-FAST(abseil-duration-unnecessary-conversion, 4.0)
-FAST(abseil-faster-strsplit-delimiter, 2.0)
-FAST(abseil-no-internal-dependencies, -1.0)
-FAST(abseil-no-namespace, -1.0)
-FAST(abseil-redundant-strcat-calls, 2.0)
-FAST(abseil-str-cat-append, 1.0)
-FAST(abseil-string-find-startswith, 1.0)
-FAST(abseil-string-find-str-contains, 1.0)
-FAST(abseil-time-comparison, -0.0)
-FAST(abseil-time-subtraction, 0.0)
+FAST(abseil-duration-comparison, -1.0)
+FAST(abseil-duration-conversion-cast, -1.0)
+FAST(abseil-duration-division, 0.0)
+FAST(abseil-duration-factory-float, 2.0)
+FAST(abseil-duration-factory-scale, 1.0)
+FAST(abseil-duration-subtraction, -1.0)
+FAST(abseil-duration-unnecessary-conversion, -0.0)
+FAST(abseil-faster-strsplit-delimiter, 3.0)
+FAST(abseil-no-internal-dependencies, 1.0)
+FAST(abseil-no-namespace, -0.0)
+FAST(abseil-redundant-strcat-calls, 1.0)
+FAST(abseil-str-cat-append, -0.0)
+FAST(abseil-string-find-startswith, -1.0)
+FAST(abseil-string-find-str-contains, 4.0)
+FAST(abseil-time-comparison, -1.0)
+FAST(abseil-time-subtraction, 1.0)
 FAST(abseil-upgrade-duration-conversions, 2.0)
 SLOW(altera-id-dependent-backward-branch, 13.0)
-FAST(altera-kernel-name-restriction, -1.0)
-FAST(altera-single-work-item-barrier, -1.0)
-FAST(altera-struct-pack-align, -1.0)
+FAST(altera-kernel-name-restriction, 4.0)
+FAST(altera-single-work-item-barrier, 1.0)
+FAST(altera-struct-pack-align, -0.0)
 FAST(altera-unroll-loops, 2.0)
-FAST(android-cloexec-accept, -1.0)
-FAST(android-cloexec-accept4, 3.0)
-FAST(android-cloexec-creat, 0.0)
-FAST(android-cloexec-dup, 3.0)
-FAST(android-cloexec-epoll-create, -2.0)
-FAST(android-cloexec-epoll-create1, -1.0)
-FAST(android-cloexec-fopen, -0.0)
-FAST(android-cloexec-inotify-init, 1.0)
-FAST(android-cloexec-inotify-init1, 2.0)
-FAST(android-cloexec-memfd-create, 2.0)
-FAST(android-cloexec-open, -1.0)
-FAST(android-cloexec-pipe, -1.0)
+FAST(android-cloexec-accept, 0.0)
+FAST(android-cloexec-accept4, 1.0)
+FAST(android-cloexec-creat, 1.0)
+FAST(android-cloexec-dup, 0.0)
+FAST(android-cloexec-epoll-create, 2.0)
+FAST(android-cloexec-epoll-create1, 0.0)
+FAST(android-cloexec-fopen, -1.0)
+FAST(android-cloexec-inotify-init, 2.0)
+FAST(android-cloexec-inotify-init1, -0.0)
+FAST(android-cloexec-memfd-create, -1.0)
+FAST(android-cloexec-open, 1.0)
+FAST(android-cloexec-pipe, -0.0)
 FAST(android-cloexec-pipe2, 0.0)
 FAST(android-cloexec-socket, 1.0)
-FAST(android-comparison-in-temp-failure-retry, 0.0)
-FAST(boost-use-to-string, 1.0)
-FAST(bugprone-argument-comment, 2.0)
+FAST(android-comparison-in-temp-failure-retry, 1.0)
+FAST(boost-use-ranges, 2.0)
+FAST(boost-use-to-string, 2.0)
+FAST(bugprone-argument-comment, 4.0)
 FAST(bugprone-assert-side-effect, 1.0)
-FAST(bugprone-assignment-in-if-condition, -0.0)
-FAST(bugprone-bad-signal-to-kill-thread, -1.0)
+FAST(bugprone-assignment-in-if-condition, 2.0)
+FAST(bugprone-bad-signal-to-kill-thread, 1.0)
 FAST(bugprone-bool-pointer-implicit-conversion, 0.0)
-FAST(bugprone-branch-clone, -0.0)
+FAST(bugprone-branch-clone, 1.0)
+FAST(bugprone-casting-through-void, 1.0)
+FAST(bugprone-chained-comparison, 1.0)
+FAST(bugprone-compare-pointer-to-member-virtual-function, -0.0)
 FAST(bugprone-copy-constructor-init, 1.0)
-FAST(bugprone-dangling-handle, 0.0)
-FAST(bugprone-dynamic-static-initializers, 1.0)
+FAST(bugprone-crtp-constructor-accessibility, 0.0)
+FAST(bugprone-dangling-handle, -0.0)
+FAST(bugprone-dynamic-static-initializers, 0.0)
 FAST(bugprone-easily-swappable-parameters, 2.0)
-FAST(bugprone-exception-escape,

[clang-tools-extra] [clangd] Update TidyFastChecks for release/19.x (PR #106354)

2024-08-28 Thread via cfe-commits

llvmbot wrote:




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

Author: kadir çetinkaya (kadircet)


Changes

Run for clang-tidy checks available in release/19.x branch.

Some notable findings:
- altera-id-dependent-backward-branch, stays slow with 13%.
- misc-const-correctness become faster, going from 261% to 67%, but still above
  8% threshold.
- misc-header-include-cycle is a new SLOW check with 10% runtime implications
- readability-container-size-empty went from 16% to 13%, still SLOW.


---

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


1 Files Affected:

- (modified) clang-tools-extra/clangd/TidyFastChecks.inc (+368-302) 


``diff
diff --git a/clang-tools-extra/clangd/TidyFastChecks.inc 
b/clang-tools-extra/clangd/TidyFastChecks.inc
index 9050ce16127ff4..b1e1bf05172daa 100644
--- a/clang-tools-extra/clangd/TidyFastChecks.inc
+++ b/clang-tools-extra/clangd/TidyFastChecks.inc
@@ -7,371 +7,437 @@
 #define SLOW(CHECK, DELTA)
 #endif
 
-FAST(abseil-cleanup-ctad, -1.0)
+FAST(abseil-cleanup-ctad, -2.0)
 FAST(abseil-duration-addition, 0.0)
-FAST(abseil-duration-comparison, 1.0)
-FAST(abseil-duration-conversion-cast, 3.0)
-FAST(abseil-duration-division, -0.0)
-FAST(abseil-duration-factory-float, 1.0)
-FAST(abseil-duration-factory-scale, -0.0)
-FAST(abseil-duration-subtraction, 1.0)
-FAST(abseil-duration-unnecessary-conversion, 4.0)
-FAST(abseil-faster-strsplit-delimiter, 2.0)
-FAST(abseil-no-internal-dependencies, -1.0)
-FAST(abseil-no-namespace, -1.0)
-FAST(abseil-redundant-strcat-calls, 2.0)
-FAST(abseil-str-cat-append, 1.0)
-FAST(abseil-string-find-startswith, 1.0)
-FAST(abseil-string-find-str-contains, 1.0)
-FAST(abseil-time-comparison, -0.0)
-FAST(abseil-time-subtraction, 0.0)
+FAST(abseil-duration-comparison, -1.0)
+FAST(abseil-duration-conversion-cast, -1.0)
+FAST(abseil-duration-division, 0.0)
+FAST(abseil-duration-factory-float, 2.0)
+FAST(abseil-duration-factory-scale, 1.0)
+FAST(abseil-duration-subtraction, -1.0)
+FAST(abseil-duration-unnecessary-conversion, -0.0)
+FAST(abseil-faster-strsplit-delimiter, 3.0)
+FAST(abseil-no-internal-dependencies, 1.0)
+FAST(abseil-no-namespace, -0.0)
+FAST(abseil-redundant-strcat-calls, 1.0)
+FAST(abseil-str-cat-append, -0.0)
+FAST(abseil-string-find-startswith, -1.0)
+FAST(abseil-string-find-str-contains, 4.0)
+FAST(abseil-time-comparison, -1.0)
+FAST(abseil-time-subtraction, 1.0)
 FAST(abseil-upgrade-duration-conversions, 2.0)
 SLOW(altera-id-dependent-backward-branch, 13.0)
-FAST(altera-kernel-name-restriction, -1.0)
-FAST(altera-single-work-item-barrier, -1.0)
-FAST(altera-struct-pack-align, -1.0)
+FAST(altera-kernel-name-restriction, 4.0)
+FAST(altera-single-work-item-barrier, 1.0)
+FAST(altera-struct-pack-align, -0.0)
 FAST(altera-unroll-loops, 2.0)
-FAST(android-cloexec-accept, -1.0)
-FAST(android-cloexec-accept4, 3.0)
-FAST(android-cloexec-creat, 0.0)
-FAST(android-cloexec-dup, 3.0)
-FAST(android-cloexec-epoll-create, -2.0)
-FAST(android-cloexec-epoll-create1, -1.0)
-FAST(android-cloexec-fopen, -0.0)
-FAST(android-cloexec-inotify-init, 1.0)
-FAST(android-cloexec-inotify-init1, 2.0)
-FAST(android-cloexec-memfd-create, 2.0)
-FAST(android-cloexec-open, -1.0)
-FAST(android-cloexec-pipe, -1.0)
+FAST(android-cloexec-accept, 0.0)
+FAST(android-cloexec-accept4, 1.0)
+FAST(android-cloexec-creat, 1.0)
+FAST(android-cloexec-dup, 0.0)
+FAST(android-cloexec-epoll-create, 2.0)
+FAST(android-cloexec-epoll-create1, 0.0)
+FAST(android-cloexec-fopen, -1.0)
+FAST(android-cloexec-inotify-init, 2.0)
+FAST(android-cloexec-inotify-init1, -0.0)
+FAST(android-cloexec-memfd-create, -1.0)
+FAST(android-cloexec-open, 1.0)
+FAST(android-cloexec-pipe, -0.0)
 FAST(android-cloexec-pipe2, 0.0)
 FAST(android-cloexec-socket, 1.0)
-FAST(android-comparison-in-temp-failure-retry, 0.0)
-FAST(boost-use-to-string, 1.0)
-FAST(bugprone-argument-comment, 2.0)
+FAST(android-comparison-in-temp-failure-retry, 1.0)
+FAST(boost-use-ranges, 2.0)
+FAST(boost-use-to-string, 2.0)
+FAST(bugprone-argument-comment, 4.0)
 FAST(bugprone-assert-side-effect, 1.0)
-FAST(bugprone-assignment-in-if-condition, -0.0)
-FAST(bugprone-bad-signal-to-kill-thread, -1.0)
+FAST(bugprone-assignment-in-if-condition, 2.0)
+FAST(bugprone-bad-signal-to-kill-thread, 1.0)
 FAST(bugprone-bool-pointer-implicit-conversion, 0.0)
-FAST(bugprone-branch-clone, -0.0)
+FAST(bugprone-branch-clone, 1.0)
+FAST(bugprone-casting-through-void, 1.0)
+FAST(bugprone-chained-comparison, 1.0)
+FAST(bugprone-compare-pointer-to-member-virtual-function, -0.0)
 FAST(bugprone-copy-constructor-init, 1.0)
-FAST(bugprone-dangling-handle, 0.0)
-FAST(bugprone-dynamic-static-initializers, 1.0)
+FAST(bugprone-crtp-constructor-accessibility, 0.0)
+FAST(bugprone-dangling-handle, -0.0)
+FAST(bugprone-dynamic-static-initializers, 0.0)
 FAST(bugprone-easily-swappable-parameters, 2.0)
-FAST(bugprone-exception-escape, 1.0)
-FAST(bugprone-fold-init-type, 2.0)
+FAST(bugprone-empty-catch, 1.0)
+FAS

[clang-tools-extra] [clangd] Update TidyFastChecks for release/19.x (PR #106354)

2024-08-28 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 22e55ba3293f72df84de509db821b4d8a2c4c55e 
38df7489ff2fa15a5bc7fc66d18ef78b489cd9d8 --extensions inc -- 
clang-tools-extra/clangd/TidyFastChecks.inc
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clangd/TidyFastChecks.inc 
b/clang-tools-extra/clangd/TidyFastChecks.inc
index b1e1bf0517..d992dbb6c1 100644
--- a/clang-tools-extra/clangd/TidyFastChecks.inc
+++ b/clang-tools-extra/clangd/TidyFastChecks.inc
@@ -7,437 +7,436 @@
 #define SLOW(CHECK, DELTA)
 #endif
 
-FAST(abseil-cleanup-ctad, -2.0)
+FAST(abseil - cleanup - ctad, -2.0)
 FAST(abseil-duration-addition, 0.0)
-FAST(abseil-duration-comparison, -1.0)
-FAST(abseil-duration-conversion-cast, -1.0)
-FAST(abseil-duration-division, 0.0)
-FAST(abseil-duration-factory-float, 2.0)
-FAST(abseil-duration-factory-scale, 1.0)
-FAST(abseil-duration-subtraction, -1.0)
-FAST(abseil-duration-unnecessary-conversion, -0.0)
-FAST(abseil-faster-strsplit-delimiter, 3.0)
-FAST(abseil-no-internal-dependencies, 1.0)
-FAST(abseil-no-namespace, -0.0)
-FAST(abseil-redundant-strcat-calls, 1.0)
-FAST(abseil-str-cat-append, -0.0)
-FAST(abseil-string-find-startswith, -1.0)
-FAST(abseil-string-find-str-contains, 4.0)
-FAST(abseil-time-comparison, -1.0)
-FAST(abseil-time-subtraction, 1.0)
+FAST(abseil - duration - comparison, -1.0)
+FAST(abseil - duration - conversion - cast, -1.0)
+FAST(abseil - duration - division, 0.0)
+FAST(abseil - duration - factory - float, 2.0)
+FAST(abseil - duration - factory - scale, 1.0)
+FAST(abseil - duration - subtraction, -1.0)
+FAST(abseil - duration - unnecessary - conversion, -0.0)
+FAST(abseil - faster - strsplit - delimiter, 3.0)
+FAST(abseil - no - internal - dependencies, 1.0)
+FAST(abseil - no - namespace, -0.0)
+FAST(abseil - redundant - strcat - calls, 1.0)
+FAST(abseil - str - cat - append, -0.0)
+FAST(abseil - string - find - startswith, -1.0)
+FAST(abseil - string - find - str - contains, 4.0)
+FAST(abseil - time - comparison, -1.0)
+FAST(abseil - time - subtraction, 1.0)
 FAST(abseil-upgrade-duration-conversions, 2.0)
 SLOW(altera-id-dependent-backward-branch, 13.0)
-FAST(altera-kernel-name-restriction, 4.0)
-FAST(altera-single-work-item-barrier, 1.0)
-FAST(altera-struct-pack-align, -0.0)
+FAST(altera - kernel - name - restriction, 4.0)
+FAST(altera - single - work - item - barrier, 1.0)
+FAST(altera - struct - pack - align, -0.0)
 FAST(altera-unroll-loops, 2.0)
-FAST(android-cloexec-accept, 0.0)
-FAST(android-cloexec-accept4, 1.0)
-FAST(android-cloexec-creat, 1.0)
-FAST(android-cloexec-dup, 0.0)
-FAST(android-cloexec-epoll-create, 2.0)
-FAST(android-cloexec-epoll-create1, 0.0)
-FAST(android-cloexec-fopen, -1.0)
-FAST(android-cloexec-inotify-init, 2.0)
-FAST(android-cloexec-inotify-init1, -0.0)
-FAST(android-cloexec-memfd-create, -1.0)
-FAST(android-cloexec-open, 1.0)
-FAST(android-cloexec-pipe, -0.0)
+FAST(android - cloexec - accept, 0.0)
+FAST(android - cloexec - accept4, 1.0)
+FAST(android - cloexec - creat, 1.0)
+FAST(android - cloexec - dup, 0.0)
+FAST(android - cloexec - epoll - create, 2.0)
+FAST(android - cloexec - epoll - create1, 0.0)
+FAST(android - cloexec - fopen, -1.0)
+FAST(android - cloexec - inotify - init, 2.0)
+FAST(android - cloexec - inotify - init1, -0.0)
+FAST(android - cloexec - memfd - create, -1.0)
+FAST(android - cloexec - open, 1.0)
+FAST(android - cloexec - pipe, -0.0)
 FAST(android-cloexec-pipe2, 0.0)
 FAST(android-cloexec-socket, 1.0)
-FAST(android-comparison-in-temp-failure-retry, 1.0)
-FAST(boost-use-ranges, 2.0)
-FAST(boost-use-to-string, 2.0)
-FAST(bugprone-argument-comment, 4.0)
+FAST(android - comparison - in - temp - failure - retry, 1.0)
+FAST(boost - use - ranges, 2.0)
+FAST(boost - use - to - string, 2.0)
+FAST(bugprone - argument - comment, 4.0)
 FAST(bugprone-assert-side-effect, 1.0)
-FAST(bugprone-assignment-in-if-condition, 2.0)
-FAST(bugprone-bad-signal-to-kill-thread, 1.0)
+FAST(bugprone - assignment - in - if - condition, 2.0)
+FAST(bugprone - bad - signal - to - kill - thread, 1.0)
 FAST(bugprone-bool-pointer-implicit-conversion, 0.0)
-FAST(bugprone-branch-clone, 1.0)
-FAST(bugprone-casting-through-void, 1.0)
-FAST(bugprone-chained-comparison, 1.0)
-FAST(bugprone-compare-pointer-to-member-virtual-function, -0.0)
+FAST(bugprone - branch - clone, 1.0)
+FAST(bugprone - casting - through - void, 1.0)
+FAST(bugprone - chained - comparison, 1.0)
+FAST(bugprone - compare - pointer - to - member - virtual - function, -0.0)
 FAST(bugprone-copy-constructor-init, 1.0)
-FAST(bugprone-crtp-constructor-accessibility, 0.0)
-FAST(bugprone-dangling-handle, -0.0)
-FAST(bugprone-dynamic-static-initializers, 0.0)
+FAST(bugprone - crtp - constructor - accessibility, 0.0)
+FAST(bugprone - dangling - handle, -0.0)
+FAST(bugprone - dynamic - static - init

[clang-tools-extra] [clangd] Update TidyFastChecks for release/19.x (PR #106354)

2024-08-28 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/106354

From c2248b8f0b6255774c7cf2aa80e7330696fd9c40 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 28 Aug 2024 11:27:47 +0200
Subject: [PATCH] [clangd] Update TidyFastChecks for release/19.x

Run for clang-tidy checks available in release/19.x branch.

Some notable findings:
- altera-id-dependent-backward-branch, stays slow with 13%.
- misc-const-correctness become faster, going from 261% to 67%, but still above
  8% threshold.
- misc-header-include-cycle is a new SLOW check with 10% runtime implications
- readability-container-size-empty went from 16% to 13%, still SLOW.
---
 clang-tools-extra/clangd/TidyFastChecks.inc | 669 +++-
 1 file changed, 367 insertions(+), 302 deletions(-)

diff --git a/clang-tools-extra/clangd/TidyFastChecks.inc 
b/clang-tools-extra/clangd/TidyFastChecks.inc
index 9050ce16127ff4..de1a025602fa9c 100644
--- a/clang-tools-extra/clangd/TidyFastChecks.inc
+++ b/clang-tools-extra/clangd/TidyFastChecks.inc
@@ -7,370 +7,435 @@
 #define SLOW(CHECK, DELTA)
 #endif
 
-FAST(abseil-cleanup-ctad, -1.0)
+FAST(abseil-cleanup-ctad, -2.0)
 FAST(abseil-duration-addition, 0.0)
-FAST(abseil-duration-comparison, 1.0)
-FAST(abseil-duration-conversion-cast, 3.0)
-FAST(abseil-duration-division, -0.0)
-FAST(abseil-duration-factory-float, 1.0)
-FAST(abseil-duration-factory-scale, -0.0)
-FAST(abseil-duration-subtraction, 1.0)
-FAST(abseil-duration-unnecessary-conversion, 4.0)
-FAST(abseil-faster-strsplit-delimiter, 2.0)
-FAST(abseil-no-internal-dependencies, -1.0)
-FAST(abseil-no-namespace, -1.0)
-FAST(abseil-redundant-strcat-calls, 2.0)
-FAST(abseil-str-cat-append, 1.0)
-FAST(abseil-string-find-startswith, 1.0)
-FAST(abseil-string-find-str-contains, 1.0)
-FAST(abseil-time-comparison, -0.0)
-FAST(abseil-time-subtraction, 0.0)
+FAST(abseil-duration-comparison, -1.0)
+FAST(abseil-duration-conversion-cast, -1.0)
+FAST(abseil-duration-division, 0.0)
+FAST(abseil-duration-factory-float, 2.0)
+FAST(abseil-duration-factory-scale, 1.0)
+FAST(abseil-duration-subtraction, -1.0)
+FAST(abseil-duration-unnecessary-conversion, -0.0)
+FAST(abseil-faster-strsplit-delimiter, 3.0)
+FAST(abseil-no-internal-dependencies, 1.0)
+FAST(abseil-no-namespace, -0.0)
+FAST(abseil-redundant-strcat-calls, 1.0)
+FAST(abseil-str-cat-append, -0.0)
+FAST(abseil-string-find-startswith, -1.0)
+FAST(abseil-string-find-str-contains, 4.0)
+FAST(abseil-time-comparison, -1.0)
+FAST(abseil-time-subtraction, 1.0)
 FAST(abseil-upgrade-duration-conversions, 2.0)
 SLOW(altera-id-dependent-backward-branch, 13.0)
-FAST(altera-kernel-name-restriction, -1.0)
-FAST(altera-single-work-item-barrier, -1.0)
-FAST(altera-struct-pack-align, -1.0)
+FAST(altera-kernel-name-restriction, 4.0)
+FAST(altera-single-work-item-barrier, 1.0)
+FAST(altera-struct-pack-align, -0.0)
 FAST(altera-unroll-loops, 2.0)
-FAST(android-cloexec-accept, -1.0)
-FAST(android-cloexec-accept4, 3.0)
-FAST(android-cloexec-creat, 0.0)
-FAST(android-cloexec-dup, 3.0)
-FAST(android-cloexec-epoll-create, -2.0)
-FAST(android-cloexec-epoll-create1, -1.0)
-FAST(android-cloexec-fopen, -0.0)
-FAST(android-cloexec-inotify-init, 1.0)
-FAST(android-cloexec-inotify-init1, 2.0)
-FAST(android-cloexec-memfd-create, 2.0)
-FAST(android-cloexec-open, -1.0)
-FAST(android-cloexec-pipe, -1.0)
+FAST(android-cloexec-accept, 0.0)
+FAST(android-cloexec-accept4, 1.0)
+FAST(android-cloexec-creat, 1.0)
+FAST(android-cloexec-dup, 0.0)
+FAST(android-cloexec-epoll-create, 2.0)
+FAST(android-cloexec-epoll-create1, 0.0)
+FAST(android-cloexec-fopen, -1.0)
+FAST(android-cloexec-inotify-init, 2.0)
+FAST(android-cloexec-inotify-init1, -0.0)
+FAST(android-cloexec-memfd-create, -1.0)
+FAST(android-cloexec-open, 1.0)
+FAST(android-cloexec-pipe, -0.0)
 FAST(android-cloexec-pipe2, 0.0)
 FAST(android-cloexec-socket, 1.0)
-FAST(android-comparison-in-temp-failure-retry, 0.0)
-FAST(boost-use-to-string, 1.0)
-FAST(bugprone-argument-comment, 2.0)
+FAST(android-comparison-in-temp-failure-retry, 1.0)
+FAST(boost-use-ranges, 2.0)
+FAST(boost-use-to-string, 2.0)
+FAST(bugprone-argument-comment, 4.0)
 FAST(bugprone-assert-side-effect, 1.0)
-FAST(bugprone-assignment-in-if-condition, -0.0)
-FAST(bugprone-bad-signal-to-kill-thread, -1.0)
+FAST(bugprone-assignment-in-if-condition, 2.0)
+FAST(bugprone-bad-signal-to-kill-thread, 1.0)
 FAST(bugprone-bool-pointer-implicit-conversion, 0.0)
-FAST(bugprone-branch-clone, -0.0)
+FAST(bugprone-branch-clone, 1.0)
+FAST(bugprone-casting-through-void, 1.0)
+FAST(bugprone-chained-comparison, 1.0)
+FAST(bugprone-compare-pointer-to-member-virtual-function, -0.0)
 FAST(bugprone-copy-constructor-init, 1.0)
-FAST(bugprone-dangling-handle, 0.0)
-FAST(bugprone-dynamic-static-initializers, 1.0)
+FAST(bugprone-crtp-constructor-accessibility, 0.0)
+FAST(bugprone-dangling-handle, -0.0)
+FAST(bugprone-dynamic-static-initializers, 0.0)
 FAST(bugprone-easily-swappable-parameters, 2.0)
-FAST(bugprone-exception-escape, 1

[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread via cfe-commits

https://github.com/cor3ntin commented:

Can you also add a changelog entry?
Thanks!

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread via cfe-commits

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread via cfe-commits


@@ -1604,10 +1604,12 @@ static bool isTargetVariantEnvironment(const TargetInfo 
&TI,
   return false;
 }
 
-#if defined(__sun__) && defined(__svr4__)
+#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && 
\
+__clang__ < 20

cor3ntin wrote:

Does every version of gcc we support handles that?

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread via cfe-commits


@@ -6953,6 +6954,27 @@ bool CXXNameMangler::mangleStandardSubstitution(const 
NamedDecl *ND) {
 return false;
   }
 
+  if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
+if (const RecordDecl *RD = dyn_cast(ND)) {
+  if (!isStdNamespace(Context.getEffectiveDeclContext(RD)))
+return false;
+
+  // Issue #33114: Need non-standard mangling of std::tm etc. for
+  // Solaris ABI compatibility.
+  static std::set types{"div_t", "ldiv_t", "lconv", "tm"};
+
+  //  ::= tm # ::std::tm, same for the others
+  if (const IdentifierInfo *II = RD->getIdentifier()) {
+StringRef type = II->getName();
+if (types.count(type)) {

cor3ntin wrote:

```suggestion
if (llvm::is_contained({"div_t", "ldiv_t", "lconv", "tm"}, type)) {
```

using a std::set is a bit overkill here


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


[clang] [llvm] [AArch64] Make apple-m4 armv8.7-a again (from armv9.2-a). (PR #106312)

2024-08-28 Thread Tomas Matheson via cfe-commits


@@ -895,7 +895,10 @@ def ProcessorFeatures {
  FeatureLSE, FeaturePAuth, FeatureFPAC,
  FeatureRAS, FeatureRCPC, FeatureRDM,
  FeatureBF16, FeatureDotProd, 
FeatureMatMulInt8, FeatureSSBS];
-  list AppleM4 = [HasV9_2aOps, FeatureSHA2, FeatureFPARMv8,
+  // Technically apple-m4 is ARMv9.2a, but a quirk of LLVM defines v9.0 as
+  // requiring SVE, which is optional according to the Arm ARM and not
+  // supported by the core. ARMv8.7a is the next closest choice.

tmatheson-arm wrote:

Please update the comment to explain the "quirk". I think what you mean is that 
clang will still add all of the architecture default features when you are 
selecting a particular CPU, even if the backend wouldn't add them.

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


[clang] [clang] Update C++ DR page (PR #106299)

2024-08-28 Thread via cfe-commits


@@ -33,7 +33,7 @@ void *operator new(std::size_t, void *p) { return p; }
 void* operator new[] (std::size_t, void* p) {return p;}
 
 
-namespace cwg2922 { // cwg2922: 20 open 2024-07-10
+namespace cwg2922 { // cwg2922: 20 tentatively ready 2024-07-10

cor3ntin wrote:

Yes! Thanks

https://github.com/llvm/llvm-project/pull/106299
___
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 user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-08-28 Thread via cfe-commits


@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"

whisperity wrote:

(This include is superfluous, ClangTidyCheck automatically pulls the related 
header in. Yes, I'm always burnt by clangd with this as well. :wink:)

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread Rainer Orth via cfe-commits


@@ -1604,10 +1604,12 @@ static bool isTargetVariantEnvironment(const TargetInfo 
&TI,
   return false;
 }
 
-#if defined(__sun__) && defined(__svr4__)
+#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && 
\
+__clang__ < 20

rorth wrote:

Certainly: the fix for GCC PR libstdc++-v3/1773 went in 13 years ago.  That 
should be good enough ;-)

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


[clang] [clang] Add lifetimebound attr to std::span/std::string_view constructor (PR #103716)

2024-08-28 Thread Nikita Popov via cfe-commits

nikic wrote:

Just as a FYI this inference introduces a small amount of overhead: 
http://llvm-compile-time-tracker.com/compare.php?from=866bec7d3ff8803b68e9972939c1a76ccf5fdc62&to=902b2a26ab9e1e78dfb66b52fba4512c91472e09&stat=instructions:u

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread Rainer Orth via cfe-commits


@@ -6953,6 +6954,27 @@ bool CXXNameMangler::mangleStandardSubstitution(const 
NamedDecl *ND) {
 return false;
   }
 
+  if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
+if (const RecordDecl *RD = dyn_cast(ND)) {
+  if (!isStdNamespace(Context.getEffectiveDeclContext(RD)))
+return false;
+
+  // Issue #33114: Need non-standard mangling of std::tm etc. for
+  // Solaris ABI compatibility.
+  static std::set types{"div_t", "ldiv_t", "lconv", "tm"};
+
+  //  ::= tm # ::std::tm, same for the others
+  if (const IdentifierInfo *II = RD->getIdentifier()) {
+StringRef type = II->getName();
+if (types.count(type)) {

rorth wrote:

Will do: I'm pretty ignorant of C++ actually...

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


[clang] [WIP][clang] Fix std::tm etc. mangling on Solaris (PR #106353)

2024-08-28 Thread Rainer Orth via cfe-commits

rorth wrote:

> Can you also add a changelog entry? Thanks!

I've never seen them used in LLVM.  Has that changed recently?

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


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

2024-08-28 Thread Younan Zhang via cfe-commits

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

>From 1119f0a8d180e482bff45c999d488827ac5ae49e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 12 Aug 2024 23:32:34 +0800
Subject: [PATCH 01/13] [Clang][NFCI] Slightly refactor
 getTemplateInstantiationArgs()

---
 clang/include/clang/Sema/Sema.h| 12 +---
 clang/lib/Sema/SemaConcept.cpp |  2 +-
 clang/lib/Sema/SemaTemplate.cpp|  2 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 15 +++
 4 files changed, 18 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..352b26b0739ffb 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13033,11 +13033,14 @@ class Sema final : public SemaBase {
   /// instantiation arguments.
   ///
   /// \param DC In the event we don't HAVE a declaration yet, we instead 
provide
-  ///  the decl context where it will be created.  In this case, the 
`Innermost`
-  ///  should likely be provided.  If ND is non-null, this is ignored.
+  ///  the decl context where it will be created.  In this case, the \p
+  ///  Innermost should likely be provided.  If \p ND is non-null and \p
+  ///  Innermost is NULL, this is ignored.
   ///
   /// \param Innermost if non-NULL, specifies a template argument list for the
-  /// template declaration passed as ND.
+  /// template declaration passed as \p ND. The next declaration context would
+  /// be switched to \p DC if present; otherwise, it would be the semantic
+  /// declaration context of \p ND.
   ///
   /// \param RelativeToPrimary true if we should get the template
   /// arguments relative to the primary template, even when we're
@@ -13053,6 +13056,9 @@ class Sema final : public SemaBase {
   /// ForConstraintInstantiation indicates we should continue looking when
   /// encountering a lambda generic call operator, and continue looking for
   /// arguments on an enclosing class template.
+  ///
+  /// \param SkipForSpecialization when specified, any template specializations
+  /// in a traversal would be ignored.
   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
   const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
   std::optional> Innermost = std::nullopt,
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..929555e94dc35d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -1482,7 +1482,7 @@ substituteParameterMappings(Sema &S, NormalizedConstraint 
&N,
 static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
 const ConceptSpecializationExpr *CSE) {
   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  CSE->getNamedConcept(), CSE->getNamedConcept()->getLexicalDeclContext(),
+  CSE->getNamedConcept(), CSE->getNamedConcept()->getDeclContext(),
   /*Final=*/true, CSE->getTemplateArguments(),
   /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1346a4a3f0012a..e6191c8c1397bd 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5582,7 +5582,7 @@ bool Sema::CheckTemplateArgumentList(
 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
 
 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
-Template, NewContext, /*Final=*/true, SugaredConverted,
+Template, Template->getDeclContext(), /*Final=*/true, SugaredConverted,
 /*RelativeToPrimary=*/true,
 /*Pattern=*/nullptr,
 /*ForConceptInstantiation=*/true);
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index de470739ab78e7..6cc9fb0ef04b65 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -491,7 +491,8 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 // has a depth of 0.
 if (const auto *TTP = dyn_cast(CurDecl))
   HandleDefaultTempArgIntoTempTempParam(TTP, Result);
-CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
+CurDecl = DC ? Decl::castFromDeclContext(DC)
+ : Response::UseNextDecl(CurDecl).NextDecl;
   }
 
   while (!CurDecl->isFileContextDecl()) {
@@ -3242,15 +3243,13 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
-  const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
-  if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
-TemplateArgumentList *CurrentTemplateArgumentList =
-TemplateArgumentList::CreateCopy(getASTContext(),
- TemplateArg

[clang] [llvm] Added instant events and marking defered templated instantiation. (PR #103039)

2024-08-28 Thread via cfe-commits

https://github.com/ivanaivanovska updated 
https://github.com/llvm/llvm-project/pull/103039

>From 1294a50b0da22e2904d3e43942a6be702c93d133 Mon Sep 17 00:00:00 2001
From: Ivana Ivanovska 
Date: Tue, 13 Aug 2024 10:30:34 +
Subject: [PATCH 1/2] Added instant events and marking defered templated
 instantiation.

---
 clang/lib/Sema/SemaExpr.cpp   | 18 ++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 17 +
 clang/unittests/Support/TimeProfilerTest.cpp  | 51 ++-
 llvm/include/llvm/Support/TimeProfiler.h  | 19 +-
 llvm/lib/Support/TimeProfiler.cpp | 64 +--
 5 files changed, 145 insertions(+), 24 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 74c0e017059055..adc021c8cd237b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18,6 +18,7 @@
 #include "clang/AST/ASTLambda.h"
 #include "clang/AST/ASTMutationListener.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
@@ -63,6 +64,7 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/SaveAndRestore.h"
+#include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/TypeSize.h"
 #include 
 
@@ -18013,6 +18015,22 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
 std::make_pair(Func, PointOfInstantiation));
 // Notify the consumer that a function was implicitly instantiated.
 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
+
+llvm::TimeTraceScope TimeScope(
+"DeferInstantiation",
+[&]() {
+  llvm::TimeTraceMetadata M;
+  llvm::raw_string_ostream OS(M.Detail);
+  Func->getNameForDiagnostic(OS, getPrintingPolicy(),
+ /*Qualified=*/true);
+  if (llvm::isTimeTraceVerbose()) {
+auto Loc = SourceMgr.getExpansionLoc(Func->getLocation());
+M.File = SourceMgr.getFilename(Loc);
+M.Line = SourceMgr.getExpansionLineNumber(Loc);
+  }
+  return M;
+},
+llvm::TimeTraceEventType::InstantEvent);
   }
 }
   } else {
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index f93cd113988ae4..d6d580d399457d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4941,6 +4941,23 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
   Function->setInstantiationIsPending(true);
   PendingInstantiations.push_back(
 std::make_pair(Function, PointOfInstantiation));
+
+  llvm::TimeTraceScope TimeScope(
+  "DeferInstantiation",
+  [&]() {
+llvm::TimeTraceMetadata M;
+llvm::raw_string_ostream OS(M.Detail);
+Function->getNameForDiagnostic(OS, getPrintingPolicy(),
+   /*Qualified=*/true);
+if (llvm::isTimeTraceVerbose()) {
+  auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
+  M.File = SourceMgr.getFilename(Loc);
+  M.Line = SourceMgr.getExpansionLineNumber(Loc);
+}
+return M;
+  },
+  llvm::TimeTraceEventType::InstantEvent);
+
 } else if (TSK == TSK_ImplicitInstantiation) {
   if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
   !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
diff --git a/clang/unittests/Support/TimeProfilerTest.cpp 
b/clang/unittests/Support/TimeProfilerTest.cpp
index f53fe71d630bf5..ccda12e943dd73 100644
--- a/clang/unittests/Support/TimeProfilerTest.cpp
+++ b/clang/unittests/Support/TimeProfilerTest.cpp
@@ -238,13 +238,55 @@ Frontend (test.cc)
 buildTraceGraph(Json));
 }
 
+TEST(TimeProfilerTest, ClassTemplateInstantiations) {
+  std::string Code = R"(
+template
+struct S
+{
+  void foo() {}
+  void bar();
+};
+
+template struct S; // explicit instantiation of S
+
+void user() {
+  S a; // implicit instantiation of S
+  S* b;
+  b->foo(); // implicit instatiation of S and S::foo()
+}
+  )";
+
+  setupProfiler();
+  ASSERT_TRUE(compileFromString(Code, "-std=c++20", "test.cc"));
+  std::string Json = teardownProfiler();
+  ASSERT_EQ(R"(
+Frontend (test.cc)
+| ParseClass (S)
+| InstantiateClass (S, test.cc:9)
+| InstantiateFunction (S::foo, test.cc:5)
+| ParseDeclarationOrFunctionDefinition (test.cc:11:5)
+| | ParseFunctionDefinition (user)
+| | | InstantiateClass (S, test.cc:3)
+| | | InstantiateClass (S, test.cc:3)
+| | | DeferInstantiatio

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

2024-08-28 Thread Younan Zhang via cfe-commits

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

>From 1119f0a8d180e482bff45c999d488827ac5ae49e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 12 Aug 2024 23:32:34 +0800
Subject: [PATCH 01/14] [Clang][NFCI] Slightly refactor
 getTemplateInstantiationArgs()

---
 clang/include/clang/Sema/Sema.h| 12 +---
 clang/lib/Sema/SemaConcept.cpp |  2 +-
 clang/lib/Sema/SemaTemplate.cpp|  2 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 15 +++
 4 files changed, 18 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..352b26b0739ffb 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13033,11 +13033,14 @@ class Sema final : public SemaBase {
   /// instantiation arguments.
   ///
   /// \param DC In the event we don't HAVE a declaration yet, we instead 
provide
-  ///  the decl context where it will be created.  In this case, the 
`Innermost`
-  ///  should likely be provided.  If ND is non-null, this is ignored.
+  ///  the decl context where it will be created.  In this case, the \p
+  ///  Innermost should likely be provided.  If \p ND is non-null and \p
+  ///  Innermost is NULL, this is ignored.
   ///
   /// \param Innermost if non-NULL, specifies a template argument list for the
-  /// template declaration passed as ND.
+  /// template declaration passed as \p ND. The next declaration context would
+  /// be switched to \p DC if present; otherwise, it would be the semantic
+  /// declaration context of \p ND.
   ///
   /// \param RelativeToPrimary true if we should get the template
   /// arguments relative to the primary template, even when we're
@@ -13053,6 +13056,9 @@ class Sema final : public SemaBase {
   /// ForConstraintInstantiation indicates we should continue looking when
   /// encountering a lambda generic call operator, and continue looking for
   /// arguments on an enclosing class template.
+  ///
+  /// \param SkipForSpecialization when specified, any template specializations
+  /// in a traversal would be ignored.
   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
   const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
   std::optional> Innermost = std::nullopt,
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..929555e94dc35d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -1482,7 +1482,7 @@ substituteParameterMappings(Sema &S, NormalizedConstraint 
&N,
 static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
 const ConceptSpecializationExpr *CSE) {
   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  CSE->getNamedConcept(), CSE->getNamedConcept()->getLexicalDeclContext(),
+  CSE->getNamedConcept(), CSE->getNamedConcept()->getDeclContext(),
   /*Final=*/true, CSE->getTemplateArguments(),
   /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1346a4a3f0012a..e6191c8c1397bd 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5582,7 +5582,7 @@ bool Sema::CheckTemplateArgumentList(
 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
 
 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
-Template, NewContext, /*Final=*/true, SugaredConverted,
+Template, Template->getDeclContext(), /*Final=*/true, SugaredConverted,
 /*RelativeToPrimary=*/true,
 /*Pattern=*/nullptr,
 /*ForConceptInstantiation=*/true);
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index de470739ab78e7..6cc9fb0ef04b65 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -491,7 +491,8 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 // has a depth of 0.
 if (const auto *TTP = dyn_cast(CurDecl))
   HandleDefaultTempArgIntoTempTempParam(TTP, Result);
-CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
+CurDecl = DC ? Decl::castFromDeclContext(DC)
+ : Response::UseNextDecl(CurDecl).NextDecl;
   }
 
   while (!CurDecl->isFileContextDecl()) {
@@ -3242,15 +3243,13 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
-  const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
-  if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
-TemplateArgumentList *CurrentTemplateArgumentList =
-TemplateArgumentList::CreateCopy(getASTContext(),
- TemplateArg

[clang] [clang] Update C++ DR page (PR #106299)

2024-08-28 Thread Vlad Serebrennikov via cfe-commits

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


[clang] 9cf052d - [clang] Update C++ DR page (#106299)

2024-08-28 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-08-28T14:01:21+04:00
New Revision: 9cf052df90418697c05810f69c588064f7b3ce71

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

LOG: [clang] Update C++ DR page (#106299)

[CWG2917](https://cplusplus.github.io/CWG/issues/2917.html) got a new
proposed resolution that is different from the one the test has been
written against.

[CWG2922](https://cplusplus.github.io/CWG/issues/2922.html) apparently
the initial "possible resolution" was approved without changes.

Added: 


Modified: 
clang/test/CXX/drs/cwg29xx.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/test/CXX/drs/cwg29xx.cpp b/clang/test/CXX/drs/cwg29xx.cpp
index 2515785f47bf19..ca598bb39a6c31 100644
--- a/clang/test/CXX/drs/cwg29xx.cpp
+++ b/clang/test/CXX/drs/cwg29xx.cpp
@@ -6,7 +6,7 @@
 // RUN: %clang_cc1 -std=c++23 -pedantic-errors -verify=expected %s
 // RUN: %clang_cc1 -std=c++2c -pedantic-errors -verify=expected %s
 
-namespace cwg2917 { // cwg2917: 20 open 2024-07-30
+namespace cwg2917 { // cwg2917: 20 review 2024-07-30
 template 
 class Foo;
 
@@ -33,7 +33,7 @@ void *operator new(std::size_t, void *p) { return p; }
 void* operator new[] (std::size_t, void* p) {return p;}
 
 
-namespace cwg2922 { // cwg2922: 20 open 2024-07-10
+namespace cwg2922 { // cwg2922: 20 tentatively ready 2024-07-10
 union U { int a, b; };
 constexpr U nondeterministic(bool i) {
   if(i) {

diff  --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index 395b5d3bff49a6..124df56bb609c0 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -17208,7 +17208,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2899.html";>2899
-open
+tentatively ready
 Bad value representations should cause undefined behavior
 Not resolved
   
@@ -17220,7 +17220,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2901.html";>2901
-open
+review
 Unclear semantics for near-match aliased access
 Not resolved
   
@@ -17262,7 +17262,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2908.html";>2908
-open
+tentatively ready
 Counting physical source lines for __LINE__
 Not resolved
   
@@ -17292,43 +17292,43 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2913.html";>2913
-open
+tentatively ready
 Grammar for deduction-guide has requires-clause in the 
wrong position
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2914.html";>2914
-open
+review
 Unclear order of initialization of static and thread-local 
variables
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2915.html";>2915
-open
+tentatively ready
 Explicit object parameters of type void
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2916.html";>2916
-open
+tentatively ready
 Variable template partial specializations should not be declared 
static
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2917.html";>2917
-open
+review
 Disallow multiple friend-type-specifiers for a friend 
template
 Not 
Resolved*
   
   
 https://cplusplus.github.io/CWG/issues/2918.html";>2918
-open
+review
 Consideration of constraints for address of overloaded function
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2919.html";>2919
-open
+tentatively ready
 Conversion function candidates for initialization of const lvalue 
reference
 Not resolved
   
@@ -17340,15 +17340,45 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2921.html";>2921
-open
+tentatively ready
 Exporting redeclarations of entities not attached to a named 
module
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2922.html";>2922
-open
+tentatively ready
 constexpr placement-new is too permissive
 Not 
Resolved*
+  
+  
+https://cplusplus.github.io/CWG/issues/2923.html";>2923
+open
+Note about infinite loops and execution steps
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2924.html";>2924
+open
+Undefined behavior during constant evaluation
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2925.html";>2925
+open
+Deleting a pointer to an incomplete enumeration type
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2926.html";>2926
+open
+Lookup context for dependent qualified names
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/is

[clang-tools-extra] [clang-tidy] Add new `bugprone-suspicious-pointer-arithmetics-using-sizeof` (`cert-arr39-c`) check (PR #106061)

2024-08-28 Thread via cfe-commits

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


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

2024-08-28 Thread Vlad Serebrennikov via cfe-commits


@@ -2099,6 +2099,70 @@ class Sema final : public SemaBase {
   bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
  bool OrNull);
 
+  // AssignmentAction - This is used by all the assignment diagnostic functions
+  // to represent what is actually causing the operation
+  enum AssignmentAction {

Endilll wrote:

Ideally you should turn it into scoped enum and move it outside of `Sema` 
definition in a separate NFC patch, then update this PR with those changes.

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


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

2024-08-28 Thread Younan Zhang via cfe-commits

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

>From 1119f0a8d180e482bff45c999d488827ac5ae49e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 12 Aug 2024 23:32:34 +0800
Subject: [PATCH 01/15] [Clang][NFCI] Slightly refactor
 getTemplateInstantiationArgs()

---
 clang/include/clang/Sema/Sema.h| 12 +---
 clang/lib/Sema/SemaConcept.cpp |  2 +-
 clang/lib/Sema/SemaTemplate.cpp|  2 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 15 +++
 4 files changed, 18 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..352b26b0739ffb 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13033,11 +13033,14 @@ class Sema final : public SemaBase {
   /// instantiation arguments.
   ///
   /// \param DC In the event we don't HAVE a declaration yet, we instead 
provide
-  ///  the decl context where it will be created.  In this case, the 
`Innermost`
-  ///  should likely be provided.  If ND is non-null, this is ignored.
+  ///  the decl context where it will be created.  In this case, the \p
+  ///  Innermost should likely be provided.  If \p ND is non-null and \p
+  ///  Innermost is NULL, this is ignored.
   ///
   /// \param Innermost if non-NULL, specifies a template argument list for the
-  /// template declaration passed as ND.
+  /// template declaration passed as \p ND. The next declaration context would
+  /// be switched to \p DC if present; otherwise, it would be the semantic
+  /// declaration context of \p ND.
   ///
   /// \param RelativeToPrimary true if we should get the template
   /// arguments relative to the primary template, even when we're
@@ -13053,6 +13056,9 @@ class Sema final : public SemaBase {
   /// ForConstraintInstantiation indicates we should continue looking when
   /// encountering a lambda generic call operator, and continue looking for
   /// arguments on an enclosing class template.
+  ///
+  /// \param SkipForSpecialization when specified, any template specializations
+  /// in a traversal would be ignored.
   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
   const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
   std::optional> Innermost = std::nullopt,
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..929555e94dc35d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -1482,7 +1482,7 @@ substituteParameterMappings(Sema &S, NormalizedConstraint 
&N,
 static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
 const ConceptSpecializationExpr *CSE) {
   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  CSE->getNamedConcept(), CSE->getNamedConcept()->getLexicalDeclContext(),
+  CSE->getNamedConcept(), CSE->getNamedConcept()->getDeclContext(),
   /*Final=*/true, CSE->getTemplateArguments(),
   /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1346a4a3f0012a..e6191c8c1397bd 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5582,7 +5582,7 @@ bool Sema::CheckTemplateArgumentList(
 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
 
 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
-Template, NewContext, /*Final=*/true, SugaredConverted,
+Template, Template->getDeclContext(), /*Final=*/true, SugaredConverted,
 /*RelativeToPrimary=*/true,
 /*Pattern=*/nullptr,
 /*ForConceptInstantiation=*/true);
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index de470739ab78e7..6cc9fb0ef04b65 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -491,7 +491,8 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 // has a depth of 0.
 if (const auto *TTP = dyn_cast(CurDecl))
   HandleDefaultTempArgIntoTempTempParam(TTP, Result);
-CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
+CurDecl = DC ? Decl::castFromDeclContext(DC)
+ : Response::UseNextDecl(CurDecl).NextDecl;
   }
 
   while (!CurDecl->isFileContextDecl()) {
@@ -3242,15 +3243,13 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
-  const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
-  if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
-TemplateArgumentList *CurrentTemplateArgumentList =
-TemplateArgumentList::CreateCopy(getASTContext(),
- TemplateArg

[clang] [clang] Add nuw attribute to GEPs (PR #105496)

2024-08-28 Thread via cfe-commits

zmodem wrote:

We're seeing many test failures in Chromium after this change as well: 
https://crbug.com/362522336

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


  1   2   3   4   5   6   >